Publish 11 evaluated Astra histories with reproducible checkpoint artifacts (part 55)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S040/training_sources/beam_calibration1/core.py +36 -0
- tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S040/training_sources/beam_calibration1/export.py +11 -0
- tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S040/training_sources/beam_calibration1/fit.py +104 -0
- tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S040/training_sources/beam_calibration1/generate_beam_training.py +34 -0
- tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S040/training_sources/beam_calibration1/generate_parent_training.py +21 -0
- tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S040/training_sources/beam_calibration1/package.py +55 -0
- tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S040/training_sources/beam_calibration1/plan.json +91 -0
- tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S040/training_sources/beam_calibration1/runtime.py +37 -0
- tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S040/training_sources/beam_calibration1/runtime_control.py +42 -0
- tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S040/training_sources/beam_calibration1/verify_during_recovery.py +21 -0
- tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S040/training_sources/condition_same1/exact_d3__exact.py +213 -0
- tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S040/training_sources/condition_same1/learned_exact__data.py +73 -0
- tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S040/training_sources/condition_same1/learned_exact__gradient.py +43 -0
- tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S040/training_sources/condition_same1/learned_exact__temporal_accumulate_train.py +158 -0
- tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S040/training_sources/condition_same1/learned_exact__temporal_model.py +44 -0
- tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S040/training_sources/confidence_joint1/exact_d3__exact.py +213 -0
- tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S040/training_sources/confidence_joint1/learned_d5__confidence_joint.py +38 -0
- tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S040/training_sources/confidence_joint1/learned_d5__confidence_joint_gradient.py +43 -0
- tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S040/training_sources/confidence_joint1/learned_d5__confidence_joint_state.py +83 -0
- tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S040/training_sources/confidence_joint1/learned_d5__confidence_joint_train.py +145 -0
- tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S040/training_sources/confidence_joint1/learned_d5__data.py +95 -0
- tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S040/training_sources/confidence_joint1/learned_d5__joint_mixture.py +75 -0
- tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S040/training_sources/confidence_joint1/learned_d5__model.py +55 -0
- tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S040/training_sources/confidence_joint1/learned_exact__checkpoint_gradient.py +73 -0
- tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S040/training_sources/fresh2_full/exact_d3__exact.py +213 -0
- tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S040/training_sources/fresh2_full/learned_d5__data.py +95 -0
- tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S040/training_sources/fresh2_full/learned_d5__model.py +55 -0
- tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S040/training_sources/fresh2_full/learned_d5__train.py +176 -0
- tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S040/training_sources/fresh2_full/learned_exact__checkpoint_gradient.py +73 -0
- tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S040/training_sources/fresh2_full/learned_exact__gradient.py +43 -0
- tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S040/training_sources/fresh_specialize1/exact_d3__exact.py +213 -0
- tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S040/training_sources/fresh_specialize1/learned_exact__data.py +73 -0
- tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S040/training_sources/fresh_specialize1/learned_exact__fresh_specialize_train.py +161 -0
- tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S040/training_sources/fresh_specialize1/learned_exact__gradient.py +43 -0
- tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S040/training_sources/fresh_specialize1/learned_exact__temporal_model.py +44 -0
- tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S040/training_sources/fresh_specialize1/parent_training_provenance.json +0 -0
- tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S040/training_sources/fresh_specialize1/run_config.json +37 -0
- tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S040/training_sources/fresh_temporal1_full/exact_d3__exact.py +213 -0
- tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S040/training_sources/fresh_temporal1_full/learned_exact__data.py +73 -0
- tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S040/training_sources/fresh_temporal1_full/learned_exact__fresh_temporal_initialization.py +16 -0
- tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S040/training_sources/fresh_temporal1_full/learned_exact__fresh_temporal_train.py +140 -0
- tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S040/training_sources/fresh_temporal1_full/learned_exact__gradient.py +43 -0
- tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S040/training_sources/fresh_temporal1_full/learned_exact__model.py +21 -0
- tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S040/training_sources/fresh_temporal1_full/learned_exact__temporal_model.py +44 -0
- tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S040/training_sources/fresh_temporal1_swa/exact_d3__exact.py +213 -0
- tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S040/training_sources/fresh_temporal1_swa/learned_exact__average_fresh_temporal.py +31 -0
- tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S040/training_sources/fresh_temporal1_swa/learned_exact__data.py +73 -0
- tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S040/training_sources/fresh_temporal1_swa/learned_exact__fresh_temporal_initialization.py +16 -0
- tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S040/training_sources/fresh_temporal1_swa/learned_exact__fresh_temporal_train.py +140 -0
- tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S040/training_sources/fresh_temporal1_swa/learned_exact__gradient.py +43 -0
tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S040/training_sources/beam_calibration1/core.py
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Small logit residual with training-only feature normalization."""
|
| 2 |
+
import numpy as np
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
def logit(probability):
|
| 6 |
+
p=np.clip(np.asarray(probability,np.float64),1e-7,1-1e-7)
|
| 7 |
+
assert p.ndim==1
|
| 8 |
+
return np.log(p)-np.log1p(-p)
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def raw_features(parent,beam=None):
|
| 12 |
+
base=logit(parent);columns=[base]
|
| 13 |
+
if beam is not None:columns.append(logit(beam)-base)
|
| 14 |
+
return base,np.ascontiguousarray(np.column_stack(columns),np.float64)
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def normalize(raw,center,scale):
|
| 18 |
+
values=(raw-np.asarray(center)[None,:])/np.asarray(scale)[None,:]
|
| 19 |
+
return np.ascontiguousarray(np.column_stack([np.ones(len(raw)),values]),np.float64)
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def sigmoid(z):
|
| 23 |
+
u=np.exp(-np.abs(z));return np.where(z>=0,1/(1+u),u/(1+u))
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def objective_gradient(weights,x,base,labels,regularization):
|
| 27 |
+
y=np.asarray(labels,np.float64);z=base+np.sum(x*weights[None,:],axis=1);penalty=np.ones(len(weights));penalty[0]=.01
|
| 28 |
+
loss=float(np.mean(np.logaddexp(0,z)-y*z)+.5*regularization*np.sum(penalty*weights*weights))
|
| 29 |
+
gradient=x.T@(sigmoid(z)-y)/len(y)+regularization*penalty*weights
|
| 30 |
+
return loss,gradient
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def predict(parent,beam,state):
|
| 34 |
+
if len(state['center'])==1:beam=None
|
| 35 |
+
base,raw=raw_features(parent,beam);x=normalize(raw,state['center'],state['scale']);z=base+np.sum(x*np.asarray(state['weights'])[None,:],axis=1)
|
| 36 |
+
return sigmoid(z).astype(np.float32)
|
tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S040/training_sources/beam_calibration1/export.py
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Copy portable helpers under unique names; no data caches in the model."""
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
import hashlib,shutil
|
| 4 |
+
root=Path(__file__).resolve().parent;r=root.parent
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def install(package):
|
| 8 |
+
package=Path(package);assert not (package/'d5_prebeam_calibration_contextual.py').exists()
|
| 9 |
+
files={'d5_prebeam_calibration_contextual.py':package/'d5_contextual.py','d5_contextual.py':root/'runtime.py','beam_calibration_core.py':root/'core.py','beam_calibration_frontier.py':r/'full_frontier/beam_jax.py'}
|
| 10 |
+
for name,source in files.items():shutil.copyfile(source,package/name)
|
| 11 |
+
return {name:hashlib.sha256((package/name).read_bytes()).hexdigest() for name in files}
|
tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S040/training_sources/beam_calibration1/fit.py
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Train-only small corrections, then six prespecified global validation choices."""
|
| 2 |
+
import os
|
| 3 |
+
os.environ['OPENBLAS_NUM_THREADS']='1'
|
| 4 |
+
os.environ['OMP_NUM_THREADS']='1'
|
| 5 |
+
os.sched_setaffinity(0,sorted(os.sched_getaffinity(0))[:4])
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
import hashlib,json,time
|
| 8 |
+
import numpy as np
|
| 9 |
+
from scipy.optimize import minimize
|
| 10 |
+
from core import raw_features,normalize,objective_gradient,predict
|
| 11 |
+
|
| 12 |
+
root=Path(__file__).resolve().parent;r=root.parent
|
| 13 |
+
|
| 14 |
+
def digest(path):return hashlib.sha256(Path(path).read_bytes()).hexdigest()
|
| 15 |
+
|
| 16 |
+
def write(path,value):Path(path).write_text(json.dumps(value,indent=2)+'\n')
|
| 17 |
+
|
| 18 |
+
def aligned(path,ids,empty=False):
|
| 19 |
+
with np.load(path,allow_pickle=False) as f:
|
| 20 |
+
keys=f['sample_ids'];p=f['probabilities']
|
| 21 |
+
assert keys.dtype==np.uint64 and keys.ndim==1 and len(np.unique(keys))==len(keys)==len(ids)
|
| 22 |
+
assert p.dtype==np.float32 and p.shape==keys.shape and np.isfinite(p).all() and ((p>=0)&(p<=1)).all()
|
| 23 |
+
order=np.argsort(keys);positions=np.searchsorted(keys[order],ids);assert (positions<len(order)).all()
|
| 24 |
+
ix=order[positions];assert np.array_equal(keys[ix],ids)
|
| 25 |
+
flags=f['empty'][ix] if empty else np.zeros(len(ids),bool)
|
| 26 |
+
assert flags.dtype==bool and flags.shape==ids.shape
|
| 27 |
+
return p[ix],flags
|
| 28 |
+
|
| 29 |
+
def main():
|
| 30 |
+
started=time.time();plan=json.loads((root/'plan.json').read_text());lock=json.loads((root/'FIT_SOURCE_LOCK.json').read_text())
|
| 31 |
+
while not all((root/k/'provenance.json').exists() for k in ['beam_training','parent_training']):
|
| 32 |
+
if time.time()-started>14400:raise TimeoutError('Training evidence incomplete')
|
| 33 |
+
time.sleep(2)
|
| 34 |
+
for path,sha in lock['source_sha256'].items():assert digest(r/path)==sha,path
|
| 35 |
+
assert json.loads((root/'control_cpu.json').read_text())['status']=='passed'
|
| 36 |
+
output=root/'fit1';output.mkdir(exist_ok=False);train=Path('/workspace/data/train');validation=Path('/workspace/data/validation')
|
| 37 |
+
train_rows={x['name']:x for x in json.loads((train/'manifest.json').read_text())['conditions']}
|
| 38 |
+
val_rows={x['name']:x for x in json.loads((validation/'manifest.json').read_text())['conditions']}
|
| 39 |
+
generation={k:json.loads((root/k/'provenance.json').read_text()) for k in ['beam_training','parent_training']}
|
| 40 |
+
reference=plan['reference'];package=Path(reference['current']['package'])
|
| 41 |
+
for filename,key in [('model_manifest.json','parent_manifest_sha256'),('model_config.json','parent_config_sha256'),('training_provenance.json','parent_provenance_sha256')]:assert digest(package/filename)==reference[key]
|
| 42 |
+
assert digest(r/'full_frontier/beam_lookahead.py')==plan['training_beam_source_sha256']
|
| 43 |
+
data={};audit=[]
|
| 44 |
+
# Validate every ID and file before any hardware-label member is opened here.
|
| 45 |
+
for name in plan['conditions']:
|
| 46 |
+
row=train_rows[name];path=train/row['arrays'];assert digest(path)==row['arrays_sha256']
|
| 47 |
+
with np.load(path,allow_pickle=False) as f:ids=f['sample_ids']
|
| 48 |
+
assert len(ids)==19880 and len(np.unique(ids))==len(ids)
|
| 49 |
+
arrays={};files={}
|
| 50 |
+
for kind in generation:
|
| 51 |
+
record=next(z for z in generation[kind]['records'] if z['condition']==name);cache=root/kind/(name+'.npz')
|
| 52 |
+
assert record['arrays_sha256']==row['arrays_sha256'] and record['shots']==len(ids)
|
| 53 |
+
assert digest(cache)==record['output_sha256'];files[kind]=record['output_sha256']
|
| 54 |
+
arrays[kind]=aligned(cache,ids,empty=kind=='beam_training')
|
| 55 |
+
parent=arrays['parent_training'][0];beam,empty=arrays['beam_training'];beam[empty]=parent[empty]
|
| 56 |
+
data[name]={'ids':ids,'parent':parent,'beam':beam}
|
| 57 |
+
audit.append({'condition':name,'shots':len(ids),'all_ids_exact_by_value':True,'arrays_sha256':row['arrays_sha256'],'cache_sha256':files,'empty_fallbacks':int(empty.sum())})
|
| 58 |
+
write(output/'training_evidence_audit.json',{'status':'passed','conditions':audit,'training_rows':sum(len(z['ids']) for z in data.values()),'label_members_opened':False,'test_data_used':False})
|
| 59 |
+
initial={basis:np.random.default_rng(seed).normal(0,.001,3) for basis,seed in plan['initial_seeds'].items()}
|
| 60 |
+
np.savez(output/'initial_weights.npz',**initial)
|
| 61 |
+
# All optimization and normalization are complete before validation labels.
|
| 62 |
+
fits=[]
|
| 63 |
+
for arm in plan['arms']:
|
| 64 |
+
for lam in plan['regularization']:
|
| 65 |
+
name=f'{arm}_lambda{lam:g}';folder=output/name;folder.mkdir();conditions=[]
|
| 66 |
+
for condition in plan['conditions']:
|
| 67 |
+
row=train_rows[condition];d=data[condition]
|
| 68 |
+
with np.load(train/row['arrays'],allow_pickle=False) as f:
|
| 69 |
+
assert np.array_equal(f['sample_ids'],d['ids']);y=f['labels'].astype(np.float64)
|
| 70 |
+
assert y.shape==d['ids'].shape and np.isin(y,[0,1]).all()
|
| 71 |
+
base,raw=raw_features(d['parent'],None if arm=='parent_only' else d['beam']);center=raw.mean(axis=0);scale=np.maximum(raw.std(axis=0),.05);x=normalize(raw,center,scale)
|
| 72 |
+
w0=initial[row['basis']][:x.shape[1]].copy();initial_loss=objective_gradient(w0,x,base,y,lam)[0]
|
| 73 |
+
result=minimize(objective_gradient,w0,args=(x,base,y,lam),method='L-BFGS-B',jac=True,options={'maxiter':500,'gtol':1e-8,'ftol':1e-12})
|
| 74 |
+
assert result.success and np.isfinite(result.x).all(),str(result)
|
| 75 |
+
state={'condition':condition,'arm':arm,'regularization':lam,'center':center.tolist(),'scale':scale.tolist(),'weights':result.x.tolist()};write(folder/(condition+'.json'),state)
|
| 76 |
+
q=predict(d['parent'],d['beam'],state);qc=np.clip(q.astype(float),1e-7,1-1e-7)
|
| 77 |
+
conditions.append({'condition':condition,'shots':len(y),'initial_weights':w0.tolist(),'initial_objective':initial_loss,'final_objective':float(result.fun),'optimizer_iterations':int(result.nit),'function_evaluations':int(result.nfev),'optimizer_message':str(result.message),'gradient_max_abs':float(np.abs(result.jac).max()),'training_failure':float(((q>=.5)!=y).mean()),'training_nll':float((-y*np.log(qc)-(1-y)*np.log1p(-qc)).mean()),'state':state})
|
| 78 |
+
fits.append({'name':name,'arm':arm,'regularization':lam,'conditions':conditions})
|
| 79 |
+
write(output/'training.json',{'status':'complete','declared_plan':plan,'fits':fits,'initial_weights_sha256':digest(output/'initial_weights.npz'),'selection_data_opened':False,'source_lock':lock,'test_data_used':False})
|
| 80 |
+
# Existing validation beams were generated before their labels; they have no empty cases.
|
| 81 |
+
validation_report=json.loads((r/'full_frontier/r3_assessment1/report.json').read_text());val={}
|
| 82 |
+
for condition in plan['conditions']:
|
| 83 |
+
row=val_rows[condition];path=validation/row['arrays'];assert digest(path)==row['arrays_sha256']
|
| 84 |
+
with np.load(path,allow_pickle=False) as f:ids=f['sample_ids'];y=f['labels'].astype(np.float64)
|
| 85 |
+
assert len(ids)==5120 and len(np.unique(ids))==len(ids) and y.shape==ids.shape and np.isin(y,[0,1]).all()
|
| 86 |
+
beam_path=r/'full_frontier/r3_assessment1/beam_predictions'/(condition+'.npz');record=next(z for z in validation_report['generation'] if z['condition']==condition)
|
| 87 |
+
assert digest(beam_path)==record['prediction_sha256'] and record['empty_fallbacks']==0
|
| 88 |
+
beam,_=aligned(beam_path,ids);parent,_=aligned(Path(reference['current']['predictions'])/(condition+'.npz'),ids)
|
| 89 |
+
val[condition]={'ids':ids,'y':y,'parent':parent,'beam':beam}
|
| 90 |
+
assessments=[]
|
| 91 |
+
for fit in fits:
|
| 92 |
+
conditions=[];folder=output/fit['name']/'validation_predictions';folder.mkdir();variance=0.
|
| 93 |
+
for item in fit['conditions']:
|
| 94 |
+
condition=item['condition'];d=val[condition];q=predict(d['parent'],d['beam'],item['state']);y=d['y'];old=(d['parent']>=.5)!=y;new=(q>=.5)!=y;diff=old.astype(int)-new.astype(int);qc=np.clip(q.astype(float),1e-7,1-1e-7)
|
| 95 |
+
np.savez(folder/(condition+'.npz'),sample_ids=d['ids'],probabilities=q)
|
| 96 |
+
gain=float(diff.mean()/52);variance+=float(diff.var(ddof=1)/len(y)/52**2)
|
| 97 |
+
conditions.append({'condition':condition,'failure':float(new.mean()),'parent_failure':float(old.mean()),'nll':float((-y*np.log(qc)-(1-y)*np.log1p(-qc)).mean()),'corrected':int((old&~new).sum()),'introduced':int((~old&new).sum()),'P_gain':gain})
|
| 98 |
+
gain=sum(z['P_gain'] for z in conditions);assessments.append({'name':fit['name'],'arm':fit['arm'],'regularization':fit['regularization'],'conditions':conditions,'net_corrected':sum(z['corrected']-z['introduced'] for z in conditions),'P_gain':gain,'expected_full_P':reference['current']['P']+gain,'paired_naive_P_standard_error':variance**.5})
|
| 99 |
+
# Fixed ordering resolves exact ties; no basis-specific selection.
|
| 100 |
+
best=max(assessments,key=lambda x:x['expected_full_P'])
|
| 101 |
+
report={'status':'complete','assessments':assessments,'selected':best if best['P_gain']>0 else None,'reference_P':reference['current']['P'],'seconds':time.time()-started,'scope':'Six prespecified global choices across both d5r3 conditions, all other128 retained. Expected score only, no actual exported replay or publication yet. Standard errors omit selection and shot dependence. Compare then-current incumbent before any publication.','test_data_used':False}
|
| 102 |
+
write(output/'report.json',report);print(json.dumps(report,indent=2),flush=True)
|
| 103 |
+
|
| 104 |
+
if __name__=='__main__':main()
|
tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S040/training_sources/beam_calibration1/generate_beam_training.py
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""CPU fullbeam training evidence, with no hardware logical-label access."""
|
| 2 |
+
import os
|
| 3 |
+
os.environ['OPENBLAS_NUM_THREADS']='1';os.environ['OMP_NUM_THREADS']='1'
|
| 4 |
+
available=sorted(os.sched_getaffinity(0));os.sched_setaffinity(0,available[4:20] if len(available)>=20 else available[:16])
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
import hashlib,json,multiprocessing,sys,time
|
| 7 |
+
import numpy as np
|
| 8 |
+
root=Path(__file__).resolve().parent;r=root.parent;sys.path.insert(0,str(r/'full_frontier'))
|
| 9 |
+
from beam_lookahead import prepare_lookahead,decode
|
| 10 |
+
PLAN=None;LOOK=None
|
| 11 |
+
|
| 12 |
+
def initialize(path):
|
| 13 |
+
global PLAN,LOOK
|
| 14 |
+
with np.load(path,allow_pickle=False) as f:PLAN={k:f[k] for k in f.files}
|
| 15 |
+
LOOK=prepare_lookahead(PLAN)
|
| 16 |
+
|
| 17 |
+
def work(ds):
|
| 18 |
+
q,report=decode(PLAN,ds,per_sector=512,lookahead=LOOK)
|
| 19 |
+
return float(q),report['status']=='empty_beam'
|
| 20 |
+
|
| 21 |
+
def main():
|
| 22 |
+
declared=json.loads((root/'plan.json').read_text());out=root/'beam_training';out.mkdir(exist_ok=False);records=[];rows=[z for z in json.loads(Path('/workspace/data/train/manifest.json').read_text())['conditions'] if z['distance']==5 and z['rounds']==3];started=time.time()
|
| 23 |
+
for row in rows:
|
| 24 |
+
with np.load(Path('/workspace/data/train')/row['arrays'],allow_pickle=False) as f:ids=f['sample_ids'];packed=f['detectors']
|
| 25 |
+
ds=np.unpackbits(packed,axis=1,count=row['num_detectors'],bitorder='little');values=[];flags=[];begin=time.time();context=multiprocessing.get_context('spawn');path=r/'full_frontier/plans'/(row['name']+'.npz')
|
| 26 |
+
with context.Pool(16,initializer=initialize,initargs=(path,)) as pool:
|
| 27 |
+
for index,(q,empty) in enumerate(pool.imap(work,ds,chunksize=8),start=1):
|
| 28 |
+
values.append(q);flags.append(empty)
|
| 29 |
+
if index%1024==0:print(json.dumps({'condition':row['name'],'completed':index,'total':len(ids),'seconds':time.time()-begin}),flush=True)
|
| 30 |
+
q=np.asarray(values,np.float32);empty=np.asarray(flags,bool);assert np.isfinite(q).all() and ((q>=0)&(q<=1)).all();output=out/(row['name']+'.npz');np.savez(output,sample_ids=ids,probabilities=q,empty=empty)
|
| 31 |
+
records.append({'condition':row['name'],'shots':len(ids),'empty_count':int(empty.sum()),'seconds':time.time()-begin,'output_sha256':hashlib.sha256(output.read_bytes()).hexdigest(),'arrays_sha256':row['arrays_sha256'],'schedule_sha256':hashlib.sha256(path.read_bytes()).hexdigest()})
|
| 32 |
+
report={'status':'complete','records':records,'seconds':time.time()-started,'scope':'All39760 supplied d5r3training syndromes, K512float64beam/float32savedprobabilities. No hardware logical-label member read. Empty flags saved for fallback to frozen parent in fitting/runtime. No model fitting or GPUwork.','test_data_used':False,'source_sha256':{str(p.relative_to(r)):hashlib.sha256(p.read_bytes()).hexdigest() for p in [Path(__file__).resolve(),r/'full_frontier/beam_lookahead.py']}};(out/'provenance.json').write_text(json.dumps(report,indent=2)+'\n')
|
| 33 |
+
|
| 34 |
+
if __name__=='__main__':main()
|
tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S040/training_sources/beam_calibration1/generate_parent_training.py
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Frozen own-parent probabilities using cached physical priors; labels unopened."""
|
| 2 |
+
import os
|
| 3 |
+
os.environ['JAX_PLATFORMS']='cpu';os.environ['OPENBLAS_NUM_THREADS']='1';os.environ['OMP_NUM_THREADS']='4'
|
| 4 |
+
os.sched_setaffinity(0,sorted(os.sched_getaffinity(0))[:4])
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
import hashlib,json,sys,time
|
| 7 |
+
import numpy as np
|
| 8 |
+
root=Path(__file__).resolve().parent;r=root.parent;reference=json.loads((r/'beam_r3/reference.json').read_text());package=Path(reference['current']['package']);config=json.loads((package/'model_config.json').read_text());sys.path.insert(0,str(package))
|
| 9 |
+
from d5_contextual import NeuralD5Decoder
|
| 10 |
+
out=root/'parent_training';out.mkdir(exist_ok=False);decoder=NeuralD5Decoder();records=[];started=time.time()
|
| 11 |
+
for row in [x for x in json.loads(Path('/workspace/data/train/manifest.json').read_text())['conditions'] if x['distance']==5 and x['rounds']==3]:
|
| 12 |
+
settings=config['neural_d5'][row['group']];passes=settings['prior_pass'];cache=r/('learned_d5/full_training_priors3' if passes==3 else 'full_prior5/cache1')/(row['name']+'.npz')
|
| 13 |
+
with np.load(Path('/workspace/data/train')/row['arrays'],allow_pickle=False) as f:ids=f['sample_ids'];packed=f['detectors']
|
| 14 |
+
with np.load(cache,allow_pickle=False) as f:assert np.array_equal(f['sample_ids'],ids) and np.array_equal(f['indices'],np.arange(len(ids)));prior=f[f'priors{passes}']
|
| 15 |
+
parts=[];begin=time.time()
|
| 16 |
+
for start in range(0,len(ids),128):
|
| 17 |
+
parts.append(decoder.predict(package,config['conditions'][row['name']],settings,packed[start:start+128],row['num_detectors'],batch=128,initial_priors=prior[start:start+128]))
|
| 18 |
+
if start//128%16==0:print(json.dumps({'condition':row['name'],'completed':min(start+128,len(ids)),'total':len(ids),'seconds':time.time()-begin}),flush=True)
|
| 19 |
+
q=np.concatenate(parts).astype(np.float32);assert np.isfinite(q).all() and ((q>=0)&(q<=1)).all();path=out/(row['name']+'.npz');np.savez(path,sample_ids=ids,probabilities=q)
|
| 20 |
+
records.append({'condition':row['name'],'shots':len(ids),'prior_pass':passes,'arrays_sha256':row['arrays_sha256'],'prior_cache_sha256':hashlib.sha256(cache.read_bytes()).hexdigest(),'output_sha256':hashlib.sha256(path.read_bytes()).hexdigest(),'seconds':time.time()-begin})
|
| 21 |
+
report={'status':'complete','reference':reference,'records':records,'seconds':time.time()-started,'scope':'All39760 supplied d5r3training syndromes with ownfrozenr3publication; cachedphysicalpriors allIDschecked, no labelmembers opened. CPUbatch128, no optimizerupdates.','test_data_used':False,'source_sha256':hashlib.sha256(Path(__file__).read_bytes()).hexdigest()};(out/'provenance.json').write_text(json.dumps(report,indent=2)+'\n')
|
tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S040/training_sources/beam_calibration1/package.py
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Assemble the selected global r3 correction on the then-current incumbent."""
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
import hashlib,json,shutil
|
| 4 |
+
from export import install
|
| 5 |
+
root=Path(__file__).resolve().parent;r=root.parent
|
| 6 |
+
|
| 7 |
+
def digest(path):return hashlib.sha256(Path(path).read_bytes()).hexdigest()
|
| 8 |
+
|
| 9 |
+
def assemble():
|
| 10 |
+
plan=json.loads((root/'plan.json').read_text());report=json.loads((root/'fit1/report.json').read_text());selected=report['selected'];assert selected is not None
|
| 11 |
+
reference=plan['reference'];reference_package=Path(reference['current']['package']);reference_config=json.loads((reference_package/'model_config.json').read_text())
|
| 12 |
+
current=json.loads((r/'CURRENT.json').read_text());score=json.loads(Path(current['score']).read_text());out=r/'context_upgrades/beam_calibration1';out.mkdir(exist_ok=False);package=out/'package';predictions=out/'predictions'
|
| 13 |
+
shutil.copytree(current['package'],package);shutil.copytree(current['predictions'],predictions);config=json.loads((package/'model_config.json').read_text());folder=root/'fit1'/selected['name'];new_files=set();parent_copies={};history=[]
|
| 14 |
+
rows={z['name']:z for z in json.loads(Path('/workspace/data/validation/manifest.json').read_text())['conditions']};(package/'beam_calibration').mkdir()
|
| 15 |
+
def parent_copy(value,basis):
|
| 16 |
+
if isinstance(value,dict):
|
| 17 |
+
result={}
|
| 18 |
+
for key,entry in value.items():
|
| 19 |
+
if key=='weights':
|
| 20 |
+
relative=f'weights/beam-calibration-parent-{basis}-{len(parent_copies)}.npz';shutil.copyfile(reference_package/entry,package/relative);new_files.add(relative);parent_copies[relative]={'original_relative_path':entry,'sha256':digest(package/relative)};result[key]=relative
|
| 21 |
+
else:result[key]=parent_copy(entry,basis)
|
| 22 |
+
return result
|
| 23 |
+
if isinstance(value,list):return [parent_copy(x,basis) for x in value]
|
| 24 |
+
return value
|
| 25 |
+
gain=0.
|
| 26 |
+
for assessment in selected['conditions']:
|
| 27 |
+
name=assessment['condition'];row=rows[name];group=row['group'];record=config['conditions'][name]
|
| 28 |
+
assert not config['neural_d5'][group].get('blend_turbo',False) and group not in config.get('frozen_stack',{})
|
| 29 |
+
for key in ['neural_d5_plan','plan','turbo_plan','conditional_plan']:
|
| 30 |
+
if key in record:assert digest(package/record[key])==digest(reference_package/reference_config['conditions'][name][key]),(name,key)
|
| 31 |
+
state_relative='beam_calibration/'+name+'.json';shutil.copyfile(folder/(name+'.json'),package/state_relative);new_files.add(state_relative)
|
| 32 |
+
option={'state':state_relative,'parent':parent_copy(reference_config['neural_d5'][group],row['basis'])}
|
| 33 |
+
if selected['arm']=='parent_plus_beam':
|
| 34 |
+
relative='beam_calibration/'+name+'.npz';shutil.copyfile(r/'beam_r3/plans'/(name+'.npz'),package/relative);new_files.add(relative);option.update(plan=relative,per_sector_states=512)
|
| 35 |
+
config['neural_d5'][group]['beam_calibration']={record['neural_d5_plan']:option}
|
| 36 |
+
shutil.copyfile(folder/'validation_predictions'/(name+'.npz'),predictions/(name+'.npz'))
|
| 37 |
+
incumbent=score['per_condition'][name]['errors']/score['per_condition'][name]['total'];gain+=(incumbent-assessment['failure'])/52
|
| 38 |
+
history.append({'condition':name,'then_current_failure':incumbent,'candidate_failure':assessment['failure'],'global_arm':selected['arm'],'global_regularization':selected['regularization']})
|
| 39 |
+
expected=current['P']+gain
|
| 40 |
+
assert expected>current['P']+1e-12,'Candidate no longer improves the incumbent'
|
| 41 |
+
runtime=install(package);training_sources=package/'training_sources/beam_calibration1';training_sources.mkdir()
|
| 42 |
+
for filename in ['core.py','fit.py','generate_beam_training.py','generate_parent_training.py','control_cpu.py','runtime_control.py','runtime.py','export.py','package.py','after_resource.py','plan.json','FIT_SOURCE_LOCK.json','PACKAGE_SOURCE_LOCK.json']:
|
| 43 |
+
shutil.copyfile(root/filename,training_sources/filename)
|
| 44 |
+
for filename in ['beam_lookahead.py','beam_cpu.py']:shutil.copyfile(r/'full_frontier'/filename,training_sources/filename)
|
| 45 |
+
config['architecture']='Contextual exact d3 and d5 decoders with a selected train-fitted r3 logit correction'
|
| 46 |
+
(package/'model_config.json').write_text(json.dumps(config,indent=2)+'\n')
|
| 47 |
+
provenance=json.loads((package/'training_provenance.json').read_text());provenance['beam_calibration1']={'declared_plan':plan,'training':json.loads((root/'fit1/training.json').read_text()),'training_evidence_audit':json.loads((root/'fit1/training_evidence_audit.json').read_text()),'evidence_generation':{kind:json.loads((root/kind/'provenance.json').read_text()) for kind in ['beam_training','parent_training']},'six_global_selection_results':report,'then_current_selection':history,'frozen_parent_weight_copies':parent_copies,'runtime_export_sha256':runtime,'controls':{name:json.loads((root/name).read_text()) for name in ['control_cpu.json','runtime_control_cpu.json','runtime_control_gpu.json']},'test_data_used':False}
|
| 48 |
+
provenance['previous_package_validation']=provenance.pop('package_validation');(package/'training_provenance.json').write_text(json.dumps(provenance,indent=2)+'\n')
|
| 49 |
+
with (package/'README.md').open('a') as f:f.write('\nThe selected d5 three-round correction fits a small regularized logit model on all39,760 corresponding training shots. Parent-only and parent-plus-full-DEM-beam arms were compared with three fixed regularization values globally across both bases. The parent networks are frozen session-trained models. Feature normalization uses training only, and sample IDs never enter the model. Inference computes all evidence from input syndromes and packaged geometry; no cached predictions are packaged.\n')
|
| 50 |
+
manifest=json.loads((package/'model_manifest.json').read_text());paths={z['path'] for z in manifest['checkpoints']}|new_files
|
| 51 |
+
manifest['checkpoints']=[{'path':p,'sha256':digest(package/p),'format':'npz' if p.endswith('.npz') else 'json' if p.endswith('.json') else 'stim-dem'} for p in sorted(paths)];(package/'model_manifest.json').write_text(json.dumps(manifest,indent=2)+'\n')
|
| 52 |
+
candidate={'package':str(package),'predictions':str(predictions),'score':str(out/'score.json'),'expected_P':expected,'selection':history,'validation_metadata':{'prediction_generation':'Two cached calibration predictions replace the corresponding incumbent conditions; all26d5 actual replay required before publication.','runtime_evidence':'Full actual d5 replay and workload projection remain required; optional beam adds inference cost.'}}
|
| 53 |
+
(out/'candidate.json').write_text(json.dumps(candidate,indent=2)+'\n');print(json.dumps(candidate,indent=2),flush=True)
|
| 54 |
+
|
| 55 |
+
if __name__=='__main__':assemble()
|
tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S040/training_sources/beam_calibration1/plan.json
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"name": "beam_calibration1",
|
| 3 |
+
"status": "Declared before fitting; training evidence caches starting CPUonly",
|
| 4 |
+
"created_utc": "2026-10-21T20:21:49.646611+00:00",
|
| 5 |
+
"hypothesis": "The fullDEM beam supplies complementary probabilities but raw/equalr3globalchoices failed. Fit a small train-only correction; matchedparent-only arm identifies whether beam is needed. No accuracy improvement claimed.",
|
| 6 |
+
"reference": {
|
| 7 |
+
"current": {
|
| 8 |
+
"package": "/run-state/workspace/research/context_upgrades/r3_pattern1/package",
|
| 9 |
+
"predictions": "/run-state/workspace/research/context_upgrades/r3_pattern1/predictions",
|
| 10 |
+
"score": "/run-state/workspace/research/context_upgrades/r3_pattern1/score.json",
|
| 11 |
+
"P": 0.76744384765625
|
| 12 |
+
},
|
| 13 |
+
"records": [
|
| 14 |
+
{
|
| 15 |
+
"condition": "surface_code_bX_d5_r03_center_5_5",
|
| 16 |
+
"group": "d5_bX_center_5_5",
|
| 17 |
+
"record": {
|
| 18 |
+
"dem": "dems/surface_code_bX_d5_r03_center_5_5.dem",
|
| 19 |
+
"circuit_sha256": "1cbfca6766d1e142e35233b2cbeeb039f41aebf5179c46acbd45824d928a78a6",
|
| 20 |
+
"conditional_plan": "conditional_plans/surface_code_bX_d5_r03_center_5_5.npz",
|
| 21 |
+
"turbo_plan": "turbo_plans/surface_code_bX_d5_r03_center_5_5.npz",
|
| 22 |
+
"neural_d5_plan": "neural_d5_plans/surface_code_bX_d5_r03_center_5_5.npz"
|
| 23 |
+
},
|
| 24 |
+
"parent_settings": {
|
| 25 |
+
"confidence_joint": {
|
| 26 |
+
"weights": "weights/confidence-joint1-1024.npz"
|
| 27 |
+
},
|
| 28 |
+
"prior_pass": 3,
|
| 29 |
+
"blend_turbo": false
|
| 30 |
+
},
|
| 31 |
+
"plan_file": "plans/surface_code_bX_d5_r03_center_5_5.npz",
|
| 32 |
+
"plan_sha256": "cc763f0638add95aa03f2b76b5acf8dcceb470de00182d6804366e3bfa0e3f0d",
|
| 33 |
+
"source_schedule_sha256": "12e9b86c551a382dade82f1a1e3efe5aa26aa29edabd0e906607c2bde8b7dfc8",
|
| 34 |
+
"source_DEM_sha256": "b0f53a8924b9c471b5f574382d8162f5eef40e5003a85a15fcb62335a0af0e4c"
|
| 35 |
+
},
|
| 36 |
+
{
|
| 37 |
+
"condition": "surface_code_bZ_d5_r03_center_5_5",
|
| 38 |
+
"group": "d5_bZ_center_5_5",
|
| 39 |
+
"record": {
|
| 40 |
+
"dem": "dems/surface_code_bZ_d5_r03_center_5_5.dem",
|
| 41 |
+
"circuit_sha256": "12b124311b84adfeeb4aa4e61b9b11707691692ee807a13cfd90ee73cf733f6c",
|
| 42 |
+
"conditional_plan": "conditional_plans/surface_code_bZ_d5_r03_center_5_5.npz",
|
| 43 |
+
"turbo_plan": "turbo_plans/surface_code_bZ_d5_r03_center_5_5.npz",
|
| 44 |
+
"neural_d5_plan": "neural_d5_plans/surface_code_bZ_d5_r03_center_5_5.npz"
|
| 45 |
+
},
|
| 46 |
+
"parent_settings": {
|
| 47 |
+
"weights": "weights/prior-pass1-pass5-0.npz",
|
| 48 |
+
"prior_pass": 5,
|
| 49 |
+
"blend_turbo": false,
|
| 50 |
+
"training_checkpoint": "prior_pass1/pass5/0"
|
| 51 |
+
},
|
| 52 |
+
"plan_file": "plans/surface_code_bZ_d5_r03_center_5_5.npz",
|
| 53 |
+
"plan_sha256": "3a6746481fe2953c4b5b7615b365fccfcee538ff1b8fadc910420fb0f9ba681d",
|
| 54 |
+
"source_schedule_sha256": "abebe153fc07da35e24b4f5e7aa7278896c2bb632a7d094ca95bcbaa58163ed7",
|
| 55 |
+
"source_DEM_sha256": "ed3409474d22d849cdc7b3deb9ded28d70aeff4a53cfb4a56a0d7411f5b57f88"
|
| 56 |
+
}
|
| 57 |
+
],
|
| 58 |
+
"parent_manifest_sha256": "112a3c67e31cae326474ee93b1454382c8a14cc59900ff86344113d727fe4ce0",
|
| 59 |
+
"parent_config_sha256": "35badea7d1c73ab42edcb1193eff22613ad6f8aa0d8281596fe2c1fd78d73925",
|
| 60 |
+
"parent_provenance_sha256": "953d23dedc55520b654852a848cca45c0e555be23ff433f1368c5b5de1580df8",
|
| 61 |
+
"scope": "Nonlearned fullDEM schedules from authorized inputs, combined only with own session-trained parent. No syndrome/label/ID rows or predictions serialized as model state.",
|
| 62 |
+
"test_data_used": false
|
| 63 |
+
},
|
| 64 |
+
"training_rows": 39760,
|
| 65 |
+
"conditions": [
|
| 66 |
+
"surface_code_bX_d5_r03_center_5_5",
|
| 67 |
+
"surface_code_bZ_d5_r03_center_5_5"
|
| 68 |
+
],
|
| 69 |
+
"beam_states_per_sector": 512,
|
| 70 |
+
"arms": [
|
| 71 |
+
"parent_only",
|
| 72 |
+
"parent_plus_beam"
|
| 73 |
+
],
|
| 74 |
+
"regularization": [
|
| 75 |
+
0.0001,
|
| 76 |
+
0.001,
|
| 77 |
+
0.01
|
| 78 |
+
],
|
| 79 |
+
"initial_seeds": {
|
| 80 |
+
"X": 20262100,
|
| 81 |
+
"Z": 20262101
|
| 82 |
+
},
|
| 83 |
+
"initialization": "Three coefficients perbasis drawnNormal(0,.001); parent_only uses firsttwo ofsameinitialvector, parent_plus_beam allthree. Eachlambda startsfromsamebasisinitialarray. No expert weights updated.",
|
| 84 |
+
"features": "Base offset logit(parent). Features parentlogit and beamlogit-minus-parentlogit, bothprobabilities clipped1e-7..1-1e-7 in float64. Center/scale fit onlyontraining, scalefloor.05; prependbias. Parent_only usesbiasandparentfeature.",
|
| 85 |
+
"loss": "Mean logicalBCE +.5lambda sum(weights^2*[.01,1,1]); independent perbasisfits, fullbatchL-BFGS-B max500,gtol1e-8,ftol1e-12.",
|
| 86 |
+
"selection": "Sixglobal(arm,lambda)choices across bothd5r3conditions againstfrozenownpublishedreference, full5120validationrows each; other128conditionsretained. No perbasisarm/lambdaselection. ActualGPU/portable/fullreplay/trustedscore/relocation/runtimebudgetrequired beforepublication; comparethen-currentstrongest.",
|
| 87 |
+
"fallback": "Emptybeam usesfrozenparent probability before featureconstruction. Parent_onlydoesnotexecute a beam ininference.",
|
| 88 |
+
"test_data_used": false,
|
| 89 |
+
"training_beam_source_sha256": "557ea3eef701c480b90896cda3e8f69e263bc852fcce805f054a90e43d7cffe5",
|
| 90 |
+
"reference_sha256": "9f0bbe90c63da1d9a13a27b9ecb61b07d689c64cc41055ba2c812e5b013c2701"
|
| 91 |
+
}
|
tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S040/training_sources/beam_calibration1/runtime.py
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Portable train-fitted logit correction, with optional full-DEM beam evidence."""
|
| 2 |
+
import json
|
| 3 |
+
import numpy as np
|
| 4 |
+
from d5_prebeam_calibration_contextual import NeuralD5Decoder as PreviousDecoder
|
| 5 |
+
from beam_calibration_core import predict as calibrate
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class NeuralD5Decoder(PreviousDecoder):
|
| 9 |
+
def __init__(self):
|
| 10 |
+
super().__init__();self.beam_calibration_states={};self.beam_calibration_engines={}
|
| 11 |
+
|
| 12 |
+
def predict(self,root,record,settings,packed,num_detectors,batch=512,initial_priors=None,**kwargs):
|
| 13 |
+
option=settings.get('beam_calibration',{}).get(record.get('neural_d5_plan',''))
|
| 14 |
+
if option is None:return super().predict(root,record,settings,packed,num_detectors,batch,initial_priors=initial_priors,**kwargs)
|
| 15 |
+
state_path=option['state']
|
| 16 |
+
if state_path not in self.beam_calibration_states:
|
| 17 |
+
state=json.loads((root/state_path).read_text());width=len(state['center'])
|
| 18 |
+
assert width in [1,2] and len(state['scale'])==width and len(state['weights'])==width+1
|
| 19 |
+
assert np.isfinite(np.array(state['weights']+state['center']+state['scale'])).all() and (np.array(state['scale'])>0).all()
|
| 20 |
+
self.beam_calibration_states[state_path]=state
|
| 21 |
+
state=self.beam_calibration_states[state_path];parent_settings=option['parent']
|
| 22 |
+
parent_priors=initial_priors if settings.get('prior_pass')==parent_settings.get('prior_pass') else None
|
| 23 |
+
parent=super().predict(root,record,parent_settings,packed,num_detectors,batch,initial_priors=parent_priors,**kwargs)
|
| 24 |
+
if len(state['center'])==1:return calibrate(parent,None,state)
|
| 25 |
+
import jax
|
| 26 |
+
from beam_calibration_frontier import make_decoder
|
| 27 |
+
path=option['plan'];states=int(option['per_sector_states']);assert states==512
|
| 28 |
+
if path not in self.beam_calibration_engines:
|
| 29 |
+
with np.load(root/path,allow_pickle=False) as f:plan={k:f[k] for k in f.files}
|
| 30 |
+
assert int(plan['num_detectors'])==num_detectors and int(plan['width'])<=30
|
| 31 |
+
fn=make_decoder(int(plan['width']),states);arguments=[jax.device_put(plan[k]) for k in ['probabilities','masks','measured','detector_lookup','future','active']]
|
| 32 |
+
self.beam_calibration_engines[path]=(fn,arguments)
|
| 33 |
+
fn,arguments=self.beam_calibration_engines[path];dets=np.unpackbits(packed,axis=1,count=num_detectors,bitorder='little');parts=[];flags=[]
|
| 34 |
+
for start in range(0,len(dets),batch):
|
| 35 |
+
ds=dets[start:start+batch];n=len(ds);ds=np.pad(ds,((0,batch-n),(0,0)));q,empty=fn(ds,*arguments);parts.append(np.asarray(q)[:n]);flags.append(np.asarray(empty)[:n])
|
| 36 |
+
beam=np.concatenate(parts).astype(np.float32);empty=np.concatenate(flags);beam[empty]=parent[empty]
|
| 37 |
+
return calibrate(parent,beam,state)
|
tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S040/training_sources/beam_calibration1/runtime_control.py
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Portable numerical composition with nonzero synthetic correction coefficients."""
|
| 2 |
+
import os,argparse
|
| 3 |
+
p=argparse.ArgumentParser();p.add_argument('--device',choices=['cpu','gpu'],default='cpu');args=p.parse_args()
|
| 4 |
+
os.environ['JAX_PLATFORMS']='cpu' if args.device=='cpu' else 'cuda';os.environ['OPENBLAS_NUM_THREADS']='1';os.environ['OMP_NUM_THREADS']='1';os.environ['XLA_PYTHON_CLIENT_PREALLOCATE']='false'
|
| 5 |
+
os.sched_setaffinity(0,sorted(os.sched_getaffinity(0))[:(4 if args.device=='cpu' else 22)])
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
import hashlib,importlib.util,json,shutil,sys,tempfile,time
|
| 8 |
+
import numpy as np
|
| 9 |
+
import jax
|
| 10 |
+
from export import install
|
| 11 |
+
from core import predict
|
| 12 |
+
root=Path(__file__).resolve().parent;r=root.parent;reference=json.loads((root/'plan.json').read_text())['reference'];package=Path(reference['current']['package']);config=json.loads((package/'model_config.json').read_text());probes=json.loads((r/'full_frontier/uncertain_r3_probes.json').read_text())['records'];numeric=json.loads((r/'full_frontier/beam_uncertain_r3_cpu.json').read_text())['records'];rows=json.loads(Path('/workspace/data/train/manifest.json').read_text())['conditions'];checks=[];batch=4 if args.device=='cpu' else 512
|
| 13 |
+
assert jax.default_backend()==args.device
|
| 14 |
+
with tempfile.TemporaryDirectory(prefix='beam-calibration-control-') as temporary:
|
| 15 |
+
target=Path(temporary)/'package';shutil.copytree(package,target);exported=install(target);(target/'beam_calibration').mkdir();sys.path.insert(0,str(target))
|
| 16 |
+
from d5_prebeam_calibration_contextual import NeuralD5Decoder as Old
|
| 17 |
+
spec=importlib.util.spec_from_file_location('calibration_export_control',target/'d5_contextual.py');module=importlib.util.module_from_spec(spec);spec.loader.exec_module(module);old,new=Old(),module.NeuralD5Decoder()
|
| 18 |
+
for probe in probes:
|
| 19 |
+
row=next(x for x in rows if x['name']==probe['condition']);record=config['conditions'][row['name']];parent_settings=config['neural_d5'][row['group']];indices=np.array(probe['input_array_positions']);passes=parent_settings['prior_pass']
|
| 20 |
+
with np.load(Path('/workspace/data/train')/row['arrays'],allow_pickle=False) as f:packed=f['detectors'][indices];ids=f['sample_ids'][indices]
|
| 21 |
+
assert np.array_equal(ids,np.array(probe['sample_ids'],np.uint64));prior_path=r/('learned_d5/full_training_priors3' if passes==3 else 'full_prior5/cache1')/(row['name']+'.npz')
|
| 22 |
+
with np.load(prior_path,allow_pickle=False) as f:assert np.array_equal(f['sample_ids'][indices],ids);prior=f[f'priors{passes}'][indices]
|
| 23 |
+
relative='beam_calibration/'+row['name']+'.npz';shutil.copyfile(r/'beam_r3/plans'/(row['name']+'.npz'),target/relative);expected_beam=np.array(next(z['probabilities'] for z in numeric if z['condition']==row['name'] and z['method']=='independent' and z['per_sector_states']==512),np.float32)
|
| 24 |
+
parent=old.predict(target,record,parent_settings,packed,row['num_detectors'],batch=batch,initial_priors=prior)
|
| 25 |
+
for width in [1,2]:
|
| 26 |
+
state={'center':[.12,-.03][:width],'scale':[2.1,.8][:width],'weights':[.03,-.09,.12][:width+1]};state_path='beam_calibration/'+row['name']+f'_width{width}.json';(target/state_path).write_text(json.dumps(state))
|
| 27 |
+
option={'state':state_path,'plan':relative,'per_sector_states':512,'parent':parent_settings};settings={**parent_settings,'beam_calibration':{record['neural_d5_plan']:option}}
|
| 28 |
+
old_engines=set(new.beam_calibration_engines);begin=time.time();actual=new.predict(target,record,settings,packed,row['num_detectors'],batch=batch,initial_priors=prior);seconds=time.time()-begin;expected=predict(parent,expected_beam,state);delta=float(abs(expected-actual).max());assert delta<1e-4 and ((expected>=.5)==(actual>=.5)).all()
|
| 29 |
+
if width==1:assert set(new.beam_calibration_engines)==old_engines and np.array_equal(expected,actual)
|
| 30 |
+
reverse=new.predict(target,record,settings,packed[::-1].copy(),row['num_detectors'],batch=batch,initial_priors=prior[::-1].copy());single=new.predict(target,record,settings,packed[:1],row['num_detectors'],batch=batch,initial_priors=prior[:1]);assert np.array_equal(reverse,actual[::-1]) and np.array_equal(single,actual[:1])
|
| 31 |
+
live=new.predict(target,record,settings,packed,row['num_detectors'],batch=batch);live_delta=float(abs(live-actual).max());assert live_delta<1e-4 and ((live>=.5)==(actual>=.5)).all()
|
| 32 |
+
checks.append({'condition':row['name'],'feature_width':width,'batch':batch,'shots':len(packed),'independent_composition_max_abs':delta,'decisions_equal':True,'order_subset_exact':True,'no_new_beam_for_parent_only':width==1,'live_cached_max_abs':live_delta,'first_call_seconds':seconds})
|
| 33 |
+
with np.load(target/relative,allow_pickle=False) as f:empty_plan={k:f[k] for k in f.files}
|
| 34 |
+
empty_plan['probabilities']=np.zeros_like(empty_plan['probabilities']);empty_relative='beam_calibration/empty_'+row['name']+'.npz';np.savez(target/empty_relative,**empty_plan)
|
| 35 |
+
settings['beam_calibration'][record['neural_d5_plan']]['plan']=empty_relative;fallback=new.predict(target,record,settings,packed,row['num_detectors'],batch=batch,initial_priors=prior);assert np.array_equal(fallback,predict(parent,parent,state));checks.append({'condition':row['name'],'forced_empty_before_feature_fallback_exact':True})
|
| 36 |
+
for basis,rounds in [('X',1),('Z',25)]:
|
| 37 |
+
row=next(z for z in rows if z['distance']==5 and z['basis']==basis and z['rounds']==rounds);record=config['conditions'][row['name']];settings={**config['neural_d5'][row['group']],'beam_calibration':{'unused_plan':{}}}
|
| 38 |
+
with np.load(Path('/workspace/data/train')/row['arrays'],allow_pickle=False) as f:packed=f['detectors'][:2]
|
| 39 |
+
a=old.predict(target,record,config['neural_d5'][row['group']],packed,row['num_detectors'],batch=batch);b=new.predict(target,record,settings,packed,row['num_detectors'],batch=batch);assert np.array_equal(a,b);checks.append({'condition':row['name'],'retained_current_path_exact':True})
|
| 40 |
+
peak=int((jax.devices()[0].memory_stats() or {}).get('peak_bytes_in_use',0));assert peak<75*1024**3
|
| 41 |
+
report={'status':'passed','device':str(jax.devices()[0]),'checks':checks,'peak_gpu_bytes':peak,'scope':'Exported wrapper with specified nonzero synthetic correction coefficients; no hardware labels or fitting. Independent NumPy beam/reference-parent composition, parent-only path, order/subsets, live conditioning, forced empty-before-feature fallback and retained paths. GPU mode uses production B512.','exported_source_sha256':exported,'test_data_used':False,'source_sha256':{str(p.relative_to(r)):hashlib.sha256(p.read_bytes()).hexdigest() for p in [root/'runtime.py',root/'export.py',root/'core.py',Path(__file__).resolve(),r/'full_frontier/beam_jax.py']}}
|
| 42 |
+
(root/f'runtime_control_{args.device}.json').write_text(json.dumps(report,indent=2)+'\n');print(json.dumps(report,indent=2),flush=True)
|
tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S040/training_sources/beam_calibration1/verify_during_recovery.py
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Use the current idle GPU window; resume trajectory only after this marker."""
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
import hashlib,json,shutil,subprocess
|
| 4 |
+
root=Path(__file__).resolve().parent;r=root.parent
|
| 5 |
+
assert not subprocess.check_output(['nvidia-smi','--query-compute-apps=pid','--format=csv,noheader'],text=True).strip()
|
| 6 |
+
assert json.loads((r/'block_physical/benchmark_finished.json').read_text())['complete']
|
| 7 |
+
assert not (r/'feedback_trajectory/trajectory1').exists()
|
| 8 |
+
for lock in ['FIT_SOURCE_LOCK.json','PACKAGE_SOURCE_LOCK.json']:
|
| 9 |
+
for path,digest in json.loads((root/lock).read_text())['source_sha256'].items():assert hashlib.sha256((r/path).read_bytes()).hexdigest()==digest,path
|
| 10 |
+
for filename in ['control_cpu.json','runtime_control_cpu.json']:
|
| 11 |
+
report=json.loads((root/filename).read_text());assert report['status']=='passed'
|
| 12 |
+
for path,digest in report['source_sha256'].items():
|
| 13 |
+
source=r/path if '/' in path else root/path;assert hashlib.sha256(source.read_bytes()).hexdigest()==digest,path
|
| 14 |
+
current=json.loads((r/'CURRENT.json').read_text());selected=json.loads((root/'fit1/report.json').read_text())['selected'];assert selected['arm']=='parent_only'
|
| 15 |
+
subprocess.run(['python',str(r/'run_limited.py'),str(root/'runtime_control.py'),'--device','gpu'],check=True)
|
| 16 |
+
subprocess.run(['python',str(root/'package.py')],check=True);out=r/'context_upgrades/beam_calibration1';package=out/'package'
|
| 17 |
+
provenance=json.loads((package/'training_provenance.json').read_text());provenance['beam_calibration1']['queue_amendment']=json.loads((root/'QUEUE_AMENDMENT.json').read_text());provenance['beam_calibration1']['verification_controller_sha256']=hashlib.sha256(Path(__file__).read_bytes()).hexdigest();(package/'training_provenance.json').write_text(json.dumps(provenance,indent=2)+'\n')
|
| 18 |
+
for filename in ['QUEUE_AMENDMENT.json','verify_during_recovery.py']:shutil.copyfile(root/filename,package/'training_sources/beam_calibration1'/filename)
|
| 19 |
+
subprocess.run(['python',str(r/'verify_d5_candidate.py'),str(out)],check=True)
|
| 20 |
+
subprocess.run(['python',str(r/'audit_completed_candidate.py'),'--candidate',str(out),'--previous',current['predictions']],check=True)
|
| 21 |
+
done=json.loads((out/'finished.json').read_text());(root/'beam_calibration1_finished.json').write_text(json.dumps({'complete':True,'published':done['published'],'queue_amended':True,'test_data_used':False})+'\n')
|
tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S040/training_sources/condition_same1/exact_d3__exact.py
ADDED
|
@@ -0,0 +1,213 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Exact detector-error-model contraction by bounded-frontier elimination."""
|
| 2 |
+
import collections
|
| 3 |
+
import numpy as np
|
| 4 |
+
import stim
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def parse_errors(dem):
|
| 8 |
+
errors = []
|
| 9 |
+
for ins in dem.flattened():
|
| 10 |
+
if ins.type != 'error':
|
| 11 |
+
continue
|
| 12 |
+
ds, logical = set(), 0
|
| 13 |
+
for t in ins.targets_copy():
|
| 14 |
+
if t.is_relative_detector_id():
|
| 15 |
+
ds.symmetric_difference_update([t.val])
|
| 16 |
+
elif t.is_logical_observable_id():
|
| 17 |
+
assert t.val == 0
|
| 18 |
+
logical ^= 1
|
| 19 |
+
errors.append((ds, logical, ins.args_copy()[0]))
|
| 20 |
+
return errors
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def elimination_order(dem, errors):
|
| 24 |
+
blocks = collections.defaultdict(list)
|
| 25 |
+
for d, c in dem.get_detector_coordinates().items():
|
| 26 |
+
blocks[c[-1]].append(d)
|
| 27 |
+
pending = [ds for ds, _, _ in errors if ds]
|
| 28 |
+
active, used, order = set(), set(), []
|
| 29 |
+
for _, block in sorted(blocks.items()):
|
| 30 |
+
remain = set(block)
|
| 31 |
+
while remain:
|
| 32 |
+
def score(d):
|
| 33 |
+
new = set().union(*(e for e in pending if d in e)) - used
|
| 34 |
+
return len(active | new), -sum(d in e for e in pending), d
|
| 35 |
+
d = min(remain, key=score)
|
| 36 |
+
related = [e for e in pending if d in e]
|
| 37 |
+
active |= set().union(*related) - used
|
| 38 |
+
active.discard(d)
|
| 39 |
+
pending = [e for e in pending if d not in e]
|
| 40 |
+
used.add(d)
|
| 41 |
+
remain.remove(d)
|
| 42 |
+
order.append(d)
|
| 43 |
+
assert sorted(order) == list(range(dem.num_detectors))
|
| 44 |
+
return order
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def make_plan(dem):
|
| 48 |
+
errors = parse_errors(dem)
|
| 49 |
+
order = elimination_order(dem, errors)
|
| 50 |
+
rank = {d: i for i, d in enumerate(order)}
|
| 51 |
+
groups = collections.defaultdict(list)
|
| 52 |
+
for source_index, (ds, logical, p) in enumerate(errors):
|
| 53 |
+
first = min(ds, key=rank.get) if ds else order[0]
|
| 54 |
+
groups[first].append((ds, logical, p, source_index))
|
| 55 |
+
slots, probabilities, masks, measured, source_indices = {}, [], [], [], []
|
| 56 |
+
width = 1
|
| 57 |
+
for d in order:
|
| 58 |
+
related = groups[d]
|
| 59 |
+
needed = set().union(*(ds for ds, _, _, _ in related)) | {d}
|
| 60 |
+
for node in sorted(needed):
|
| 61 |
+
if node not in slots:
|
| 62 |
+
free = next(i for i in range(1, 64) if i not in slots.values())
|
| 63 |
+
slots[node] = free
|
| 64 |
+
width = max(width, free+1)
|
| 65 |
+
for ds, logical, p, source_index in related:
|
| 66 |
+
mask = logical
|
| 67 |
+
for node in ds:
|
| 68 |
+
mask ^= 1 << slots[node]
|
| 69 |
+
probabilities.append(p)
|
| 70 |
+
masks.append(mask)
|
| 71 |
+
measured.append(-1)
|
| 72 |
+
source_indices.append(source_index)
|
| 73 |
+
probabilities.append(0)
|
| 74 |
+
masks.append(1 << slots.pop(d))
|
| 75 |
+
measured.append(d)
|
| 76 |
+
source_indices.append(-1)
|
| 77 |
+
assert not slots
|
| 78 |
+
return {'probabilities': np.array(probabilities, np.float32),
|
| 79 |
+
'masks': np.array(masks, np.int32), 'measured': np.array(measured, np.int32),
|
| 80 |
+
'width': np.array(width, np.int32), 'num_detectors': np.array(dem.num_detectors, np.int32),
|
| 81 |
+
'source_indices': np.array(source_indices, np.int32),
|
| 82 |
+
'order': np.array(order, np.int32)}
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def make_decoder(width):
|
| 86 |
+
import jax
|
| 87 |
+
import jax.numpy as jnp
|
| 88 |
+
indices = jnp.arange(1 << width, dtype=jnp.int32)
|
| 89 |
+
@jax.jit
|
| 90 |
+
def decode(dets, probabilities, masks, measured):
|
| 91 |
+
f = jnp.zeros((dets.shape[0], 1 << width), jnp.float32).at[:, 0].set(1)
|
| 92 |
+
def step(f, args):
|
| 93 |
+
p, mask, d = args
|
| 94 |
+
def error(f):
|
| 95 |
+
prob = p[:, None] if p.ndim else p
|
| 96 |
+
return (1-prob)*f + prob*f[:, indices ^ mask]
|
| 97 |
+
def project(f):
|
| 98 |
+
obs = dets[:, d].astype(jnp.int32)
|
| 99 |
+
dst = (indices[None, :] & ~mask) | (obs[:, None]*mask)
|
| 100 |
+
g = jnp.take_along_axis(f, dst, axis=1) * ((indices & mask)==0)
|
| 101 |
+
return g / jnp.maximum(jnp.sum(g, axis=1, keepdims=True), 1e-30)
|
| 102 |
+
return jax.lax.cond(d < 0, error, project, f), None
|
| 103 |
+
f, _ = jax.lax.scan(step, f, (probabilities, masks, measured))
|
| 104 |
+
return jnp.sum(f[:, 1::2], axis=1) / jnp.maximum(jnp.sum(f, axis=1), 1e-30)
|
| 105 |
+
return decode
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def make_marginals(width):
|
| 109 |
+
"""Per-shot derivatives of log syndrome probability give all error marginals."""
|
| 110 |
+
import jax
|
| 111 |
+
import jax.numpy as jnp
|
| 112 |
+
indices = jnp.arange(1 << width, dtype=jnp.int32)
|
| 113 |
+
def log_partition(dets, probabilities, masks, measured):
|
| 114 |
+
f = jnp.zeros(1 << width, jnp.float32).at[0].set(1)
|
| 115 |
+
def step(carry, args):
|
| 116 |
+
f, logz = carry
|
| 117 |
+
p, mask, d = args
|
| 118 |
+
def error(carry):
|
| 119 |
+
f, logz = carry
|
| 120 |
+
return ((1-p)*f + p*f[indices ^ mask], logz)
|
| 121 |
+
def project(carry):
|
| 122 |
+
f, logz = carry
|
| 123 |
+
dst = (indices & ~mask) | (dets[d].astype(jnp.int32)*mask)
|
| 124 |
+
g = f[dst] * ((indices & mask)==0)
|
| 125 |
+
norm = jnp.maximum(jnp.sum(g), 1e-30)
|
| 126 |
+
return g/norm, logz+jnp.log(norm)
|
| 127 |
+
return jax.lax.cond(d<0, error, project, carry), None
|
| 128 |
+
(_, logz), _ = jax.lax.scan(jax.checkpoint(step), (f, jnp.float32(0)), (probabilities, masks, measured))
|
| 129 |
+
return logz
|
| 130 |
+
return jax.jit(jax.vmap(jax.value_and_grad(log_partition, argnums=1), in_axes=(0,None,None,None)))
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
def make_marginals_fb(width, return_observable=False):
|
| 134 |
+
"""Forward/backward contraction without generic gather-gradient scatter."""
|
| 135 |
+
import jax
|
| 136 |
+
import jax.numpy as jnp
|
| 137 |
+
indices = jnp.arange(1 << width, dtype=jnp.int32)
|
| 138 |
+
# The syndrome likelihood marginalizes the unobserved logical bit. Keep
|
| 139 |
+
# that bit in the forward state for its output, but omit it from histories
|
| 140 |
+
# and backward messages, halving the largest buffers.
|
| 141 |
+
backward_width=width-1 if return_observable else width
|
| 142 |
+
backward_indices=jnp.arange(1 << backward_width,dtype=jnp.int32)
|
| 143 |
+
@jax.jit
|
| 144 |
+
def marginals(dets, probabilities, masks, measured):
|
| 145 |
+
f=jnp.zeros((dets.shape[0],1<<width),jnp.float32).at[:,0].set(1)
|
| 146 |
+
def forward(carry,args):
|
| 147 |
+
f,logz=carry
|
| 148 |
+
p,mask,d=args
|
| 149 |
+
def error(carry):
|
| 150 |
+
f,logz=carry
|
| 151 |
+
prob=p[:,None] if p.ndim else p
|
| 152 |
+
return ((1-prob)*f+prob*f[:,indices^mask],logz)
|
| 153 |
+
def project(carry):
|
| 154 |
+
f,logz=carry
|
| 155 |
+
dst=(indices[None,:]&~mask)|(dets[:,d,None].astype(jnp.int32)*mask)
|
| 156 |
+
g=jnp.take_along_axis(f,dst,axis=1)*((indices&mask)==0)
|
| 157 |
+
norm=jnp.maximum(g.sum(axis=1),1e-30)
|
| 158 |
+
return g/norm[:,None],logz+jnp.log(norm)
|
| 159 |
+
out=jax.lax.cond(d<0,error,project,carry)
|
| 160 |
+
return out,(f[:,::2]+f[:,1::2]) if return_observable else f
|
| 161 |
+
(final,logz),history=jax.lax.scan(forward,(f,jnp.zeros(len(dets))),(probabilities,masks,measured))
|
| 162 |
+
def backward(b,args):
|
| 163 |
+
p,mask,d,f=args
|
| 164 |
+
def error(b):
|
| 165 |
+
flipped=b[:,backward_indices^mask]
|
| 166 |
+
prob=p[:,None] if p.ndim else p
|
| 167 |
+
prior=(1-prob)*b+prob*flipped
|
| 168 |
+
norm=jnp.maximum(jnp.sum(f*prior,axis=1),1e-30)
|
| 169 |
+
q=p*jnp.sum(f*flipped,axis=1)/norm
|
| 170 |
+
grad=(q-p)/jnp.maximum(p*(1-p),1e-20)
|
| 171 |
+
return prior/norm[:,None],grad
|
| 172 |
+
def project(b):
|
| 173 |
+
prior=b[:,backward_indices&~mask]*((backward_indices[None,:]&mask)==(dets[:,d,None].astype(jnp.int32)*mask))
|
| 174 |
+
norm=jnp.maximum(jnp.sum(f*prior,axis=1),1e-30)
|
| 175 |
+
return prior/norm[:,None],jnp.zeros(len(dets))
|
| 176 |
+
return jax.lax.cond(d<0,error,project,b)
|
| 177 |
+
backward_masks=masks>>1 if return_observable else masks
|
| 178 |
+
_,grad=jax.lax.scan(backward,jnp.ones((len(dets),1<<backward_width),jnp.float32),
|
| 179 |
+
(probabilities,backward_masks,measured,history),reverse=True)
|
| 180 |
+
if return_observable:
|
| 181 |
+
return logz,grad.T,jnp.sum(final[:,1::2],axis=1)/jnp.maximum(jnp.sum(final,axis=1),1e-30)
|
| 182 |
+
return logz,grad.T
|
| 183 |
+
return marginals
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
def predict(plan, packed, decoder=None, batch=256):
|
| 187 |
+
import jax
|
| 188 |
+
decoder = decoder or make_decoder(int(plan['width']))
|
| 189 |
+
dets = np.unpackbits(packed, bitorder='little', axis=1, count=int(plan['num_detectors']))
|
| 190 |
+
args = [jax.device_put(plan[k]) for k in ['probabilities', 'masks', 'measured']]
|
| 191 |
+
result = []
|
| 192 |
+
for start in range(0, len(dets), batch):
|
| 193 |
+
ds = dets[start:start+batch]
|
| 194 |
+
ds = np.pad(ds, ((0, batch-len(ds)), (0, 0)))
|
| 195 |
+
result.append(np.asarray(decoder(ds, *args))[:min(batch, len(dets)-start)])
|
| 196 |
+
return np.concatenate(result)
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
if __name__ == '__main__':
|
| 200 |
+
import sys, time
|
| 201 |
+
from pathlib import Path
|
| 202 |
+
import jax
|
| 203 |
+
print(jax.devices(), flush=True)
|
| 204 |
+
path = Path(sys.argv[1])
|
| 205 |
+
dem = stim.DetectorErrorModel.from_file(path/'pij_from_even_for_odd.dem')
|
| 206 |
+
plan = make_plan(dem)
|
| 207 |
+
print({k: v.shape if v.ndim else int(v) for k, v in plan.items()}, flush=True)
|
| 208 |
+
a = np.load(path/'arrays.npz')
|
| 209 |
+
decoder = make_decoder(int(plan['width']))
|
| 210 |
+
for i in range(2):
|
| 211 |
+
t = time.time()
|
| 212 |
+
p = predict(plan, a['detectors'][:1024], decoder)
|
| 213 |
+
print({'seconds': time.time()-t, 'failure': np.mean((p>=.5)!=a['labels'][:len(p)]), 'min': p.min(), 'max': p.max()}, flush=True)
|
tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S040/training_sources/condition_same1/learned_exact__data.py
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pathlib import Path
|
| 2 |
+
import json,sys
|
| 3 |
+
import numpy as np
|
| 4 |
+
import stim
|
| 5 |
+
sys.path.insert(0,'/workspace/research/exact_d3')
|
| 6 |
+
from exact import make_plan,parse_errors
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def _attach_arrays(item,root,splits):
|
| 10 |
+
row=item['row']
|
| 11 |
+
for split in splits:
|
| 12 |
+
a=np.load(root/split/row['arrays']);ds=np.unpackbits(a['detectors'],axis=1,count=row['num_detectors'],bitorder='little')
|
| 13 |
+
item[split+'_dets']=np.pad(ds,((0,0),(0,201-ds.shape[1])))
|
| 14 |
+
item[split+'_labels']=a['labels']
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def load_all(max_ops=3072,splits=('train','validation')):
|
| 18 |
+
assert set(splits)<=set(['train','validation'])
|
| 19 |
+
root=Path('/workspace/data')
|
| 20 |
+
rows=[r for r in json.loads((root/'train/manifest.json').read_text())['conditions'] if r['distance']==3]
|
| 21 |
+
groups=sorted({r['group'] for r in rows});result=[]
|
| 22 |
+
cache=Path('/workspace/research/learned_exact')/f'feature_cache-v2-{max_ops}'
|
| 23 |
+
cache.mkdir(exist_ok=True)
|
| 24 |
+
for row in rows:
|
| 25 |
+
cached=cache/f"{row['name']}-{row['noise_sha256'][:12]}-{row['circuit_sha256'][:12]}.npz"
|
| 26 |
+
if cached.exists():
|
| 27 |
+
item=dict(np.load(cached,allow_pickle=False));item['row']=row
|
| 28 |
+
_attach_arrays(item,root,splits);result.append(item);continue
|
| 29 |
+
dem=stim.DetectorErrorModel.from_file(root/'train'/row['noise']);plan=make_plan(dem)
|
| 30 |
+
assert int(plan['width'])<=10
|
| 31 |
+
count=len(plan['masks']);assert count<=max_ops,(row['name'],count)
|
| 32 |
+
coords=dem.get_detector_coordinates()
|
| 33 |
+
circuit=stim.Circuit.from_file(root/'train'/row['circuit'])
|
| 34 |
+
qubit_coords=circuit.get_final_qubit_coordinates()
|
| 35 |
+
first_measurement=next(ins for ins in circuit.flattened() if ins.name in ['M','MX','MR','MRX'])
|
| 36 |
+
spaces=sorted(tuple(qubit_coords[t.value][:2]) for t in first_measurement.targets_copy())
|
| 37 |
+
assert len(spaces)==8
|
| 38 |
+
idx={(int(c[2]),tuple(c[:2])):d for d,c in coords.items()}
|
| 39 |
+
errors=parse_errors(dem)
|
| 40 |
+
context=np.full((max_ops,40),200,np.int32)
|
| 41 |
+
static=np.zeros((max_ops,57),np.float32)
|
| 42 |
+
for op,source in enumerate(plan['source_indices']):
|
| 43 |
+
if source<0:continue
|
| 44 |
+
ds,logical,p=errors[source]
|
| 45 |
+
t=min(int(coords[d][2]) for d in ds) if ds else 0
|
| 46 |
+
for dt in range(-2,3):
|
| 47 |
+
for s,spatial in enumerate(spaces):context[op,(dt+2)*8+s]=idx.get((t+dt,spatial),200)
|
| 48 |
+
for d in ds:
|
| 49 |
+
c=coords[d];static[op,(int(c[2])-t+2)*8+spaces.index(tuple(c[:2]))]=1
|
| 50 |
+
static[op,40]=np.log(max(p,1e-7)/(1-max(p,1e-7)))/8
|
| 51 |
+
static[op,41]=logical;static[op,42]=len(ds)/4
|
| 52 |
+
static[op,43]=t/25;static[op,44]=row['rounds']/25
|
| 53 |
+
static[op,45]=t==0;static[op,46]=t>=row['rounds']-1
|
| 54 |
+
static[op,47+groups.index(row['group'])]=1
|
| 55 |
+
static[op,55]=row['basis']=='X';static[op,56]=1
|
| 56 |
+
masks=np.pad(plan['masks'],(0,max_ops-count))
|
| 57 |
+
measured=np.pad(plan['measured'],(0,max_ops-count),constant_values=-1)
|
| 58 |
+
p=np.pad(plan['probabilities'],(0,max_ops-count))
|
| 59 |
+
valid=((p>0)&(measured<0)).astype(np.float32)
|
| 60 |
+
logits=np.log(np.clip(p,1e-7,1-1e-7)/np.clip(1-p,1e-7,1-1e-7)).astype(np.float32)
|
| 61 |
+
item={'row':row,'context':context,'static':static,'masks':masks,'measured':measured,'base_logits':logits,'valid':valid}
|
| 62 |
+
grid=np.full((26,8),200,np.int32)
|
| 63 |
+
measurement_indices=np.full(201,208,np.int32)
|
| 64 |
+
for detector,c in coords.items():
|
| 65 |
+
t=int(c[2]);s=spaces.index(tuple(c[:2]));grid[t,s]=detector
|
| 66 |
+
measurement_indices[detector]=t*8+s
|
| 67 |
+
item['grid']=grid;item['measurement_indices']=measurement_indices
|
| 68 |
+
item['counts']=np.maximum((grid!=200).sum(axis=0),1).astype(np.float32)
|
| 69 |
+
temporary=cached.with_suffix('.tmp.npz')
|
| 70 |
+
np.savez(temporary,**{k:v for k,v in item.items() if k!='row'});temporary.replace(cached)
|
| 71 |
+
_attach_arrays(item,root,splits)
|
| 72 |
+
result.append(item)
|
| 73 |
+
return result
|
tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S040/training_sources/condition_same1/learned_exact__gradient.py
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Differentiable conditional logical likelihood through exact DEM elimination."""
|
| 2 |
+
import jax
|
| 3 |
+
import jax.numpy as jnp
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
def make_loss_and_grad(width):
|
| 7 |
+
indices=jnp.arange(1<<width,dtype=jnp.int32)
|
| 8 |
+
@jax.jit
|
| 9 |
+
def evaluate(dets,labels,probabilities,masks,measured):
|
| 10 |
+
# Per-shot error probabilities have shape [operations,batch].
|
| 11 |
+
f=jnp.zeros((len(dets),1<<width),jnp.float32).at[:,0].set(1)
|
| 12 |
+
def forward(f,args):
|
| 13 |
+
p,mask,d=args
|
| 14 |
+
def error(f):
|
| 15 |
+
return (1-p[:,None])*f+p[:,None]*f[:,indices^mask],jnp.ones(len(dets))
|
| 16 |
+
def project(f):
|
| 17 |
+
dst=(indices[None,:]&~mask)|(dets[:,d,None].astype(jnp.int32)*mask)
|
| 18 |
+
g=jnp.take_along_axis(f,dst,axis=1)*((indices&mask)==0)
|
| 19 |
+
norm=jnp.maximum(g.sum(axis=1),1e-30)
|
| 20 |
+
return g/norm[:,None],norm
|
| 21 |
+
out,norm=jax.lax.cond(d<0,error,project,f)
|
| 22 |
+
return out,(f,norm)
|
| 23 |
+
f,(history,norms)=jax.lax.scan(forward,f,(probabilities,masks,measured))
|
| 24 |
+
indicator=((indices[None,:]&1)==labels[:,None])
|
| 25 |
+
correct=jnp.maximum(jnp.sum(f*indicator,axis=1),1e-10)
|
| 26 |
+
predicted=jnp.sum(f[:,1::2],axis=1)
|
| 27 |
+
initial=1-indicator/correct[:,None]
|
| 28 |
+
def backward(b,args):
|
| 29 |
+
p,mask,d,old,norm=args
|
| 30 |
+
def error(b):
|
| 31 |
+
flipped=b[:,indices^mask]
|
| 32 |
+
grad=jnp.sum(old*(flipped-b),axis=1)
|
| 33 |
+
return (1-p[:,None])*b+p[:,None]*flipped,grad
|
| 34 |
+
def project(b):
|
| 35 |
+
obs=((indices[None,:]&mask)==dets[:,d,None].astype(jnp.int32)*mask)
|
| 36 |
+
values=b[:,indices&~mask]
|
| 37 |
+
mean=jnp.sum(old*obs*values,axis=1)/norm
|
| 38 |
+
prior=(values-mean[:,None])*obs/norm[:,None]
|
| 39 |
+
return prior,jnp.zeros(len(dets))
|
| 40 |
+
return jax.lax.cond(d<0,error,project,b)
|
| 41 |
+
_,grad=jax.lax.scan(backward,initial,(probabilities,masks,measured,history,norms),reverse=True)
|
| 42 |
+
return -jnp.log(correct),predicted,grad
|
| 43 |
+
return evaluate
|
tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S040/training_sources/condition_same1/learned_exact__temporal_accumulate_train.py
ADDED
|
@@ -0,0 +1,158 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Derived from temporal_train.py SHA256 7d48d2fc7f62d0bec3023b3df1c2ac28537d0417966131ae3a156697a34cda5f; separate matched condition-mixing experiment.
|
| 2 |
+
import os
|
| 3 |
+
os.environ['OPENBLAS_NUM_THREADS']='1'
|
| 4 |
+
os.environ['OMP_NUM_THREADS']='1'
|
| 5 |
+
os.environ['XLA_PYTHON_CLIENT_PREALLOCATE']='false'
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
import argparse,json,time,sys,hashlib,shutil
|
| 8 |
+
import numpy as np
|
| 9 |
+
import jax,jax.numpy as jnp,optax
|
| 10 |
+
from temporal_model import initialize_from_rich,probabilities
|
| 11 |
+
from data import load_all
|
| 12 |
+
from gradient import make_loss_and_grad
|
| 13 |
+
sys.path.insert(0,'/workspace/research/exact_d3')
|
| 14 |
+
from exact import make_decoder
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def main():
|
| 18 |
+
parser=argparse.ArgumentParser();parser.add_argument('--steps',type=int,default=512);parser.add_argument('--batch',type=int,default=128)
|
| 19 |
+
parser.add_argument('--output',type=Path,required=True);parser.add_argument('--validation-shots',type=int,default=1024)
|
| 20 |
+
parser.add_argument('--init-weights',type=Path)
|
| 21 |
+
parser.add_argument('--rich-checkpoint',type=Path,required=True)
|
| 22 |
+
parser.add_argument('--learning-rate',type=float,default=1e-3)
|
| 23 |
+
parser.add_argument('--eval-every',type=int,default=256)
|
| 24 |
+
parser.add_argument('--seed',type=int,default=20261025)
|
| 25 |
+
parser.add_argument('--validation-batch',type=int,default=1024)
|
| 26 |
+
parser.add_argument('--uniform-validation',action='store_true')
|
| 27 |
+
parser.add_argument('--accumulate-conditions',type=int,default=4)
|
| 28 |
+
parser.add_argument('--condition-policy',choices=['same','mixed'],default='mixed')
|
| 29 |
+
parser.add_argument('--reset-optimizer',action='store_true')
|
| 30 |
+
parser.add_argument('--reset-rng',action='store_true')
|
| 31 |
+
args=parser.parse_args();args.output.mkdir(parents=True,exist_ok=True)
|
| 32 |
+
assert args.accumulate_conditions>=1
|
| 33 |
+
run_config={k:str(v) if isinstance(v,Path) else v for k,v in vars(args).items()}
|
| 34 |
+
run_config['original_random_seed']=20261030
|
| 35 |
+
run_config['feature_mode']='events+measurements+global_density+temporal_convolutions'
|
| 36 |
+
run_config['temporal_seed']=20261104
|
| 37 |
+
run_config['rich_checkpoint_sha256']=hashlib.sha256(args.rich_checkpoint.read_bytes()).hexdigest()
|
| 38 |
+
run_config['hidden_width']=128
|
| 39 |
+
run_config['logit_correction_bound']=4
|
| 40 |
+
run_config['starting_checkpoint_sha256']=hashlib.sha256(args.init_weights.read_bytes()).hexdigest() if args.init_weights else None
|
| 41 |
+
run_config['train_manifest_sha256']=hashlib.sha256(Path('/workspace/data/train/manifest.json').read_bytes()).hexdigest()
|
| 42 |
+
run_config['validation_manifest_sha256']=hashlib.sha256(Path('/workspace/data/validation/manifest.json').read_bytes()).hexdigest()
|
| 43 |
+
source_root=Path(__file__).resolve().parent;research=source_root.parent
|
| 44 |
+
snapshot=args.output/'training_source';snapshot.mkdir(exist_ok=True)
|
| 45 |
+
source_hashes={}
|
| 46 |
+
for source in [Path(__file__).resolve(),source_root/'temporal_model.py',source_root/'data.py',source_root/'gradient.py',research/'exact_d3/exact.py']:
|
| 47 |
+
name=str(source.relative_to(research)).replace('/','__')
|
| 48 |
+
shutil.copyfile(source,snapshot/name);source_hashes[name]=hashlib.sha256(source.read_bytes()).hexdigest()
|
| 49 |
+
run_config['training_source_sha256']=source_hashes
|
| 50 |
+
run_config['runtime_versions']={'jax':jax.__version__,'numpy':np.__version__,'optax':optax.__version__}
|
| 51 |
+
(args.output/'run_config.json').write_text(json.dumps(run_config,indent=2)+'\n')
|
| 52 |
+
t=time.time();dataset=load_all();print(json.dumps({'loaded':len(dataset),'seconds':time.time()-t}),flush=True)
|
| 53 |
+
seen=[np.zeros(len(item['train_labels']),bool) for item in dataset]
|
| 54 |
+
assert len({len(item['train_labels']) for item in dataset})==1, 'Matched RNG protocol assumes equal condition sizes'
|
| 55 |
+
parameters=({k:jnp.asarray(v) for k,v in dict(np.load(args.init_weights,allow_pickle=False)).items()} if args.init_weights else initialize_from_rich(args.rich_checkpoint,seed=20261104))
|
| 56 |
+
optimizer=optax.chain(optax.clip_by_global_norm(1.),optax.adamw(learning_rate=args.learning_rate,weight_decay=1e-4))
|
| 57 |
+
state=optimizer.init(parameters);exact_gradient=make_loss_and_grad(10)
|
| 58 |
+
rng=np.random.default_rng(args.seed);optimizer_restored=False;rng_restored=False
|
| 59 |
+
if args.init_weights:
|
| 60 |
+
optfile=args.init_weights.with_name(args.init_weights.name.replace('weights-','optimizer-'))
|
| 61 |
+
if optfile.exists() and not args.reset_optimizer:
|
| 62 |
+
leaves,treedef=jax.tree_util.tree_flatten(state);saved=np.load(optfile,allow_pickle=False)
|
| 63 |
+
assert len(leaves)==len(saved.files)
|
| 64 |
+
state=jax.tree_util.tree_unflatten(treedef,[jnp.asarray(saved[f'arr_{i}']) for i in range(len(leaves))]);optimizer_restored=True
|
| 65 |
+
rngfile=args.init_weights.with_name(args.init_weights.name.replace('weights-','rng-')).with_suffix('.json')
|
| 66 |
+
if rngfile.exists() and not args.reset_rng:rng.bit_generator.state=json.loads(rngfile.read_text());rng_restored=True
|
| 67 |
+
@jax.jit
|
| 68 |
+
def batch_gradient(parameters,ds,ys,context,static,base_logits,valid,masks,measured,grid,measurement_indices,counts):
|
| 69 |
+
p,pullback=jax.vjp(lambda w:probabilities(w,ds,context,static,base_logits,valid,grid,measurement_indices,counts),parameters)
|
| 70 |
+
loss,pred,g=exact_gradient(ds,ys,p,masks,measured)
|
| 71 |
+
grads=pullback(g/len(ds))[0]
|
| 72 |
+
return grads,jnp.mean(loss),jnp.mean((pred>=.5)!=ys)
|
| 73 |
+
@jax.jit
|
| 74 |
+
def apply_gradient(parameters,state,grads):
|
| 75 |
+
changes,state=optimizer.update(grads,state,parameters)
|
| 76 |
+
return optax.apply_updates(parameters,changes),state,optax.global_norm(grads)
|
| 77 |
+
exact_decode=make_decoder(10)
|
| 78 |
+
@jax.jit
|
| 79 |
+
def infer(parameters,ds,context,static,base_logits,valid,masks,measured,grid,measurement_indices,counts):
|
| 80 |
+
p=probabilities(parameters,ds,context,static,base_logits,valid,grid,measurement_indices,counts)
|
| 81 |
+
return exact_decode(ds,p,masks,measured)
|
| 82 |
+
def evaluate(step):
|
| 83 |
+
results=[];start=time.time()
|
| 84 |
+
for item in dataset:
|
| 85 |
+
n=min(args.validation_shots,len(item['validation_labels']));pred=[]
|
| 86 |
+
selected=np.random.default_rng(20261028).choice(len(item['validation_labels']),n,replace=False) if args.uniform_validation else np.arange(n)
|
| 87 |
+
vd=item['validation_dets'][selected];vy=item['validation_labels'][selected]
|
| 88 |
+
for begin in range(0,n,args.validation_batch):
|
| 89 |
+
ds=vd[begin:begin+args.validation_batch];size=len(ds)
|
| 90 |
+
ds=np.pad(ds,((0,args.validation_batch-size),(0,0)))
|
| 91 |
+
p=np.asarray(infer(parameters,ds,*[item[k] for k in ['context','static','base_logits','valid','masks','measured','grid','measurement_indices','counts']]))[:size]
|
| 92 |
+
pred.append(p)
|
| 93 |
+
p=np.concatenate(pred)
|
| 94 |
+
pp=np.clip(p.astype(np.float64),1e-7,1-1e-7);yy=vy.astype(np.float64)
|
| 95 |
+
results.append({'condition':item['row']['name'],'failure':float(np.mean((p>=.5)!=vy)),
|
| 96 |
+
'negative_log_likelihood':float(np.mean(-yy*np.log(pp)-(1-yy)*np.log1p(-pp))),
|
| 97 |
+
'brier':float(np.mean((p-vy)**2))})
|
| 98 |
+
result={'step':step,'validation_failure':float(np.mean([r['failure'] for r in results])),
|
| 99 |
+
'negative_log_likelihood':float(np.mean([r['negative_log_likelihood'] for r in results])),
|
| 100 |
+
'seconds':time.time()-start,'conditions':results}
|
| 101 |
+
(args.output/f'validation-{step}.json').write_text(json.dumps(result,indent=2)+'\n')
|
| 102 |
+
np.savez(args.output/f'weights-{step}.npz',**{k:np.asarray(v) for k,v in parameters.items()})
|
| 103 |
+
leaves,_=jax.tree_util.tree_flatten(state)
|
| 104 |
+
np.savez(args.output/f'optimizer-{step}.npz',**{f'arr_{i}':np.asarray(v) for i,v in enumerate(leaves)})
|
| 105 |
+
(args.output/f'rng-{step}.json').write_text(json.dumps(rng.bit_generator.state)+'\n')
|
| 106 |
+
(args.output/f'checkpoint-{step}.json').write_text(json.dumps({'step':step,'new_training_shots':step*args.batch*args.accumulate_conditions,
|
| 107 |
+
'unique_training_rows_seen_in_this_phase':sum(int(x.sum()) for x in seen),
|
| 108 |
+
'weights':f'weights-{step}.npz','weights_sha256':hashlib.sha256((args.output/f'weights-{step}.npz').read_bytes()).hexdigest(),
|
| 109 |
+
'validation':f'validation-{step}.json','complete':True},indent=2)+'\n')
|
| 110 |
+
print(json.dumps({k:v for k,v in result.items() if k!='conditions'}),flush=True)
|
| 111 |
+
evaluate(0)
|
| 112 |
+
records=[]
|
| 113 |
+
for step in range(1,args.steps+1):
|
| 114 |
+
# Both arms consume the same condition and row RNG draws. The control
|
| 115 |
+
# reuses the first condition; the mixed arm uses every drawn condition.
|
| 116 |
+
sampled_conditions=rng.integers(len(dataset),size=args.accumulate_conditions)
|
| 117 |
+
total_grads=None;loss=0.;error=0.
|
| 118 |
+
for microbatch in range(args.accumulate_conditions):
|
| 119 |
+
condition_index=int(sampled_conditions[0 if args.condition_policy=='same' else microbatch])
|
| 120 |
+
item=dataset[condition_index]
|
| 121 |
+
ix=rng.integers(len(item['train_labels']),size=args.batch);seen[condition_index][ix]=True
|
| 122 |
+
grads,part_loss,part_error=batch_gradient(parameters,item['train_dets'][ix],item['train_labels'][ix],
|
| 123 |
+
*[item[k] for k in ['context','static','base_logits','valid','masks','measured','grid','measurement_indices','counts']])
|
| 124 |
+
total_grads=grads if total_grads is None else jax.tree_util.tree_map(jnp.add,total_grads,grads)
|
| 125 |
+
loss+=part_loss/args.accumulate_conditions;error+=part_error/args.accumulate_conditions
|
| 126 |
+
total_grads=jax.tree_util.tree_map(lambda g:g/args.accumulate_conditions,total_grads)
|
| 127 |
+
parameters,state,norm=apply_gradient(parameters,state,total_grads)
|
| 128 |
+
if step%16==0 or step==1:
|
| 129 |
+
record={'step':step,'loss':float(loss),'error':float(error),'gradient_norm':float(norm),'elapsed':time.time()-t}
|
| 130 |
+
records.append(record);print(json.dumps(record),flush=True)
|
| 131 |
+
if not np.isfinite(record['loss']):raise ValueError('Nonfinite training loss')
|
| 132 |
+
if step%args.eval_every==0 or step==args.steps:evaluate(step)
|
| 133 |
+
provenance={'initialization':('Continue from this session\'s trained checkpoint' if args.init_weights else 'Continue from rich weights trained from random initialization in this session; new temporal parameters randomly initialized now'),
|
| 134 |
+
'original_initialization':'Rich network random seed20261030; new 32-channel temporal network random seed20261104; rich parameters retained, new input rows Normal(0,.001)',
|
| 135 |
+
'rich_starting_checkpoint':str(args.rich_checkpoint),
|
| 136 |
+
'rich_checkpoint_sha256':hashlib.sha256(args.rich_checkpoint.read_bytes()).hexdigest(),
|
| 137 |
+
'architecture':'Rich 128-unit MLP plus 32-channel temporal encoder: four residual kernel3 convolutions with dilations1/2/4/8 and channel normalization. Receptive field31 rounds. Encoder sees events, measurements and presence masks. Per-edge 177 input features. Output4*tanh.',
|
| 138 |
+
'training':'Uniform condition sampling from all 104 d3 conditions; batch drawn from the supplied training split only',
|
| 139 |
+
'training_source_sha256':source_hashes,'runtime_versions':run_config['runtime_versions'],
|
| 140 |
+
'eligible_training_shots':sum(len(item['train_labels']) for item in dataset),
|
| 141 |
+
'unique_training_rows_seen_in_this_phase':sum(int(x.sum()) for x in seen),
|
| 142 |
+
'unique_rows_by_condition':{item['row']['name']:int(x.sum()) for item,x in zip(dataset,seen)},
|
| 143 |
+
'steps':args.steps,'batch_size':args.batch,'accumulate_conditions':args.accumulate_conditions,
|
| 144 |
+
'effective_batch_size':args.batch*args.accumulate_conditions,'condition_policy':args.condition_policy,
|
| 145 |
+
'training_draws':args.steps*args.batch*args.accumulate_conditions,
|
| 146 |
+
'condition_sampling':'Draw one condition index per microbatch in both arms; same-condition control reuses the first index while mixed arm uses all indices. Both arms consume identical RNG draws with equal-sized condition pools.','optimizer':'AdamW, weight decay 1e-4, global gradient norm clip 1',
|
| 147 |
+
'learning_rate':args.learning_rate,'sampling_seed':args.seed,'optimizer_restored':optimizer_restored,'rng_restored':rng_restored,'explicit_optimizer_reset':args.reset_optimizer,'explicit_rng_reset':args.reset_rng,
|
| 148 |
+
'sampling_state_source':str(rngfile) if rng_restored else f'Fresh NumPy default_rng seed {args.seed}',
|
| 149 |
+
'session_trained_starting_checkpoint':str(args.init_weights) if args.init_weights else None,
|
| 150 |
+
'starting_checkpoint_sha256':hashlib.sha256(args.init_weights.read_bytes()).hexdigest() if args.init_weights else None,
|
| 151 |
+
'starting_training_provenance':json.loads((args.init_weights.parent/'provenance.json').read_text()) if args.init_weights else None,
|
| 152 |
+
'loss':'Binary conditional logical likelihood computed by exact frontier elimination',
|
| 153 |
+
'validation_shots_per_condition':args.validation_shots,'uniform_validation':args.uniform_validation,
|
| 154 |
+
'uniform_validation_seed':20261028 if args.uniform_validation else None,'test_data_used':False,'log':records}
|
| 155 |
+
(args.output/'provenance.json').write_text(json.dumps(provenance,indent=2)+'\n')
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
if __name__=='__main__':main()
|
tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S040/training_sources/condition_same1/learned_exact__temporal_model.py
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Long temporal context for contextual exact d3 decoding."""
|
| 2 |
+
import numpy as np
|
| 3 |
+
import jax
|
| 4 |
+
import jax.numpy as jnp
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def initialize_from_rich(path,seed=20261104,channels=32):
|
| 8 |
+
parameters={k:jnp.asarray(v) for k,v in dict(np.load(path,allow_pickle=False)).items()}
|
| 9 |
+
keys=jax.random.split(jax.random.key(seed),6)
|
| 10 |
+
parameters['w1']=jnp.concatenate([parameters['w1'],jax.random.normal(keys[0],(channels,parameters['w1'].shape[1]))*.001],axis=0)
|
| 11 |
+
parameters['temporal_in']=jax.random.normal(keys[1],(24,channels))*jnp.sqrt(2/24)
|
| 12 |
+
parameters['temporal_bias']=jnp.zeros(channels)
|
| 13 |
+
for i in range(4):
|
| 14 |
+
parameters[f'temporal_conv_{i}']=jax.random.normal(keys[i+2],(3,channels,channels))*jnp.sqrt(1/(3*channels))
|
| 15 |
+
parameters[f'temporal_conv_bias_{i}']=jnp.zeros(channels)
|
| 16 |
+
return parameters
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def probabilities(parameters,dets,context_indices,static,base_logits,valid,grid,measurement_indices,counts):
|
| 20 |
+
event_grid=dets[:,grid]
|
| 21 |
+
measurement_grid=(jnp.cumsum(event_grid.astype(jnp.int32),axis=1)&1).astype(jnp.float32)
|
| 22 |
+
observed=(grid!=200).astype(jnp.float32)
|
| 23 |
+
frames=jnp.concatenate([event_grid.astype(jnp.float32),measurement_grid*observed[None,:,:],
|
| 24 |
+
jnp.broadcast_to(observed[None,:,:],event_grid.shape)],axis=-1)
|
| 25 |
+
temporal=jax.nn.silu(frames@parameters['temporal_in']+parameters['temporal_bias'])
|
| 26 |
+
for i,dilation in enumerate([1,2,4,8]):
|
| 27 |
+
mean=jnp.mean(temporal,axis=-1,keepdims=True)
|
| 28 |
+
normalized=(temporal-mean)*jax.lax.rsqrt(jnp.mean((temporal-mean)**2,axis=-1,keepdims=True)+1e-5)
|
| 29 |
+
value=jax.lax.conv_general_dilated(normalized,parameters[f'temporal_conv_{i}'],(1,),padding='SAME',
|
| 30 |
+
rhs_dilation=(dilation,),dimension_numbers=('NWC','WIO','NWC'))
|
| 31 |
+
temporal=temporal+jax.nn.silu(value+parameters[f'temporal_conv_bias_{i}'])
|
| 32 |
+
times=jnp.clip(jnp.rint(static[:,43]*25).astype(jnp.int32),0,25)
|
| 33 |
+
temporal_context=temporal[:,times,:]
|
| 34 |
+
measured=jnp.pad(measurement_grid.reshape(len(dets),208),((0,0),(0,1)))
|
| 35 |
+
events=dets[:,context_indices].astype(jnp.float32)
|
| 36 |
+
measurements=measured[:,measurement_indices[context_indices]].astype(jnp.float32)
|
| 37 |
+
density=jnp.sum(event_grid,axis=1)/counts[None,:]
|
| 38 |
+
features=jnp.concatenate([events,measurements,
|
| 39 |
+
jnp.broadcast_to(density[:,None,:],(len(dets),len(context_indices),8)),
|
| 40 |
+
jnp.broadcast_to(static[None,:,:],(len(dets),*static.shape)),temporal_context],axis=-1)
|
| 41 |
+
h=jax.nn.silu(features@parameters['w1']+parameters['b1'])
|
| 42 |
+
h=jax.nn.silu(h@parameters['w2']+parameters['b2'])
|
| 43 |
+
delta=4*jnp.tanh((h@parameters['w3']+parameters['b3'])[...,0])
|
| 44 |
+
return (jax.nn.sigmoid(base_logits[None,:]+delta)*valid[None,:]).T
|
tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S040/training_sources/confidence_joint1/exact_d3__exact.py
ADDED
|
@@ -0,0 +1,213 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Exact detector-error-model contraction by bounded-frontier elimination."""
|
| 2 |
+
import collections
|
| 3 |
+
import numpy as np
|
| 4 |
+
import stim
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def parse_errors(dem):
|
| 8 |
+
errors = []
|
| 9 |
+
for ins in dem.flattened():
|
| 10 |
+
if ins.type != 'error':
|
| 11 |
+
continue
|
| 12 |
+
ds, logical = set(), 0
|
| 13 |
+
for t in ins.targets_copy():
|
| 14 |
+
if t.is_relative_detector_id():
|
| 15 |
+
ds.symmetric_difference_update([t.val])
|
| 16 |
+
elif t.is_logical_observable_id():
|
| 17 |
+
assert t.val == 0
|
| 18 |
+
logical ^= 1
|
| 19 |
+
errors.append((ds, logical, ins.args_copy()[0]))
|
| 20 |
+
return errors
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def elimination_order(dem, errors):
|
| 24 |
+
blocks = collections.defaultdict(list)
|
| 25 |
+
for d, c in dem.get_detector_coordinates().items():
|
| 26 |
+
blocks[c[-1]].append(d)
|
| 27 |
+
pending = [ds for ds, _, _ in errors if ds]
|
| 28 |
+
active, used, order = set(), set(), []
|
| 29 |
+
for _, block in sorted(blocks.items()):
|
| 30 |
+
remain = set(block)
|
| 31 |
+
while remain:
|
| 32 |
+
def score(d):
|
| 33 |
+
new = set().union(*(e for e in pending if d in e)) - used
|
| 34 |
+
return len(active | new), -sum(d in e for e in pending), d
|
| 35 |
+
d = min(remain, key=score)
|
| 36 |
+
related = [e for e in pending if d in e]
|
| 37 |
+
active |= set().union(*related) - used
|
| 38 |
+
active.discard(d)
|
| 39 |
+
pending = [e for e in pending if d not in e]
|
| 40 |
+
used.add(d)
|
| 41 |
+
remain.remove(d)
|
| 42 |
+
order.append(d)
|
| 43 |
+
assert sorted(order) == list(range(dem.num_detectors))
|
| 44 |
+
return order
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def make_plan(dem):
|
| 48 |
+
errors = parse_errors(dem)
|
| 49 |
+
order = elimination_order(dem, errors)
|
| 50 |
+
rank = {d: i for i, d in enumerate(order)}
|
| 51 |
+
groups = collections.defaultdict(list)
|
| 52 |
+
for source_index, (ds, logical, p) in enumerate(errors):
|
| 53 |
+
first = min(ds, key=rank.get) if ds else order[0]
|
| 54 |
+
groups[first].append((ds, logical, p, source_index))
|
| 55 |
+
slots, probabilities, masks, measured, source_indices = {}, [], [], [], []
|
| 56 |
+
width = 1
|
| 57 |
+
for d in order:
|
| 58 |
+
related = groups[d]
|
| 59 |
+
needed = set().union(*(ds for ds, _, _, _ in related)) | {d}
|
| 60 |
+
for node in sorted(needed):
|
| 61 |
+
if node not in slots:
|
| 62 |
+
free = next(i for i in range(1, 64) if i not in slots.values())
|
| 63 |
+
slots[node] = free
|
| 64 |
+
width = max(width, free+1)
|
| 65 |
+
for ds, logical, p, source_index in related:
|
| 66 |
+
mask = logical
|
| 67 |
+
for node in ds:
|
| 68 |
+
mask ^= 1 << slots[node]
|
| 69 |
+
probabilities.append(p)
|
| 70 |
+
masks.append(mask)
|
| 71 |
+
measured.append(-1)
|
| 72 |
+
source_indices.append(source_index)
|
| 73 |
+
probabilities.append(0)
|
| 74 |
+
masks.append(1 << slots.pop(d))
|
| 75 |
+
measured.append(d)
|
| 76 |
+
source_indices.append(-1)
|
| 77 |
+
assert not slots
|
| 78 |
+
return {'probabilities': np.array(probabilities, np.float32),
|
| 79 |
+
'masks': np.array(masks, np.int32), 'measured': np.array(measured, np.int32),
|
| 80 |
+
'width': np.array(width, np.int32), 'num_detectors': np.array(dem.num_detectors, np.int32),
|
| 81 |
+
'source_indices': np.array(source_indices, np.int32),
|
| 82 |
+
'order': np.array(order, np.int32)}
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def make_decoder(width):
|
| 86 |
+
import jax
|
| 87 |
+
import jax.numpy as jnp
|
| 88 |
+
indices = jnp.arange(1 << width, dtype=jnp.int32)
|
| 89 |
+
@jax.jit
|
| 90 |
+
def decode(dets, probabilities, masks, measured):
|
| 91 |
+
f = jnp.zeros((dets.shape[0], 1 << width), jnp.float32).at[:, 0].set(1)
|
| 92 |
+
def step(f, args):
|
| 93 |
+
p, mask, d = args
|
| 94 |
+
def error(f):
|
| 95 |
+
prob = p[:, None] if p.ndim else p
|
| 96 |
+
return (1-prob)*f + prob*f[:, indices ^ mask]
|
| 97 |
+
def project(f):
|
| 98 |
+
obs = dets[:, d].astype(jnp.int32)
|
| 99 |
+
dst = (indices[None, :] & ~mask) | (obs[:, None]*mask)
|
| 100 |
+
g = jnp.take_along_axis(f, dst, axis=1) * ((indices & mask)==0)
|
| 101 |
+
return g / jnp.maximum(jnp.sum(g, axis=1, keepdims=True), 1e-30)
|
| 102 |
+
return jax.lax.cond(d < 0, error, project, f), None
|
| 103 |
+
f, _ = jax.lax.scan(step, f, (probabilities, masks, measured))
|
| 104 |
+
return jnp.sum(f[:, 1::2], axis=1) / jnp.maximum(jnp.sum(f, axis=1), 1e-30)
|
| 105 |
+
return decode
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def make_marginals(width):
|
| 109 |
+
"""Per-shot derivatives of log syndrome probability give all error marginals."""
|
| 110 |
+
import jax
|
| 111 |
+
import jax.numpy as jnp
|
| 112 |
+
indices = jnp.arange(1 << width, dtype=jnp.int32)
|
| 113 |
+
def log_partition(dets, probabilities, masks, measured):
|
| 114 |
+
f = jnp.zeros(1 << width, jnp.float32).at[0].set(1)
|
| 115 |
+
def step(carry, args):
|
| 116 |
+
f, logz = carry
|
| 117 |
+
p, mask, d = args
|
| 118 |
+
def error(carry):
|
| 119 |
+
f, logz = carry
|
| 120 |
+
return ((1-p)*f + p*f[indices ^ mask], logz)
|
| 121 |
+
def project(carry):
|
| 122 |
+
f, logz = carry
|
| 123 |
+
dst = (indices & ~mask) | (dets[d].astype(jnp.int32)*mask)
|
| 124 |
+
g = f[dst] * ((indices & mask)==0)
|
| 125 |
+
norm = jnp.maximum(jnp.sum(g), 1e-30)
|
| 126 |
+
return g/norm, logz+jnp.log(norm)
|
| 127 |
+
return jax.lax.cond(d<0, error, project, carry), None
|
| 128 |
+
(_, logz), _ = jax.lax.scan(jax.checkpoint(step), (f, jnp.float32(0)), (probabilities, masks, measured))
|
| 129 |
+
return logz
|
| 130 |
+
return jax.jit(jax.vmap(jax.value_and_grad(log_partition, argnums=1), in_axes=(0,None,None,None)))
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
def make_marginals_fb(width, return_observable=False):
|
| 134 |
+
"""Forward/backward contraction without generic gather-gradient scatter."""
|
| 135 |
+
import jax
|
| 136 |
+
import jax.numpy as jnp
|
| 137 |
+
indices = jnp.arange(1 << width, dtype=jnp.int32)
|
| 138 |
+
# The syndrome likelihood marginalizes the unobserved logical bit. Keep
|
| 139 |
+
# that bit in the forward state for its output, but omit it from histories
|
| 140 |
+
# and backward messages, halving the largest buffers.
|
| 141 |
+
backward_width=width-1 if return_observable else width
|
| 142 |
+
backward_indices=jnp.arange(1 << backward_width,dtype=jnp.int32)
|
| 143 |
+
@jax.jit
|
| 144 |
+
def marginals(dets, probabilities, masks, measured):
|
| 145 |
+
f=jnp.zeros((dets.shape[0],1<<width),jnp.float32).at[:,0].set(1)
|
| 146 |
+
def forward(carry,args):
|
| 147 |
+
f,logz=carry
|
| 148 |
+
p,mask,d=args
|
| 149 |
+
def error(carry):
|
| 150 |
+
f,logz=carry
|
| 151 |
+
prob=p[:,None] if p.ndim else p
|
| 152 |
+
return ((1-prob)*f+prob*f[:,indices^mask],logz)
|
| 153 |
+
def project(carry):
|
| 154 |
+
f,logz=carry
|
| 155 |
+
dst=(indices[None,:]&~mask)|(dets[:,d,None].astype(jnp.int32)*mask)
|
| 156 |
+
g=jnp.take_along_axis(f,dst,axis=1)*((indices&mask)==0)
|
| 157 |
+
norm=jnp.maximum(g.sum(axis=1),1e-30)
|
| 158 |
+
return g/norm[:,None],logz+jnp.log(norm)
|
| 159 |
+
out=jax.lax.cond(d<0,error,project,carry)
|
| 160 |
+
return out,(f[:,::2]+f[:,1::2]) if return_observable else f
|
| 161 |
+
(final,logz),history=jax.lax.scan(forward,(f,jnp.zeros(len(dets))),(probabilities,masks,measured))
|
| 162 |
+
def backward(b,args):
|
| 163 |
+
p,mask,d,f=args
|
| 164 |
+
def error(b):
|
| 165 |
+
flipped=b[:,backward_indices^mask]
|
| 166 |
+
prob=p[:,None] if p.ndim else p
|
| 167 |
+
prior=(1-prob)*b+prob*flipped
|
| 168 |
+
norm=jnp.maximum(jnp.sum(f*prior,axis=1),1e-30)
|
| 169 |
+
q=p*jnp.sum(f*flipped,axis=1)/norm
|
| 170 |
+
grad=(q-p)/jnp.maximum(p*(1-p),1e-20)
|
| 171 |
+
return prior/norm[:,None],grad
|
| 172 |
+
def project(b):
|
| 173 |
+
prior=b[:,backward_indices&~mask]*((backward_indices[None,:]&mask)==(dets[:,d,None].astype(jnp.int32)*mask))
|
| 174 |
+
norm=jnp.maximum(jnp.sum(f*prior,axis=1),1e-30)
|
| 175 |
+
return prior/norm[:,None],jnp.zeros(len(dets))
|
| 176 |
+
return jax.lax.cond(d<0,error,project,b)
|
| 177 |
+
backward_masks=masks>>1 if return_observable else masks
|
| 178 |
+
_,grad=jax.lax.scan(backward,jnp.ones((len(dets),1<<backward_width),jnp.float32),
|
| 179 |
+
(probabilities,backward_masks,measured,history),reverse=True)
|
| 180 |
+
if return_observable:
|
| 181 |
+
return logz,grad.T,jnp.sum(final[:,1::2],axis=1)/jnp.maximum(jnp.sum(final,axis=1),1e-30)
|
| 182 |
+
return logz,grad.T
|
| 183 |
+
return marginals
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
def predict(plan, packed, decoder=None, batch=256):
|
| 187 |
+
import jax
|
| 188 |
+
decoder = decoder or make_decoder(int(plan['width']))
|
| 189 |
+
dets = np.unpackbits(packed, bitorder='little', axis=1, count=int(plan['num_detectors']))
|
| 190 |
+
args = [jax.device_put(plan[k]) for k in ['probabilities', 'masks', 'measured']]
|
| 191 |
+
result = []
|
| 192 |
+
for start in range(0, len(dets), batch):
|
| 193 |
+
ds = dets[start:start+batch]
|
| 194 |
+
ds = np.pad(ds, ((0, batch-len(ds)), (0, 0)))
|
| 195 |
+
result.append(np.asarray(decoder(ds, *args))[:min(batch, len(dets)-start)])
|
| 196 |
+
return np.concatenate(result)
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
if __name__ == '__main__':
|
| 200 |
+
import sys, time
|
| 201 |
+
from pathlib import Path
|
| 202 |
+
import jax
|
| 203 |
+
print(jax.devices(), flush=True)
|
| 204 |
+
path = Path(sys.argv[1])
|
| 205 |
+
dem = stim.DetectorErrorModel.from_file(path/'pij_from_even_for_odd.dem')
|
| 206 |
+
plan = make_plan(dem)
|
| 207 |
+
print({k: v.shape if v.ndim else int(v) for k, v in plan.items()}, flush=True)
|
| 208 |
+
a = np.load(path/'arrays.npz')
|
| 209 |
+
decoder = make_decoder(int(plan['width']))
|
| 210 |
+
for i in range(2):
|
| 211 |
+
t = time.time()
|
| 212 |
+
p = predict(plan, a['detectors'][:1024], decoder)
|
| 213 |
+
print({'seconds': time.time()-t, 'failure': np.mean((p>=.5)!=a['labels'][:len(p)]), 'min': p.min(), 'max': p.max()}, flush=True)
|
tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S040/training_sources/confidence_joint1/learned_d5__confidence_joint.py
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Prototype confidence-aware gate; not yet a trained or queued candidate."""
|
| 2 |
+
import jax.numpy as jnp
|
| 3 |
+
from joint_mixture import gate_features as syndrome_features
|
| 4 |
+
from joint_mixture import initialize_gate as initialize_base_gate
|
| 5 |
+
from joint_mixture import gate_logit, mixture_terms, mix_predictions
|
| 6 |
+
|
| 7 |
+
GATE_FEATURES = 45
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def confidence_features(predictions):
|
| 11 |
+
"""Four bounded shot-local features; no labels or batch statistics."""
|
| 12 |
+
p = jnp.clip(predictions, 1e-6, 1-1e-6)
|
| 13 |
+
z = jnp.clip(jnp.log(p)-jnp.log1p(-p), -8., 8.)/8
|
| 14 |
+
return jnp.concatenate([z,jnp.sqrt(z*z+1e-4)],axis=1)
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def gate_features(dets, grid, static, predictions):
|
| 18 |
+
result = jnp.concatenate([syndrome_features(dets,grid,static),confidence_features(predictions)],axis=1)
|
| 19 |
+
assert result.shape==(len(dets),GATE_FEATURES)
|
| 20 |
+
return result
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def initialize_gate(seed, hidden=32):
|
| 24 |
+
"""Preserve the original seeded 41-input trunk; append zero new-input rows."""
|
| 25 |
+
gate = initialize_base_gate(seed,hidden)
|
| 26 |
+
gate['w1'] = jnp.concatenate([gate['w1'],jnp.zeros((4,hidden),gate['w1'].dtype)],axis=0)
|
| 27 |
+
return gate
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def expert_adjoint_factors(losses, labels, responsibility, gate_prediction_adjoint):
|
| 31 |
+
"""Per-shot factors on expert BCE adjoints, including the confidence path.
|
| 32 |
+
|
| 33 |
+
gate_prediction_adjoint is dL/dq through the gate only, for each per-shot
|
| 34 |
+
loss (not its batch mean). dq/dedge=(1-2*y)*exp(-BCE)*dBCE/dedge.
|
| 35 |
+
Labels enter this loss derivative only; all gate inputs use predictions.
|
| 36 |
+
"""
|
| 37 |
+
sign = 1-2*labels.astype(losses.dtype)
|
| 38 |
+
return responsibility+sign[:,None]*jnp.exp(-losses)*gate_prediction_adjoint
|
tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S040/training_sources/confidence_joint1/learned_d5__confidence_joint_gradient.py
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Prototype complete gate/expert chain rule through confidence features."""
|
| 2 |
+
import jax
|
| 3 |
+
import jax.numpy as jnp
|
| 4 |
+
from confidence_joint import gate_features, gate_logit, mixture_terms, mix_predictions, expert_adjoint_factors
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def make_gradient(probabilities, exact_gradient):
|
| 8 |
+
@jax.jit
|
| 9 |
+
def gradient(parameters,dets,labels,base,context,static,valid,masks,measured,
|
| 10 |
+
grid,measurement_indices,counts):
|
| 11 |
+
arguments = (dets,base,context,static,valid,grid,measurement_indices,counts)
|
| 12 |
+
p0,pull0 = jax.vjp(lambda w:probabilities(w,*arguments),parameters['expert0'])
|
| 13 |
+
loss0,pred0,g0 = exact_gradient(dets,labels,p0,masks,measured)
|
| 14 |
+
p1,pull1 = jax.vjp(lambda w:probabilities(w,*arguments),parameters['expert1'])
|
| 15 |
+
loss1,pred1,g1 = exact_gradient(dets,labels,p1,masks,measured)
|
| 16 |
+
losses = jnp.stack([loss0,loss1],axis=1)
|
| 17 |
+
predictions = jnp.stack([pred0,pred1],axis=1)
|
| 18 |
+
logit,pull_gate = jax.vjp(lambda w,q:gate_logit(w,gate_features(dets,grid,static,q)),
|
| 19 |
+
parameters['gate'],predictions)
|
| 20 |
+
loss,responsibility,adjoint,coefficients = mixture_terms(losses,logit)
|
| 21 |
+
# Each gate output depends only on its own shot, so this VJP yields
|
| 22 |
+
# per-shot prediction adjoints and the sum of parameter gradients.
|
| 23 |
+
gate_sum,extra_prediction_adjoint = pull_gate(adjoint)
|
| 24 |
+
factors = expert_adjoint_factors(losses,labels,responsibility,extra_prediction_adjoint)
|
| 25 |
+
batch = len(dets)
|
| 26 |
+
gradients = {'expert0':pull0(g0*factors[:,0][None]/batch)[0],
|
| 27 |
+
'expert1':pull1(g1*factors[:,1][None]/batch)[0],
|
| 28 |
+
'gate':jax.tree_util.tree_map(lambda x:x/batch,gate_sum)}
|
| 29 |
+
prediction = mix_predictions(predictions,logit)
|
| 30 |
+
return gradients,loss.mean(),jnp.mean((prediction>=.5)!=labels),coefficients.mean(axis=0)
|
| 31 |
+
return gradient
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def make_infer(probabilities,exact_decode):
|
| 35 |
+
@jax.jit
|
| 36 |
+
def infer(parameters,dets,base,context,static,valid,masks,measured,
|
| 37 |
+
grid,measurement_indices,counts):
|
| 38 |
+
arguments = (dets,base,context,static,valid,grid,measurement_indices,counts)
|
| 39 |
+
q = jnp.stack([exact_decode(dets,probabilities(parameters[key],*arguments),masks,measured)
|
| 40 |
+
for key in ['expert0','expert1']],axis=1)
|
| 41 |
+
logit = gate_logit(parameters['gate'],gate_features(dets,grid,static,q))
|
| 42 |
+
return mix_predictions(q,logit)
|
| 43 |
+
return infer
|
tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S040/training_sources/confidence_joint1/learned_d5__confidence_joint_state.py
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Serialization and distinct Adam clocks for two experts and a new gate."""
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
import hashlib
|
| 4 |
+
import numpy as np
|
| 5 |
+
import jax
|
| 6 |
+
import jax.numpy as jnp
|
| 7 |
+
import optax
|
| 8 |
+
from confidence_joint import initialize_gate
|
| 9 |
+
|
| 10 |
+
PARTS = ('expert0', 'expert1', 'gate')
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def save_weights(path, parameters):
|
| 14 |
+
np.savez(path, **{part + '__' + key: np.asarray(value)
|
| 15 |
+
for part, values in parameters.items() for key, value in values.items()})
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def load_weights(path):
|
| 19 |
+
result = {part: {} for part in PARTS}
|
| 20 |
+
with np.load(path, allow_pickle=False) as saved:
|
| 21 |
+
for key in saved.files:
|
| 22 |
+
part, name = key.split('__', 1)
|
| 23 |
+
result[part][name] = jnp.asarray(saved[key])
|
| 24 |
+
assert all(result.values())
|
| 25 |
+
return result
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def save_state(path, state):
|
| 29 |
+
leaves, _ = jax.tree_util.tree_flatten(state)
|
| 30 |
+
np.savez(path, **{f'arr_{i}': np.asarray(leaf) for i, leaf in enumerate(leaves)})
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def load_state(path, template):
|
| 34 |
+
leaves, tree = jax.tree_util.tree_flatten(template)
|
| 35 |
+
loaded = []
|
| 36 |
+
with np.load(path, allow_pickle=False) as saved:
|
| 37 |
+
assert set(saved.files) == {f'arr_{i}' for i in range(len(leaves))}
|
| 38 |
+
for i, leaf in enumerate(leaves):
|
| 39 |
+
value = saved[f'arr_{i}']
|
| 40 |
+
assert value.shape == leaf.shape and value.dtype == leaf.dtype
|
| 41 |
+
loaded.append(jnp.asarray(value))
|
| 42 |
+
return jax.tree_util.tree_unflatten(tree, loaded)
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def initialize(parent_paths, seed, expert_lr, gate_lr):
|
| 46 |
+
assert len(parent_paths) == 2
|
| 47 |
+
parameters = {'gate': initialize_gate(seed)}
|
| 48 |
+
state = {}
|
| 49 |
+
records = []
|
| 50 |
+
for i, path in enumerate(map(Path, parent_paths)):
|
| 51 |
+
key = f'expert{i}'
|
| 52 |
+
with np.load(path, allow_pickle=False) as saved:
|
| 53 |
+
parameters[key] = {name: jnp.asarray(saved[name]) for name in saved.files}
|
| 54 |
+
assert set(parameters[key]) == {'w1', 'b1', 'w2', 'b2', 'w3', 'b3'}
|
| 55 |
+
assert parameters[key]['w1'].shape == (394, 64)
|
| 56 |
+
original = optax.chain(optax.clip_by_global_norm(1), optax.adamw(expert_lr, weight_decay=1e-4))
|
| 57 |
+
optimizer_path = path.with_name(path.name.replace('weights-', 'optimizer-'))
|
| 58 |
+
original_state = load_state(optimizer_path, original.init(parameters[key]))
|
| 59 |
+
state[key] = original_state[1]
|
| 60 |
+
records.append({'part': key, 'weights': str(path), 'weights_sha256': hashlib.sha256(path.read_bytes()).hexdigest(),
|
| 61 |
+
'optimizer': str(optimizer_path), 'optimizer_sha256': hashlib.sha256(optimizer_path.read_bytes()).hexdigest(),
|
| 62 |
+
'initial_adam_count': int(state[key][0].count), 'moments_restored': True})
|
| 63 |
+
state['gate'] = optax.adamw(gate_lr, weight_decay=1e-4).init(parameters['gate'])
|
| 64 |
+
return parameters, state, records
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def make_apply(expert_lr, gate_lr):
|
| 68 |
+
optimizers = {part: optax.adamw(gate_lr if part == 'gate' else expert_lr, weight_decay=1e-4) for part in PARTS}
|
| 69 |
+
clip = optax.clip_by_global_norm(1)
|
| 70 |
+
@jax.jit
|
| 71 |
+
def apply(parameters, state, gradients):
|
| 72 |
+
norm = optax.global_norm(gradients)
|
| 73 |
+
gradients, _ = clip.update(gradients, clip.init(parameters), parameters)
|
| 74 |
+
new_parameters, new_state = {}, {}
|
| 75 |
+
for part in PARTS:
|
| 76 |
+
updates, new_state[part] = optimizers[part].update(gradients[part], state[part], parameters[part])
|
| 77 |
+
new_parameters[part] = optax.apply_updates(parameters[part], updates)
|
| 78 |
+
return new_parameters, new_state, norm
|
| 79 |
+
return apply
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def counts(state):
|
| 83 |
+
return {part: int(state[part][0].count) for part in PARTS}
|
tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S040/training_sources/confidence_joint1/learned_d5__confidence_joint_train.py
ADDED
|
@@ -0,0 +1,145 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Matched joint BCE training with syndrome and expert-confidence gate inputs."""
|
| 2 |
+
import os
|
| 3 |
+
os.environ['OPENBLAS_NUM_THREADS'] = '1'
|
| 4 |
+
os.environ['OMP_NUM_THREADS'] = '1'
|
| 5 |
+
os.environ['XLA_PYTHON_CLIENT_PREALLOCATE'] = 'false'
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
import argparse
|
| 8 |
+
import hashlib
|
| 9 |
+
import json
|
| 10 |
+
import shutil
|
| 11 |
+
import sys
|
| 12 |
+
import time
|
| 13 |
+
import numpy as np
|
| 14 |
+
import jax
|
| 15 |
+
from model import probabilities
|
| 16 |
+
from data import load_all
|
| 17 |
+
from confidence_joint_gradient import make_gradient, make_infer
|
| 18 |
+
from confidence_joint_state import initialize, make_apply, save_weights, load_weights, save_state, load_state, counts
|
| 19 |
+
|
| 20 |
+
root = Path(__file__).resolve().parent
|
| 21 |
+
research = root.parent
|
| 22 |
+
sys.path.insert(0, str(research / 'learned_exact'))
|
| 23 |
+
from checkpoint_gradient import make_loss_and_grad
|
| 24 |
+
from exact import make_decoder
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def main():
|
| 28 |
+
parser = argparse.ArgumentParser()
|
| 29 |
+
parser.add_argument('--parents', type=Path, nargs=2, required=True)
|
| 30 |
+
parser.add_argument('--output', type=Path, required=True)
|
| 31 |
+
parser.add_argument('--training-cache', type=Path, required=True)
|
| 32 |
+
parser.add_argument('--resume', type=Path)
|
| 33 |
+
parser.add_argument('--steps', type=int, default=2048)
|
| 34 |
+
parser.add_argument('--batch', type=int, default=1024)
|
| 35 |
+
parser.add_argument('--expert-lr', type=float, default=.0001)
|
| 36 |
+
parser.add_argument('--gate-lr', type=float, default=.001)
|
| 37 |
+
parser.add_argument('--gate-seed', type=int, default=20261310)
|
| 38 |
+
parser.add_argument('--seed', type=int, default=20261311)
|
| 39 |
+
parser.add_argument('--eval-every', type=int, default=512)
|
| 40 |
+
parser.add_argument('--validation-shots', type=int, default=1024)
|
| 41 |
+
parser.add_argument('--validation-batch', type=int, default=512)
|
| 42 |
+
args = parser.parse_args()
|
| 43 |
+
args.output.mkdir(exist_ok=False)
|
| 44 |
+
config = {key: ([str(p) for p in value] if key == 'parents' else str(value) if isinstance(value, Path) else value)
|
| 45 |
+
for key, value in vars(args).items()}
|
| 46 |
+
source_paths = [root / name for name in ['joint_mixture.py', 'confidence_joint.py', 'confidence_joint_gradient.py', 'confidence_joint_state.py',
|
| 47 |
+
'confidence_joint_train.py', 'model.py', 'data.py']]
|
| 48 |
+
source_paths += [research / 'learned_exact/checkpoint_gradient.py', research / 'exact_d3/exact.py']
|
| 49 |
+
snapshot = args.output / 'training_source'; snapshot.mkdir()
|
| 50 |
+
hashes = {}
|
| 51 |
+
for source in source_paths:
|
| 52 |
+
name = str(source.relative_to(research)).replace('/', '__')
|
| 53 |
+
shutil.copyfile(source, snapshot / name)
|
| 54 |
+
hashes[name] = hashlib.sha256(source.read_bytes()).hexdigest()
|
| 55 |
+
parameters, state, parent_records = initialize(args.parents, args.gate_seed, args.expert_lr, args.gate_lr)
|
| 56 |
+
rng = np.random.default_rng(args.seed)
|
| 57 |
+
if args.resume:
|
| 58 |
+
old = json.loads((args.resume.parent / 'run_config.json').read_text())
|
| 59 |
+
for key in ['parents', 'expert_lr', 'gate_lr', 'gate_seed', 'seed', 'batch', 'training_cache']:
|
| 60 |
+
assert old[key] == config[key], key
|
| 61 |
+
parameters = load_weights(args.resume)
|
| 62 |
+
state = load_state(args.resume.with_name(args.resume.name.replace('weights-', 'optimizer-')), state)
|
| 63 |
+
rng.bit_generator.state = json.loads(args.resume.with_name(args.resume.name.replace('weights-', 'rng-')).with_suffix('.json').read_text())
|
| 64 |
+
config.update(training_source_sha256=hashes, parent_records=parent_records, initial_adam_counts=counts(state),
|
| 65 |
+
initialization='Both experts copied with exact Adam state from declared session-trained parents; new gate retains the original seeded 41-input hidden weights, appends four zero confidence-input rows, and has zero output, giving the same initial equal mixture',
|
| 66 |
+
sampling='Same seed and draws as syndrome-only joint_mixture1; resumed phases restore only their own saved sampling state',
|
| 67 |
+
runtime_versions={'jax': jax.__version__, 'numpy': np.__version__})
|
| 68 |
+
(args.output / 'run_config.json').write_text(json.dumps(config, indent=2) + '\n')
|
| 69 |
+
started = time.time()
|
| 70 |
+
dataset = load_all(prior_pass=3, training_cache=args.training_cache)
|
| 71 |
+
assert len(dataset) == 26
|
| 72 |
+
print(json.dumps({'loaded_conditions': len(dataset), 'seconds': time.time() - started}), flush=True)
|
| 73 |
+
seen = [np.zeros(len(item['train_labels']), bool) for item in dataset]
|
| 74 |
+
os.environ['XLA_PYTHON_CLIENT_PREALLOCATE'] = 'true'
|
| 75 |
+
os.environ['XLA_PYTHON_CLIENT_MEM_FRACTION'] = '0.90'
|
| 76 |
+
gradient = make_gradient(probabilities, make_loss_and_grad(14, 32))
|
| 77 |
+
infer = make_infer(probabilities, make_decoder(14))
|
| 78 |
+
apply = make_apply(args.expert_lr, args.gate_lr)
|
| 79 |
+
feature_names = ['context', 'static', 'valid', 'masks', 'measured', 'grid', 'measurement_indices', 'counts']
|
| 80 |
+
|
| 81 |
+
def feature_values(item):
|
| 82 |
+
length = ((int(item['operation_count']) + 511) // 512) * 512
|
| 83 |
+
return length, [item[k][:length] for k in feature_names[:5]] + [item[k] for k in feature_names[5:]]
|
| 84 |
+
|
| 85 |
+
def evaluate(step):
|
| 86 |
+
results = []; beginning = time.time()
|
| 87 |
+
for item in dataset:
|
| 88 |
+
n = min(args.validation_shots, len(item['validation_labels']))
|
| 89 |
+
selected = np.random.default_rng(20261102).choice(len(item['validation_labels']), n, replace=False)
|
| 90 |
+
length, features = feature_values(item)
|
| 91 |
+
parts = []
|
| 92 |
+
for begin in range(0, n, args.validation_batch):
|
| 93 |
+
ix = selected[begin:begin + args.validation_batch]; size = len(ix)
|
| 94 |
+
ds = np.pad(item['validation_dets'][ix], ((0, args.validation_batch - size), (0, 0)))
|
| 95 |
+
base = np.pad(item['validation_base_logits'][ix, :length], ((0, args.validation_batch - size), (0, 0)))
|
| 96 |
+
parts.append(np.asarray(infer(parameters, ds, base, *features))[:size])
|
| 97 |
+
p = np.concatenate(parts); y = item['validation_labels'][selected].astype(np.float64)
|
| 98 |
+
pp = np.clip(p.astype(np.float64), 1e-7, 1 - 1e-7)
|
| 99 |
+
results.append({'condition': item['row']['name'], 'failure': float(np.mean((p >= .5) != y)),
|
| 100 |
+
'negative_log_likelihood': float(np.mean(-y * np.log(pp) - (1 - y) * np.log1p(-pp)))})
|
| 101 |
+
report = {'step': step, 'validation_failure': float(np.mean([r['failure'] for r in results])),
|
| 102 |
+
'negative_log_likelihood': float(np.mean([r['negative_log_likelihood'] for r in results])),
|
| 103 |
+
'conditions': results, 'seconds': time.time() - beginning}
|
| 104 |
+
(args.output / f'validation-{step}.json').write_text(json.dumps(report, indent=2) + '\n')
|
| 105 |
+
save_weights(args.output / f'weights-{step}.npz', parameters)
|
| 106 |
+
save_state(args.output / f'optimizer-{step}.npz', state)
|
| 107 |
+
(args.output / f'rng-{step}.json').write_text(json.dumps(rng.bit_generator.state) + '\n')
|
| 108 |
+
(args.output / f'checkpoint-{step}.json').write_text(json.dumps({
|
| 109 |
+
'step': step, 'training_draws': step * args.batch, 'adam_counts': counts(state),
|
| 110 |
+
'distinct_phase_rows': sum(int(mask.sum()) for mask in seen),
|
| 111 |
+
'distinct_by_condition': {item['row']['name']: int(mask.sum()) for item, mask in zip(dataset, seen)},
|
| 112 |
+
'weights_sha256': hashlib.sha256((args.output / f'weights-{step}.npz').read_bytes()).hexdigest(), 'complete': True}, indent=2) + '\n')
|
| 113 |
+
print(json.dumps({k: v for k, v in report.items() if k != 'conditions'}), flush=True)
|
| 114 |
+
|
| 115 |
+
evaluate(0)
|
| 116 |
+
records = []
|
| 117 |
+
for step in range(1, args.steps + 1):
|
| 118 |
+
condition = int(rng.integers(len(dataset))); item = dataset[condition]
|
| 119 |
+
ix = rng.integers(len(item['train_labels']), size=args.batch); seen[condition][ix] = True
|
| 120 |
+
length, features = feature_values(item)
|
| 121 |
+
gradients, loss, error, coefficients = gradient(parameters, item['train_dets'][ix], item['train_labels'][ix],
|
| 122 |
+
item['train_base_logits'][ix, :length], *features)
|
| 123 |
+
parameters, state, norm = apply(parameters, state, gradients)
|
| 124 |
+
if step == 1 or step % 16 == 0:
|
| 125 |
+
record = {'step': step, 'loss': float(loss), 'error': float(error), 'gradient_norm': float(norm),
|
| 126 |
+
'mean_coefficients': np.asarray(coefficients).tolist(), 'elapsed': time.time() - started}
|
| 127 |
+
assert np.isfinite(record['loss']) and np.isfinite(record['gradient_norm'])
|
| 128 |
+
records.append(record); print(json.dumps(record), flush=True)
|
| 129 |
+
if step % args.eval_every == 0 or step == args.steps:
|
| 130 |
+
evaluate(step)
|
| 131 |
+
provenance = {'run_config': config, 'parent_provenance': [json.loads((p.parent / 'provenance.json').read_text()) for p in args.parents],
|
| 132 |
+
'training': 'All516880 supplied d5 training rows eligible; uniform condition and row sampling with replacement',
|
| 133 |
+
'training_shots': sum(len(item['train_labels']) for item in dataset),
|
| 134 |
+
'distinct_phase_rows': sum(int(mask.sum()) for mask in seen),
|
| 135 |
+
'loss': 'Conditional logical BCE of two trainable exact-decoder probabilities; responsibilities and the complete expert-confidence gate chain rule scale expert BCE gradients; free gate-logit adjoint is coefficient minus responsibility',
|
| 136 |
+
'optimizer': 'Separate restored expert AdamW states and fresh gate AdamW; one global norm1 clipping over the full joint gradient, weight_decay1e-4; rates in run_config',
|
| 137 |
+
'gate': '41 fixed-scale syndrome/basis/duration features plus two expert clipped logits/8 and their smooth absolute values;45 inputs,32-unit SiLU hidden layer,one free logit,other logit zero;no label/ID/position features;confidence features are fully differentiated',
|
| 138 |
+
'validation': 'Uniform1024-shot per-condition screens by default, seed20261102; full validation required for checkpoint selection',
|
| 139 |
+
'independence': 'This joint model uses all training rows; it does not retain the reserved-parent training-label holdout claim',
|
| 140 |
+
'test_data_used': False, 'records': records, 'seconds': time.time() - started}
|
| 141 |
+
(args.output / 'provenance.json').write_text(json.dumps(provenance, indent=2) + '\n')
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
if __name__ == '__main__':
|
| 145 |
+
main()
|
tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S040/training_sources/confidence_joint1/learned_d5__data.py
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Static physical features and authorized cached training/validation priors."""
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
import json,sys
|
| 4 |
+
import numpy as np
|
| 5 |
+
import stim
|
| 6 |
+
sys.path.insert(0,'/workspace/research/exact_d3')
|
| 7 |
+
from exact import parse_errors
|
| 8 |
+
from conditional import load_state
|
| 9 |
+
|
| 10 |
+
ROOT=Path(__file__).resolve().parent
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def build_features(row,package,max_ops=2048):
|
| 14 |
+
dem=stim.DetectorErrorModel.from_file(Path('/workspace/data/train')/row['noise'])
|
| 15 |
+
errors=parse_errors(dem);coords=dem.get_detector_coordinates()
|
| 16 |
+
if row['rounds']==1:
|
| 17 |
+
plan=dict(np.load(package/f"plans/{row['name']}.npz"));supports=[(ds,l) for ds,l,p in errors]
|
| 18 |
+
measured=plan['measured']
|
| 19 |
+
else:
|
| 20 |
+
state=load_state(package/f"conditional_plans/{row['name']}.npz");plan=state['on']
|
| 21 |
+
on=set(state['on_indices'].tolist());groups={}
|
| 22 |
+
for ds,l,p in errors:
|
| 23 |
+
key=tuple(sorted(ds&on)),l
|
| 24 |
+
if key[0] or key[1]:groups.setdefault(key,len(groups))
|
| 25 |
+
supports=list(groups)
|
| 26 |
+
measured=np.where(plan['measured']>=0,state['on_indices'][np.maximum(plan['measured'],0)],-1)
|
| 27 |
+
assert int(plan['width'])<=14
|
| 28 |
+
circuit=stim.Circuit.from_file(Path('/workspace/data/train')/row['circuit'])
|
| 29 |
+
qubits=circuit.get_final_qubit_coordinates()
|
| 30 |
+
first=next(ins for ins in circuit.flattened() if ins.name in ['M','MX','MR','MRX'])
|
| 31 |
+
spaces=sorted(tuple(qubits[t.value][:2]) for t in first.targets_copy());assert len(spaces)==24
|
| 32 |
+
idx={(int(c[2]),tuple(c[:2])):d for d,c in coords.items()}
|
| 33 |
+
context=np.full((max_ops,120),600,np.int32);static=np.zeros((max_ops,129),np.float32)
|
| 34 |
+
n=len(plan['masks']);assert n<=max_ops
|
| 35 |
+
for op,source in enumerate(plan['source_indices']):
|
| 36 |
+
if source<0:continue
|
| 37 |
+
ds,logical=supports[source];t=min(int(coords[d][2]) for d in ds) if ds else 0
|
| 38 |
+
for dt in range(-2,3):
|
| 39 |
+
for s,space in enumerate(spaces):context[op,(dt+2)*24+s]=idx.get((t+dt,space),600)
|
| 40 |
+
for d in ds:
|
| 41 |
+
c=coords[d];static[op,(int(c[2])-t+2)*24+spaces.index(tuple(c[:2]))]=1
|
| 42 |
+
p=float(plan['probabilities'][op]);static[op,120]=np.log(max(p,1e-7)/max(1-p,1e-7))/8
|
| 43 |
+
static[op,121:]=[logical,len(ds)/4,t/25,row['rounds']/25,t==0,t>=row['rounds']-1,row['basis']=='X',1]
|
| 44 |
+
grid=np.full((26,24),600,np.int32);measurement_indices=np.full(601,624,np.int32)
|
| 45 |
+
for d,c in coords.items():
|
| 46 |
+
t=int(c[2]);s=spaces.index(tuple(c[:2]));grid[t,s]=d;measurement_indices[d]=t*24+s
|
| 47 |
+
return {'context':context,'static':static,'masks':np.pad(plan['masks'],(0,max_ops-n)),
|
| 48 |
+
'measured':np.pad(measured,(0,max_ops-n),constant_values=-1),
|
| 49 |
+
'valid':np.pad((plan['source_indices']>=0).astype(np.float32),(0,max_ops-n)),
|
| 50 |
+
'grid':grid,'measurement_indices':measurement_indices,
|
| 51 |
+
'counts':np.maximum((grid!=600).sum(axis=0),1).astype(np.float32),'operation_count':np.array(n,np.int32)}
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def load_all(splits=('train','validation'),max_ops=2048,prior_pass=1,training_cache=None):
|
| 55 |
+
assert prior_pass in [1,3,5]
|
| 56 |
+
assert training_cache is None or prior_pass in [1,3]
|
| 57 |
+
rows=[r for r in json.loads(Path('/workspace/data/train/manifest.json').read_text())['conditions'] if r['distance']==5]
|
| 58 |
+
package=Path(json.loads(Path('/workspace/research/CURRENT.json').read_text())['package'])
|
| 59 |
+
plans=ROOT/'feature_plans';plans.mkdir(exist_ok=True);items=[]
|
| 60 |
+
for row in rows:
|
| 61 |
+
path=plans/f"{row['name']}.npz"
|
| 62 |
+
if not path.exists():np.savez(path,**build_features(row,package,max_ops))
|
| 63 |
+
item=dict(np.load(path,allow_pickle=False));item['row']=row
|
| 64 |
+
if splits:
|
| 65 |
+
cache=np.load(Path('/workspace/research/exact_d3/turbo_cache')/f"{row['name']}.npz")
|
| 66 |
+
feedback=np.load(Path('/workspace/research/exact_d3/feedback5_cache')/f"{row['name']}.npz") if prior_pass>1 else None
|
| 67 |
+
for split in splits:
|
| 68 |
+
assert split in ['train','validation']
|
| 69 |
+
arrays=np.load(Path('/workspace/data')/split/row['arrays'])
|
| 70 |
+
if split=='train' and training_cache is not None:
|
| 71 |
+
full=np.load(Path(training_cache)/f"{row['name']}.npz",allow_pickle=False)
|
| 72 |
+
indices=full['indices'];p=full[f'priors{prior_pass}']
|
| 73 |
+
assert np.array_equal(arrays['sample_ids'][indices],full['sample_ids'])
|
| 74 |
+
physical_prediction=full['probabilities3']
|
| 75 |
+
else:
|
| 76 |
+
indices=cache['train4096_indices'] if split=='train' else np.arange(len(arrays['labels']))
|
| 77 |
+
key='train4096' if split=='train' else 'validation'
|
| 78 |
+
p=cache[key+'_on_prior'] if prior_pass==1 else feedback[f'{key}_priors{prior_pass}']
|
| 79 |
+
physical_prediction=cache[key][:,0] if prior_pass==1 else feedback[key][:,prior_pass-1]
|
| 80 |
+
assert p.shape[1]==int(item['operation_count'])
|
| 81 |
+
if feedback is not None:assert np.array_equal(feedback['train4096_indices'],cache['train4096_indices'])
|
| 82 |
+
logits=np.log(np.clip(p,1e-7,1-1e-7)/np.clip(1-p,1e-7,1-1e-7))
|
| 83 |
+
item[split+'_base_logits']=np.pad(logits,((0,0),(0,max_ops-p.shape[1]))).astype(np.float32)
|
| 84 |
+
ds=np.unpackbits(arrays['detectors'][indices],axis=1,count=row['num_detectors'],bitorder='little')
|
| 85 |
+
item[split+'_dets']=np.pad(ds,((0,0),(0,601-ds.shape[1])))
|
| 86 |
+
item[split+'_labels']=arrays['labels'][indices]
|
| 87 |
+
item[split+'_sample_ids']=arrays['sample_ids'][indices]
|
| 88 |
+
item[split+'_physical_probabilities']=physical_prediction.astype(np.float32)
|
| 89 |
+
items.append(item)
|
| 90 |
+
return items
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
if __name__=='__main__':
|
| 94 |
+
items=load_all(splits=())
|
| 95 |
+
print(json.dumps({'conditions':len(items),'maximum_operations':max(int(x['operation_count']) for x in items)}))
|
tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S040/training_sources/confidence_joint1/learned_d5__joint_mixture.py
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Two trainable exact-decoder experts with a syndrome-only mixture gate."""
|
| 2 |
+
import jax
|
| 3 |
+
import jax.numpy as jnp
|
| 4 |
+
|
| 5 |
+
GATE_FEATURES = 41
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def gate_features(dets, grid, static):
|
| 9 |
+
"""Shot-local features; no labels, IDs, expert probabilities, or batch statistics."""
|
| 10 |
+
presence = grid != 600
|
| 11 |
+
event = dets[:, grid].astype(jnp.float32) * presence[None]
|
| 12 |
+
count = jnp.maximum(presence.sum(axis=0), 1)
|
| 13 |
+
density = event.sum(axis=1) / count[None]
|
| 14 |
+
blocks = [density * 4]
|
| 15 |
+
for lag in [1, 2, 4, 8]:
|
| 16 |
+
valid = presence[:-lag] & presence[lag:]
|
| 17 |
+
denom = jnp.maximum(valid.sum(axis=0), 1)
|
| 18 |
+
site_valid = valid.any(axis=0)
|
| 19 |
+
a = event[:, :-lag] * valid[None]
|
| 20 |
+
b = event[:, lag:] * valid[None]
|
| 21 |
+
coincidence = (a * b).sum(axis=1) / denom[None]
|
| 22 |
+
covariance = coincidence - a.sum(axis=1) * b.sum(axis=1) / denom[None] ** 2
|
| 23 |
+
divisor = jnp.maximum(site_valid.sum(), 1)
|
| 24 |
+
blocks.extend([(coincidence * site_valid).sum(axis=1, keepdims=True) * 8 / divisor,
|
| 25 |
+
(covariance * site_valid).sum(axis=1, keepdims=True) * 16 / divisor])
|
| 26 |
+
valid_frame = presence.any(axis=1)
|
| 27 |
+
nframes = jnp.maximum(valid_frame.sum(), 1)
|
| 28 |
+
frame = event.sum(axis=2) / jnp.maximum(presence.sum(axis=1), 1)[None]
|
| 29 |
+
frame_mean = frame.sum(axis=1) / nframes
|
| 30 |
+
frame_var = (((frame - frame_mean[:, None]) ** 2) * valid_frame[None]).sum(axis=1) / nframes
|
| 31 |
+
rank = jnp.cumsum(valid_frame) - 1
|
| 32 |
+
first_mask = valid_frame & (rank < jnp.maximum(nframes // 2, 1))
|
| 33 |
+
last_mask = valid_frame & ~first_mask
|
| 34 |
+
first = (frame * first_mask[None]).sum(axis=1) / jnp.maximum(first_mask.sum(), 1)
|
| 35 |
+
last = (frame * last_mask[None]).sum(axis=1) / jnp.maximum(last_mask.sum(), 1)
|
| 36 |
+
last = jnp.where(last_mask.any(), last, first)
|
| 37 |
+
fraction = jnp.max(static[:, 124])
|
| 38 |
+
basis = jnp.max(static[:, 127])
|
| 39 |
+
blocks.append(4 * jnp.stack([density.mean(axis=1), density.std(axis=1), density.max(axis=1),
|
| 40 |
+
jnp.sqrt(jnp.maximum(frame_var, 0)), frame.max(axis=1),
|
| 41 |
+
jnp.abs(first - last)], axis=1))
|
| 42 |
+
blocks.append(jnp.broadcast_to(jnp.stack([fraction, fraction ** 2, basis]), (len(dets), 3)))
|
| 43 |
+
result = jnp.concatenate(blocks, axis=1)
|
| 44 |
+
assert result.shape == (len(dets), GATE_FEATURES)
|
| 45 |
+
return result
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def initialize_gate(seed, hidden=32):
|
| 49 |
+
key = jax.random.key(seed)
|
| 50 |
+
return {'w1': jax.random.normal(key, (GATE_FEATURES, hidden)) * jnp.sqrt(2 / GATE_FEATURES),
|
| 51 |
+
'b1': jnp.zeros(hidden), 'w2': jnp.zeros((hidden, 1)), 'b2': jnp.zeros(1)}
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def gate_logit(parameters, features):
|
| 55 |
+
hidden = jax.nn.silu(features @ parameters['w1'] + parameters['b1'])
|
| 56 |
+
return (hidden @ parameters['w2'] + parameters['b2'])[:, 0]
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def mixture_terms(losses, logit):
|
| 60 |
+
"""Stable BCE and exact expert/gate adjoints from per-expert BCE losses.
|
| 61 |
+
|
| 62 |
+
losses has shape [batch,2]. Responsibilities multiply each expert BCE
|
| 63 |
+
gradient; gate_adjoint is d(BCE mixture)/d(single free gate logit).
|
| 64 |
+
"""
|
| 65 |
+
logits = jnp.stack([logit, jnp.zeros_like(logit)], axis=1)
|
| 66 |
+
log_a = jax.nn.log_softmax(logits, axis=1)
|
| 67 |
+
log_c = jax.scipy.special.logsumexp(log_a - losses, axis=1)
|
| 68 |
+
responsibility = jnp.exp(log_a - losses - log_c[:, None])
|
| 69 |
+
a = jnp.exp(log_a)
|
| 70 |
+
return -log_c, responsibility, a[:, 0] - responsibility[:, 0], a
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def mix_predictions(predictions, logit):
|
| 74 |
+
a = jax.nn.sigmoid(logit)
|
| 75 |
+
return a * predictions[:, 0] + (1 - a) * predictions[:, 1]
|
tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S040/training_sources/confidence_joint1/learned_d5__model.py
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Small shared network corrects soft-conditioned relevant-CSS edge logits."""
|
| 2 |
+
import jax
|
| 3 |
+
import jax.numpy as jnp
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
def initialize(seed,hidden=64,input_features=394):
|
| 7 |
+
assert input_features in (394,414)
|
| 8 |
+
keys=jax.random.split(jax.random.key(seed),3)
|
| 9 |
+
return {'w1':jax.random.normal(keys[0],(input_features,hidden))*jnp.sqrt(2/input_features),'b1':jnp.zeros(hidden),
|
| 10 |
+
'w2':jax.random.normal(keys[1],(hidden,hidden))*jnp.sqrt(2/hidden),'b2':jnp.zeros(hidden),
|
| 11 |
+
'w3':jax.random.normal(keys[2],(hidden,1))*.001,'b3':jnp.zeros(1)}
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def endpoint_features(events,measurements,density,static):
|
| 15 |
+
"""Twenty endpoint/history summaries computed solely from the input syndrome."""
|
| 16 |
+
support=static[:,:120].reshape(-1,5,24)
|
| 17 |
+
selected=jnp.max(support,axis=1)
|
| 18 |
+
endpoint_counts=jnp.maximum(support.sum(axis=-1),1)
|
| 19 |
+
spatial_count=jnp.maximum(selected.sum(axis=-1),1)
|
| 20 |
+
event_frames=events.reshape(len(events),-1,5,24)
|
| 21 |
+
measurement_frames=measurements.reshape(len(events),-1,5,24)
|
| 22 |
+
endpoint_events=(event_frames*support[None,:,:,:]).sum(axis=-1)
|
| 23 |
+
endpoint_measurements=(measurement_frames*support[None,:,:,:]).sum(axis=-1)
|
| 24 |
+
spatial_events=(event_frames*selected[None,:,None,:]).sum(axis=-1)/spatial_count[None,:,None]
|
| 25 |
+
endpoint_total=endpoint_events.sum(axis=-1)
|
| 26 |
+
endpoint_fraction=endpoint_total/jnp.maximum(support.sum(axis=(1,2)),1)[None,:]
|
| 27 |
+
endpoint_parity=jnp.mod(endpoint_total,2)
|
| 28 |
+
selected_density=(density[:,None,:]*selected[None,:,:]).sum(axis=-1)/spatial_count[None,:]
|
| 29 |
+
adjacent=(event_frames[:,:,:-1,:]*event_frames[:,:,1:,:]*selected[None,:,None,:]).sum(axis=(2,3))/(4*spatial_count[None,:])
|
| 30 |
+
measurement_mean=(measurement_frames*selected[None,:,None,:]).sum(axis=(2,3))/(5*spatial_count[None,:])
|
| 31 |
+
return jnp.concatenate([
|
| 32 |
+
endpoint_events/endpoint_counts[None,:,:],
|
| 33 |
+
endpoint_measurements/endpoint_counts[None,:,:],spatial_events,
|
| 34 |
+
selected_density[:,:,None],endpoint_fraction[:,:,None],endpoint_parity[:,:,None],
|
| 35 |
+
adjacent[:,:,None],measurement_mean[:,:,None]],axis=-1)
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def probabilities(parameters,dets,base_logits,context,static,valid,grid,measurement_indices,counts):
|
| 39 |
+
event_grid=dets[:,grid]
|
| 40 |
+
measured=(jnp.cumsum(event_grid.astype(jnp.int32),axis=1)&1).reshape(len(dets),624)
|
| 41 |
+
measured=jnp.pad(measured,((0,0),(0,1)))
|
| 42 |
+
events=dets[:,context].astype(jnp.float32)
|
| 43 |
+
measurements=measured[:,measurement_indices[context]].astype(jnp.float32)
|
| 44 |
+
density=jnp.sum(event_grid,axis=1)/counts[None,:]
|
| 45 |
+
features=jnp.concatenate([events,measurements,
|
| 46 |
+
jnp.broadcast_to(density[:,None,:],(len(dets),len(context),24)),
|
| 47 |
+
jnp.broadcast_to(static[None,:,:],(len(dets),*static.shape)),base_logits[:,:,None]/8],axis=-1)
|
| 48 |
+
if parameters['w1'].shape[0]==414:
|
| 49 |
+
features=jnp.concatenate([features,endpoint_features(events,measurements,density,static)],axis=-1)
|
| 50 |
+
else:
|
| 51 |
+
assert parameters['w1'].shape[0]==394
|
| 52 |
+
h=jax.nn.silu(features@parameters['w1']+parameters['b1'])
|
| 53 |
+
h=jax.nn.silu(h@parameters['w2']+parameters['b2'])
|
| 54 |
+
delta=2*jnp.tanh((h@parameters['w3']+parameters['b3'])[...,0])
|
| 55 |
+
return (jax.nn.sigmoid(base_logits+delta)*valid[None,:]).T
|
tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S040/training_sources/confidence_joint1/learned_exact__checkpoint_gradient.py
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Exact logical BCE gradient with block recomputation of frontier histories."""
|
| 2 |
+
import jax
|
| 3 |
+
import jax.numpy as jnp
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
def make_loss_and_grad(width, block_size=32):
|
| 7 |
+
indices = jnp.arange(1 << width, dtype=jnp.int32)
|
| 8 |
+
|
| 9 |
+
@jax.jit
|
| 10 |
+
def evaluate(dets, labels, probabilities, masks, measured):
|
| 11 |
+
nops, batch = probabilities.shape
|
| 12 |
+
padding = (-nops) % block_size
|
| 13 |
+
p = jnp.pad(probabilities, ((0, padding), (0, 0)))
|
| 14 |
+
m = jnp.pad(masks, (0, padding))
|
| 15 |
+
d = jnp.pad(measured, (0, padding), constant_values=-1)
|
| 16 |
+
blocks = (p.reshape(-1, block_size, batch), m.reshape(-1, block_size),
|
| 17 |
+
d.reshape(-1, block_size))
|
| 18 |
+
|
| 19 |
+
def forward(f, args):
|
| 20 |
+
probability, mask, detector = args
|
| 21 |
+
|
| 22 |
+
def error(f):
|
| 23 |
+
out = (1 - probability[:, None]) * f + probability[:, None] * f[:, indices ^ mask]
|
| 24 |
+
return out, jnp.ones(batch)
|
| 25 |
+
|
| 26 |
+
def project(f):
|
| 27 |
+
dst = (indices[None, :] & ~mask) | (dets[:, detector, None].astype(jnp.int32) * mask)
|
| 28 |
+
g = jnp.take_along_axis(f, dst, axis=1) * ((indices & mask) == 0)
|
| 29 |
+
norm = jnp.maximum(g.sum(axis=1), 1e-30)
|
| 30 |
+
return g / norm[:, None], norm
|
| 31 |
+
|
| 32 |
+
out, norm = jax.lax.cond(detector < 0, error, project, f)
|
| 33 |
+
return out, (f, norm)
|
| 34 |
+
|
| 35 |
+
def forward_block(f, args):
|
| 36 |
+
def step(carry, item):
|
| 37 |
+
result, _ = forward(carry, item)
|
| 38 |
+
return result, None
|
| 39 |
+
out, _ = jax.lax.scan(step, f, args)
|
| 40 |
+
return out, f
|
| 41 |
+
|
| 42 |
+
initial = jnp.zeros((batch, 1 << width), jnp.float32).at[:, 0].set(1)
|
| 43 |
+
f, checkpoints = jax.lax.scan(forward_block, initial, blocks)
|
| 44 |
+
indicator = ((indices[None, :] & 1) == labels[:, None])
|
| 45 |
+
correct = jnp.maximum(jnp.sum(f * indicator, axis=1), 1e-10)
|
| 46 |
+
prediction = jnp.sum(f[:, 1::2], axis=1)
|
| 47 |
+
terminal = 1 - indicator / correct[:, None]
|
| 48 |
+
|
| 49 |
+
def backward(b, args):
|
| 50 |
+
probability, mask, detector, old, norm = args
|
| 51 |
+
|
| 52 |
+
def error(b):
|
| 53 |
+
flipped = b[:, indices ^ mask]
|
| 54 |
+
grad = jnp.sum(old * (flipped - b), axis=1)
|
| 55 |
+
return (1 - probability[:, None]) * b + probability[:, None] * flipped, grad
|
| 56 |
+
|
| 57 |
+
def project(b):
|
| 58 |
+
obs = ((indices[None, :] & mask) == dets[:, detector, None].astype(jnp.int32) * mask)
|
| 59 |
+
values = b[:, indices & ~mask]
|
| 60 |
+
mean = jnp.sum(old * obs * values, axis=1) / norm
|
| 61 |
+
return (values - mean[:, None]) * obs / norm[:, None], jnp.zeros(batch)
|
| 62 |
+
|
| 63 |
+
return jax.lax.cond(detector < 0, error, project, b)
|
| 64 |
+
|
| 65 |
+
def backward_block(b, args):
|
| 66 |
+
probabilities, masks, measured, checkpoint = args
|
| 67 |
+
_, (history, norms) = jax.lax.scan(forward, checkpoint, (probabilities, masks, measured))
|
| 68 |
+
return jax.lax.scan(backward, b, (probabilities, masks, measured, history, norms), reverse=True)
|
| 69 |
+
|
| 70 |
+
_, gradients = jax.lax.scan(backward_block, terminal, (*blocks, checkpoints), reverse=True)
|
| 71 |
+
return -jnp.log(correct), prediction, gradients.reshape(-1, batch)[:nops]
|
| 72 |
+
|
| 73 |
+
return evaluate
|
tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S040/training_sources/fresh2_full/exact_d3__exact.py
ADDED
|
@@ -0,0 +1,213 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Exact detector-error-model contraction by bounded-frontier elimination."""
|
| 2 |
+
import collections
|
| 3 |
+
import numpy as np
|
| 4 |
+
import stim
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def parse_errors(dem):
|
| 8 |
+
errors = []
|
| 9 |
+
for ins in dem.flattened():
|
| 10 |
+
if ins.type != 'error':
|
| 11 |
+
continue
|
| 12 |
+
ds, logical = set(), 0
|
| 13 |
+
for t in ins.targets_copy():
|
| 14 |
+
if t.is_relative_detector_id():
|
| 15 |
+
ds.symmetric_difference_update([t.val])
|
| 16 |
+
elif t.is_logical_observable_id():
|
| 17 |
+
assert t.val == 0
|
| 18 |
+
logical ^= 1
|
| 19 |
+
errors.append((ds, logical, ins.args_copy()[0]))
|
| 20 |
+
return errors
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def elimination_order(dem, errors):
|
| 24 |
+
blocks = collections.defaultdict(list)
|
| 25 |
+
for d, c in dem.get_detector_coordinates().items():
|
| 26 |
+
blocks[c[-1]].append(d)
|
| 27 |
+
pending = [ds for ds, _, _ in errors if ds]
|
| 28 |
+
active, used, order = set(), set(), []
|
| 29 |
+
for _, block in sorted(blocks.items()):
|
| 30 |
+
remain = set(block)
|
| 31 |
+
while remain:
|
| 32 |
+
def score(d):
|
| 33 |
+
new = set().union(*(e for e in pending if d in e)) - used
|
| 34 |
+
return len(active | new), -sum(d in e for e in pending), d
|
| 35 |
+
d = min(remain, key=score)
|
| 36 |
+
related = [e for e in pending if d in e]
|
| 37 |
+
active |= set().union(*related) - used
|
| 38 |
+
active.discard(d)
|
| 39 |
+
pending = [e for e in pending if d not in e]
|
| 40 |
+
used.add(d)
|
| 41 |
+
remain.remove(d)
|
| 42 |
+
order.append(d)
|
| 43 |
+
assert sorted(order) == list(range(dem.num_detectors))
|
| 44 |
+
return order
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def make_plan(dem):
|
| 48 |
+
errors = parse_errors(dem)
|
| 49 |
+
order = elimination_order(dem, errors)
|
| 50 |
+
rank = {d: i for i, d in enumerate(order)}
|
| 51 |
+
groups = collections.defaultdict(list)
|
| 52 |
+
for source_index, (ds, logical, p) in enumerate(errors):
|
| 53 |
+
first = min(ds, key=rank.get) if ds else order[0]
|
| 54 |
+
groups[first].append((ds, logical, p, source_index))
|
| 55 |
+
slots, probabilities, masks, measured, source_indices = {}, [], [], [], []
|
| 56 |
+
width = 1
|
| 57 |
+
for d in order:
|
| 58 |
+
related = groups[d]
|
| 59 |
+
needed = set().union(*(ds for ds, _, _, _ in related)) | {d}
|
| 60 |
+
for node in sorted(needed):
|
| 61 |
+
if node not in slots:
|
| 62 |
+
free = next(i for i in range(1, 64) if i not in slots.values())
|
| 63 |
+
slots[node] = free
|
| 64 |
+
width = max(width, free+1)
|
| 65 |
+
for ds, logical, p, source_index in related:
|
| 66 |
+
mask = logical
|
| 67 |
+
for node in ds:
|
| 68 |
+
mask ^= 1 << slots[node]
|
| 69 |
+
probabilities.append(p)
|
| 70 |
+
masks.append(mask)
|
| 71 |
+
measured.append(-1)
|
| 72 |
+
source_indices.append(source_index)
|
| 73 |
+
probabilities.append(0)
|
| 74 |
+
masks.append(1 << slots.pop(d))
|
| 75 |
+
measured.append(d)
|
| 76 |
+
source_indices.append(-1)
|
| 77 |
+
assert not slots
|
| 78 |
+
return {'probabilities': np.array(probabilities, np.float32),
|
| 79 |
+
'masks': np.array(masks, np.int32), 'measured': np.array(measured, np.int32),
|
| 80 |
+
'width': np.array(width, np.int32), 'num_detectors': np.array(dem.num_detectors, np.int32),
|
| 81 |
+
'source_indices': np.array(source_indices, np.int32),
|
| 82 |
+
'order': np.array(order, np.int32)}
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def make_decoder(width):
|
| 86 |
+
import jax
|
| 87 |
+
import jax.numpy as jnp
|
| 88 |
+
indices = jnp.arange(1 << width, dtype=jnp.int32)
|
| 89 |
+
@jax.jit
|
| 90 |
+
def decode(dets, probabilities, masks, measured):
|
| 91 |
+
f = jnp.zeros((dets.shape[0], 1 << width), jnp.float32).at[:, 0].set(1)
|
| 92 |
+
def step(f, args):
|
| 93 |
+
p, mask, d = args
|
| 94 |
+
def error(f):
|
| 95 |
+
prob = p[:, None] if p.ndim else p
|
| 96 |
+
return (1-prob)*f + prob*f[:, indices ^ mask]
|
| 97 |
+
def project(f):
|
| 98 |
+
obs = dets[:, d].astype(jnp.int32)
|
| 99 |
+
dst = (indices[None, :] & ~mask) | (obs[:, None]*mask)
|
| 100 |
+
g = jnp.take_along_axis(f, dst, axis=1) * ((indices & mask)==0)
|
| 101 |
+
return g / jnp.maximum(jnp.sum(g, axis=1, keepdims=True), 1e-30)
|
| 102 |
+
return jax.lax.cond(d < 0, error, project, f), None
|
| 103 |
+
f, _ = jax.lax.scan(step, f, (probabilities, masks, measured))
|
| 104 |
+
return jnp.sum(f[:, 1::2], axis=1) / jnp.maximum(jnp.sum(f, axis=1), 1e-30)
|
| 105 |
+
return decode
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def make_marginals(width):
|
| 109 |
+
"""Per-shot derivatives of log syndrome probability give all error marginals."""
|
| 110 |
+
import jax
|
| 111 |
+
import jax.numpy as jnp
|
| 112 |
+
indices = jnp.arange(1 << width, dtype=jnp.int32)
|
| 113 |
+
def log_partition(dets, probabilities, masks, measured):
|
| 114 |
+
f = jnp.zeros(1 << width, jnp.float32).at[0].set(1)
|
| 115 |
+
def step(carry, args):
|
| 116 |
+
f, logz = carry
|
| 117 |
+
p, mask, d = args
|
| 118 |
+
def error(carry):
|
| 119 |
+
f, logz = carry
|
| 120 |
+
return ((1-p)*f + p*f[indices ^ mask], logz)
|
| 121 |
+
def project(carry):
|
| 122 |
+
f, logz = carry
|
| 123 |
+
dst = (indices & ~mask) | (dets[d].astype(jnp.int32)*mask)
|
| 124 |
+
g = f[dst] * ((indices & mask)==0)
|
| 125 |
+
norm = jnp.maximum(jnp.sum(g), 1e-30)
|
| 126 |
+
return g/norm, logz+jnp.log(norm)
|
| 127 |
+
return jax.lax.cond(d<0, error, project, carry), None
|
| 128 |
+
(_, logz), _ = jax.lax.scan(jax.checkpoint(step), (f, jnp.float32(0)), (probabilities, masks, measured))
|
| 129 |
+
return logz
|
| 130 |
+
return jax.jit(jax.vmap(jax.value_and_grad(log_partition, argnums=1), in_axes=(0,None,None,None)))
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
def make_marginals_fb(width, return_observable=False):
|
| 134 |
+
"""Forward/backward contraction without generic gather-gradient scatter."""
|
| 135 |
+
import jax
|
| 136 |
+
import jax.numpy as jnp
|
| 137 |
+
indices = jnp.arange(1 << width, dtype=jnp.int32)
|
| 138 |
+
# The syndrome likelihood marginalizes the unobserved logical bit. Keep
|
| 139 |
+
# that bit in the forward state for its output, but omit it from histories
|
| 140 |
+
# and backward messages, halving the largest buffers.
|
| 141 |
+
backward_width=width-1 if return_observable else width
|
| 142 |
+
backward_indices=jnp.arange(1 << backward_width,dtype=jnp.int32)
|
| 143 |
+
@jax.jit
|
| 144 |
+
def marginals(dets, probabilities, masks, measured):
|
| 145 |
+
f=jnp.zeros((dets.shape[0],1<<width),jnp.float32).at[:,0].set(1)
|
| 146 |
+
def forward(carry,args):
|
| 147 |
+
f,logz=carry
|
| 148 |
+
p,mask,d=args
|
| 149 |
+
def error(carry):
|
| 150 |
+
f,logz=carry
|
| 151 |
+
prob=p[:,None] if p.ndim else p
|
| 152 |
+
return ((1-prob)*f+prob*f[:,indices^mask],logz)
|
| 153 |
+
def project(carry):
|
| 154 |
+
f,logz=carry
|
| 155 |
+
dst=(indices[None,:]&~mask)|(dets[:,d,None].astype(jnp.int32)*mask)
|
| 156 |
+
g=jnp.take_along_axis(f,dst,axis=1)*((indices&mask)==0)
|
| 157 |
+
norm=jnp.maximum(g.sum(axis=1),1e-30)
|
| 158 |
+
return g/norm[:,None],logz+jnp.log(norm)
|
| 159 |
+
out=jax.lax.cond(d<0,error,project,carry)
|
| 160 |
+
return out,(f[:,::2]+f[:,1::2]) if return_observable else f
|
| 161 |
+
(final,logz),history=jax.lax.scan(forward,(f,jnp.zeros(len(dets))),(probabilities,masks,measured))
|
| 162 |
+
def backward(b,args):
|
| 163 |
+
p,mask,d,f=args
|
| 164 |
+
def error(b):
|
| 165 |
+
flipped=b[:,backward_indices^mask]
|
| 166 |
+
prob=p[:,None] if p.ndim else p
|
| 167 |
+
prior=(1-prob)*b+prob*flipped
|
| 168 |
+
norm=jnp.maximum(jnp.sum(f*prior,axis=1),1e-30)
|
| 169 |
+
q=p*jnp.sum(f*flipped,axis=1)/norm
|
| 170 |
+
grad=(q-p)/jnp.maximum(p*(1-p),1e-20)
|
| 171 |
+
return prior/norm[:,None],grad
|
| 172 |
+
def project(b):
|
| 173 |
+
prior=b[:,backward_indices&~mask]*((backward_indices[None,:]&mask)==(dets[:,d,None].astype(jnp.int32)*mask))
|
| 174 |
+
norm=jnp.maximum(jnp.sum(f*prior,axis=1),1e-30)
|
| 175 |
+
return prior/norm[:,None],jnp.zeros(len(dets))
|
| 176 |
+
return jax.lax.cond(d<0,error,project,b)
|
| 177 |
+
backward_masks=masks>>1 if return_observable else masks
|
| 178 |
+
_,grad=jax.lax.scan(backward,jnp.ones((len(dets),1<<backward_width),jnp.float32),
|
| 179 |
+
(probabilities,backward_masks,measured,history),reverse=True)
|
| 180 |
+
if return_observable:
|
| 181 |
+
return logz,grad.T,jnp.sum(final[:,1::2],axis=1)/jnp.maximum(jnp.sum(final,axis=1),1e-30)
|
| 182 |
+
return logz,grad.T
|
| 183 |
+
return marginals
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
def predict(plan, packed, decoder=None, batch=256):
|
| 187 |
+
import jax
|
| 188 |
+
decoder = decoder or make_decoder(int(plan['width']))
|
| 189 |
+
dets = np.unpackbits(packed, bitorder='little', axis=1, count=int(plan['num_detectors']))
|
| 190 |
+
args = [jax.device_put(plan[k]) for k in ['probabilities', 'masks', 'measured']]
|
| 191 |
+
result = []
|
| 192 |
+
for start in range(0, len(dets), batch):
|
| 193 |
+
ds = dets[start:start+batch]
|
| 194 |
+
ds = np.pad(ds, ((0, batch-len(ds)), (0, 0)))
|
| 195 |
+
result.append(np.asarray(decoder(ds, *args))[:min(batch, len(dets)-start)])
|
| 196 |
+
return np.concatenate(result)
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
if __name__ == '__main__':
|
| 200 |
+
import sys, time
|
| 201 |
+
from pathlib import Path
|
| 202 |
+
import jax
|
| 203 |
+
print(jax.devices(), flush=True)
|
| 204 |
+
path = Path(sys.argv[1])
|
| 205 |
+
dem = stim.DetectorErrorModel.from_file(path/'pij_from_even_for_odd.dem')
|
| 206 |
+
plan = make_plan(dem)
|
| 207 |
+
print({k: v.shape if v.ndim else int(v) for k, v in plan.items()}, flush=True)
|
| 208 |
+
a = np.load(path/'arrays.npz')
|
| 209 |
+
decoder = make_decoder(int(plan['width']))
|
| 210 |
+
for i in range(2):
|
| 211 |
+
t = time.time()
|
| 212 |
+
p = predict(plan, a['detectors'][:1024], decoder)
|
| 213 |
+
print({'seconds': time.time()-t, 'failure': np.mean((p>=.5)!=a['labels'][:len(p)]), 'min': p.min(), 'max': p.max()}, flush=True)
|
tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S040/training_sources/fresh2_full/learned_d5__data.py
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Static physical features and authorized cached training/validation priors."""
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
import json,sys
|
| 4 |
+
import numpy as np
|
| 5 |
+
import stim
|
| 6 |
+
sys.path.insert(0,'/workspace/research/exact_d3')
|
| 7 |
+
from exact import parse_errors
|
| 8 |
+
from conditional import load_state
|
| 9 |
+
|
| 10 |
+
ROOT=Path(__file__).resolve().parent
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def build_features(row,package,max_ops=2048):
|
| 14 |
+
dem=stim.DetectorErrorModel.from_file(Path('/workspace/data/train')/row['noise'])
|
| 15 |
+
errors=parse_errors(dem);coords=dem.get_detector_coordinates()
|
| 16 |
+
if row['rounds']==1:
|
| 17 |
+
plan=dict(np.load(package/f"plans/{row['name']}.npz"));supports=[(ds,l) for ds,l,p in errors]
|
| 18 |
+
measured=plan['measured']
|
| 19 |
+
else:
|
| 20 |
+
state=load_state(package/f"conditional_plans/{row['name']}.npz");plan=state['on']
|
| 21 |
+
on=set(state['on_indices'].tolist());groups={}
|
| 22 |
+
for ds,l,p in errors:
|
| 23 |
+
key=tuple(sorted(ds&on)),l
|
| 24 |
+
if key[0] or key[1]:groups.setdefault(key,len(groups))
|
| 25 |
+
supports=list(groups)
|
| 26 |
+
measured=np.where(plan['measured']>=0,state['on_indices'][np.maximum(plan['measured'],0)],-1)
|
| 27 |
+
assert int(plan['width'])<=14
|
| 28 |
+
circuit=stim.Circuit.from_file(Path('/workspace/data/train')/row['circuit'])
|
| 29 |
+
qubits=circuit.get_final_qubit_coordinates()
|
| 30 |
+
first=next(ins for ins in circuit.flattened() if ins.name in ['M','MX','MR','MRX'])
|
| 31 |
+
spaces=sorted(tuple(qubits[t.value][:2]) for t in first.targets_copy());assert len(spaces)==24
|
| 32 |
+
idx={(int(c[2]),tuple(c[:2])):d for d,c in coords.items()}
|
| 33 |
+
context=np.full((max_ops,120),600,np.int32);static=np.zeros((max_ops,129),np.float32)
|
| 34 |
+
n=len(plan['masks']);assert n<=max_ops
|
| 35 |
+
for op,source in enumerate(plan['source_indices']):
|
| 36 |
+
if source<0:continue
|
| 37 |
+
ds,logical=supports[source];t=min(int(coords[d][2]) for d in ds) if ds else 0
|
| 38 |
+
for dt in range(-2,3):
|
| 39 |
+
for s,space in enumerate(spaces):context[op,(dt+2)*24+s]=idx.get((t+dt,space),600)
|
| 40 |
+
for d in ds:
|
| 41 |
+
c=coords[d];static[op,(int(c[2])-t+2)*24+spaces.index(tuple(c[:2]))]=1
|
| 42 |
+
p=float(plan['probabilities'][op]);static[op,120]=np.log(max(p,1e-7)/max(1-p,1e-7))/8
|
| 43 |
+
static[op,121:]=[logical,len(ds)/4,t/25,row['rounds']/25,t==0,t>=row['rounds']-1,row['basis']=='X',1]
|
| 44 |
+
grid=np.full((26,24),600,np.int32);measurement_indices=np.full(601,624,np.int32)
|
| 45 |
+
for d,c in coords.items():
|
| 46 |
+
t=int(c[2]);s=spaces.index(tuple(c[:2]));grid[t,s]=d;measurement_indices[d]=t*24+s
|
| 47 |
+
return {'context':context,'static':static,'masks':np.pad(plan['masks'],(0,max_ops-n)),
|
| 48 |
+
'measured':np.pad(measured,(0,max_ops-n),constant_values=-1),
|
| 49 |
+
'valid':np.pad((plan['source_indices']>=0).astype(np.float32),(0,max_ops-n)),
|
| 50 |
+
'grid':grid,'measurement_indices':measurement_indices,
|
| 51 |
+
'counts':np.maximum((grid!=600).sum(axis=0),1).astype(np.float32),'operation_count':np.array(n,np.int32)}
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def load_all(splits=('train','validation'),max_ops=2048,prior_pass=1,training_cache=None):
|
| 55 |
+
assert prior_pass in [1,3,5]
|
| 56 |
+
assert training_cache is None or prior_pass in [1,3]
|
| 57 |
+
rows=[r for r in json.loads(Path('/workspace/data/train/manifest.json').read_text())['conditions'] if r['distance']==5]
|
| 58 |
+
package=Path(json.loads(Path('/workspace/research/CURRENT.json').read_text())['package'])
|
| 59 |
+
plans=ROOT/'feature_plans';plans.mkdir(exist_ok=True);items=[]
|
| 60 |
+
for row in rows:
|
| 61 |
+
path=plans/f"{row['name']}.npz"
|
| 62 |
+
if not path.exists():np.savez(path,**build_features(row,package,max_ops))
|
| 63 |
+
item=dict(np.load(path,allow_pickle=False));item['row']=row
|
| 64 |
+
if splits:
|
| 65 |
+
cache=np.load(Path('/workspace/research/exact_d3/turbo_cache')/f"{row['name']}.npz")
|
| 66 |
+
feedback=np.load(Path('/workspace/research/exact_d3/feedback5_cache')/f"{row['name']}.npz") if prior_pass>1 else None
|
| 67 |
+
for split in splits:
|
| 68 |
+
assert split in ['train','validation']
|
| 69 |
+
arrays=np.load(Path('/workspace/data')/split/row['arrays'])
|
| 70 |
+
if split=='train' and training_cache is not None:
|
| 71 |
+
full=np.load(Path(training_cache)/f"{row['name']}.npz",allow_pickle=False)
|
| 72 |
+
indices=full['indices'];p=full[f'priors{prior_pass}']
|
| 73 |
+
assert np.array_equal(arrays['sample_ids'][indices],full['sample_ids'])
|
| 74 |
+
physical_prediction=full['probabilities3']
|
| 75 |
+
else:
|
| 76 |
+
indices=cache['train4096_indices'] if split=='train' else np.arange(len(arrays['labels']))
|
| 77 |
+
key='train4096' if split=='train' else 'validation'
|
| 78 |
+
p=cache[key+'_on_prior'] if prior_pass==1 else feedback[f'{key}_priors{prior_pass}']
|
| 79 |
+
physical_prediction=cache[key][:,0] if prior_pass==1 else feedback[key][:,prior_pass-1]
|
| 80 |
+
assert p.shape[1]==int(item['operation_count'])
|
| 81 |
+
if feedback is not None:assert np.array_equal(feedback['train4096_indices'],cache['train4096_indices'])
|
| 82 |
+
logits=np.log(np.clip(p,1e-7,1-1e-7)/np.clip(1-p,1e-7,1-1e-7))
|
| 83 |
+
item[split+'_base_logits']=np.pad(logits,((0,0),(0,max_ops-p.shape[1]))).astype(np.float32)
|
| 84 |
+
ds=np.unpackbits(arrays['detectors'][indices],axis=1,count=row['num_detectors'],bitorder='little')
|
| 85 |
+
item[split+'_dets']=np.pad(ds,((0,0),(0,601-ds.shape[1])))
|
| 86 |
+
item[split+'_labels']=arrays['labels'][indices]
|
| 87 |
+
item[split+'_sample_ids']=arrays['sample_ids'][indices]
|
| 88 |
+
item[split+'_physical_probabilities']=physical_prediction.astype(np.float32)
|
| 89 |
+
items.append(item)
|
| 90 |
+
return items
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
if __name__=='__main__':
|
| 94 |
+
items=load_all(splits=())
|
| 95 |
+
print(json.dumps({'conditions':len(items),'maximum_operations':max(int(x['operation_count']) for x in items)}))
|
tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S040/training_sources/fresh2_full/learned_d5__model.py
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Small shared network corrects soft-conditioned relevant-CSS edge logits."""
|
| 2 |
+
import jax
|
| 3 |
+
import jax.numpy as jnp
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
def initialize(seed,hidden=64,input_features=394):
|
| 7 |
+
assert input_features in (394,414)
|
| 8 |
+
keys=jax.random.split(jax.random.key(seed),3)
|
| 9 |
+
return {'w1':jax.random.normal(keys[0],(input_features,hidden))*jnp.sqrt(2/input_features),'b1':jnp.zeros(hidden),
|
| 10 |
+
'w2':jax.random.normal(keys[1],(hidden,hidden))*jnp.sqrt(2/hidden),'b2':jnp.zeros(hidden),
|
| 11 |
+
'w3':jax.random.normal(keys[2],(hidden,1))*.001,'b3':jnp.zeros(1)}
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def endpoint_features(events,measurements,density,static):
|
| 15 |
+
"""Twenty endpoint/history summaries computed solely from the input syndrome."""
|
| 16 |
+
support=static[:,:120].reshape(-1,5,24)
|
| 17 |
+
selected=jnp.max(support,axis=1)
|
| 18 |
+
endpoint_counts=jnp.maximum(support.sum(axis=-1),1)
|
| 19 |
+
spatial_count=jnp.maximum(selected.sum(axis=-1),1)
|
| 20 |
+
event_frames=events.reshape(len(events),-1,5,24)
|
| 21 |
+
measurement_frames=measurements.reshape(len(events),-1,5,24)
|
| 22 |
+
endpoint_events=(event_frames*support[None,:,:,:]).sum(axis=-1)
|
| 23 |
+
endpoint_measurements=(measurement_frames*support[None,:,:,:]).sum(axis=-1)
|
| 24 |
+
spatial_events=(event_frames*selected[None,:,None,:]).sum(axis=-1)/spatial_count[None,:,None]
|
| 25 |
+
endpoint_total=endpoint_events.sum(axis=-1)
|
| 26 |
+
endpoint_fraction=endpoint_total/jnp.maximum(support.sum(axis=(1,2)),1)[None,:]
|
| 27 |
+
endpoint_parity=jnp.mod(endpoint_total,2)
|
| 28 |
+
selected_density=(density[:,None,:]*selected[None,:,:]).sum(axis=-1)/spatial_count[None,:]
|
| 29 |
+
adjacent=(event_frames[:,:,:-1,:]*event_frames[:,:,1:,:]*selected[None,:,None,:]).sum(axis=(2,3))/(4*spatial_count[None,:])
|
| 30 |
+
measurement_mean=(measurement_frames*selected[None,:,None,:]).sum(axis=(2,3))/(5*spatial_count[None,:])
|
| 31 |
+
return jnp.concatenate([
|
| 32 |
+
endpoint_events/endpoint_counts[None,:,:],
|
| 33 |
+
endpoint_measurements/endpoint_counts[None,:,:],spatial_events,
|
| 34 |
+
selected_density[:,:,None],endpoint_fraction[:,:,None],endpoint_parity[:,:,None],
|
| 35 |
+
adjacent[:,:,None],measurement_mean[:,:,None]],axis=-1)
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def probabilities(parameters,dets,base_logits,context,static,valid,grid,measurement_indices,counts):
|
| 39 |
+
event_grid=dets[:,grid]
|
| 40 |
+
measured=(jnp.cumsum(event_grid.astype(jnp.int32),axis=1)&1).reshape(len(dets),624)
|
| 41 |
+
measured=jnp.pad(measured,((0,0),(0,1)))
|
| 42 |
+
events=dets[:,context].astype(jnp.float32)
|
| 43 |
+
measurements=measured[:,measurement_indices[context]].astype(jnp.float32)
|
| 44 |
+
density=jnp.sum(event_grid,axis=1)/counts[None,:]
|
| 45 |
+
features=jnp.concatenate([events,measurements,
|
| 46 |
+
jnp.broadcast_to(density[:,None,:],(len(dets),len(context),24)),
|
| 47 |
+
jnp.broadcast_to(static[None,:,:],(len(dets),*static.shape)),base_logits[:,:,None]/8],axis=-1)
|
| 48 |
+
if parameters['w1'].shape[0]==414:
|
| 49 |
+
features=jnp.concatenate([features,endpoint_features(events,measurements,density,static)],axis=-1)
|
| 50 |
+
else:
|
| 51 |
+
assert parameters['w1'].shape[0]==394
|
| 52 |
+
h=jax.nn.silu(features@parameters['w1']+parameters['b1'])
|
| 53 |
+
h=jax.nn.silu(h@parameters['w2']+parameters['b2'])
|
| 54 |
+
delta=2*jnp.tanh((h@parameters['w3']+parameters['b3'])[...,0])
|
| 55 |
+
return (jax.nn.sigmoid(base_logits+delta)*valid[None,:]).T
|
tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S040/training_sources/fresh2_full/learned_d5__train.py
ADDED
|
@@ -0,0 +1,176 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Train effective d5 CSS weights from random initialization on hardware labels."""
|
| 2 |
+
import os
|
| 3 |
+
os.environ['OPENBLAS_NUM_THREADS']='1'
|
| 4 |
+
os.environ['OMP_NUM_THREADS']='1'
|
| 5 |
+
os.environ['XLA_PYTHON_CLIENT_PREALLOCATE']='false'
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
import argparse,json,time,sys,hashlib,shutil
|
| 8 |
+
import numpy as np
|
| 9 |
+
import jax,jax.numpy as jnp,optax
|
| 10 |
+
from model import initialize,probabilities
|
| 11 |
+
from data import load_all
|
| 12 |
+
sys.path.insert(0,'/workspace/research/learned_exact')
|
| 13 |
+
from gradient import make_loss_and_grad
|
| 14 |
+
from exact import make_decoder
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def main():
|
| 18 |
+
parser=argparse.ArgumentParser();parser.add_argument('--steps',type=int,default=1024)
|
| 19 |
+
parser.add_argument('--batch',type=int,default=256);parser.add_argument('--output',type=Path,required=True)
|
| 20 |
+
parser.add_argument('--validation-shots',type=int,default=512);parser.add_argument('--validation-batch',type=int,default=512)
|
| 21 |
+
parser.add_argument('--init-weights',type=Path);parser.add_argument('--learning-rate',type=float,default=.001)
|
| 22 |
+
parser.add_argument('--eval-every',type=int,default=256);parser.add_argument('--seed',type=int,default=20261101)
|
| 23 |
+
parser.add_argument('--initial-seed',type=int,default=20261101)
|
| 24 |
+
parser.add_argument('--prior-pass',type=int,choices=[1,3,5],default=1)
|
| 25 |
+
parser.add_argument('--training-cache',type=Path)
|
| 26 |
+
parser.add_argument('--gradient-block-size',type=int,default=0)
|
| 27 |
+
parser.add_argument('--bucket-operations',action='store_true')
|
| 28 |
+
parser.add_argument('--accumulate-conditions',type=int,default=1)
|
| 29 |
+
parser.add_argument('--uncertainty-weight-floor',type=float,default=1.)
|
| 30 |
+
parser.add_argument('--hidden-width',type=int,default=64)
|
| 31 |
+
parser.add_argument('--endpoint-features',action='store_true')
|
| 32 |
+
parser.add_argument('--reset-optimizer',action='store_true')
|
| 33 |
+
parser.add_argument('--reset-rng',action='store_true')
|
| 34 |
+
args=parser.parse_args();args.output.mkdir(parents=True,exist_ok=True)
|
| 35 |
+
assert args.accumulate_conditions>=1 and 0<args.uncertainty_weight_floor<=1
|
| 36 |
+
assert args.uncertainty_weight_floor==1 or args.prior_pass==3
|
| 37 |
+
config={k:str(v) if isinstance(v,Path) else v for k,v in vars(args).items()}
|
| 38 |
+
root=Path(__file__).resolve().parent;research=root.parent
|
| 39 |
+
sources=[root/'train.py',root/'data.py',root/'model.py',research/'learned_exact/gradient.py',
|
| 40 |
+
research/'learned_exact/checkpoint_gradient.py',research/'exact_d3/exact.py']
|
| 41 |
+
snapshot=args.output/'training_source';snapshot.mkdir(exist_ok=True)
|
| 42 |
+
source_hashes={}
|
| 43 |
+
for source in sources:
|
| 44 |
+
name=str(source.relative_to(research)).replace('/','__');shutil.copyfile(source,snapshot/name)
|
| 45 |
+
source_hashes[name]=hashlib.sha256(source.read_bytes()).hexdigest()
|
| 46 |
+
feature_mode='local events, reconstructed measurements, shot densities, physical edge support and conditioned prior'
|
| 47 |
+
if args.endpoint_features:feature_mode+=';20 explicit endpoint and local temporal summaries'
|
| 48 |
+
input_features=414 if args.endpoint_features else 394
|
| 49 |
+
config.update({'initialization_seed':args.initial_seed,'feature_mode':feature_mode,'input_features':input_features,
|
| 50 |
+
'training_source_sha256':source_hashes,'runtime_versions':{'jax':jax.__version__,'numpy':np.__version__,'optax':optax.__version__},
|
| 51 |
+
'hidden_width':args.hidden_width,'logit_correction_bound':2,'train_manifest_sha256':hashlib.sha256(Path('/workspace/data/train/manifest.json').read_bytes()).hexdigest(),
|
| 52 |
+
'validation_manifest_sha256':hashlib.sha256(Path('/workspace/data/validation/manifest.json').read_bytes()).hexdigest()})
|
| 53 |
+
(args.output/'run_config.json').write_text(json.dumps(config,indent=2)+'\n')
|
| 54 |
+
started=time.time();dataset=load_all(prior_pass=args.prior_pass,training_cache=args.training_cache);print(json.dumps({'loaded_conditions':len(dataset),'seconds':time.time()-started}),flush=True)
|
| 55 |
+
seen=[np.zeros(len(item['train_labels']),dtype=bool) for item in dataset]
|
| 56 |
+
os.environ['XLA_PYTHON_CLIENT_PREALLOCATE']='true'
|
| 57 |
+
os.environ['XLA_PYTHON_CLIENT_MEM_FRACTION']='0.90'
|
| 58 |
+
parameters=initialize(args.initial_seed,hidden=args.hidden_width,input_features=input_features)
|
| 59 |
+
if args.init_weights:parameters={k:jnp.asarray(v) for k,v in dict(np.load(args.init_weights,allow_pickle=False)).items()}
|
| 60 |
+
actual_hidden=int(parameters['w2'].shape[0])
|
| 61 |
+
assert actual_hidden==args.hidden_width, 'Explicit hidden-width must match the starting checkpoint'
|
| 62 |
+
assert parameters['w1'].shape[0]==input_features, 'Explicit endpoint-feature mode must match the starting checkpoint'
|
| 63 |
+
optimizer=optax.chain(optax.clip_by_global_norm(1.),optax.adamw(args.learning_rate,weight_decay=1e-4))
|
| 64 |
+
state=optimizer.init(parameters);rng=np.random.default_rng(args.seed);restored=False;rng_restored=False
|
| 65 |
+
if args.init_weights:
|
| 66 |
+
optfile=args.init_weights.with_name(args.init_weights.name.replace('weights-','optimizer-'))
|
| 67 |
+
rngfile=args.init_weights.with_name(args.init_weights.name.replace('weights-','rng-')).with_suffix('.json')
|
| 68 |
+
if optfile.exists() and not args.reset_optimizer:
|
| 69 |
+
leaves,treedef=jax.tree_util.tree_flatten(state);saved=np.load(optfile)
|
| 70 |
+
state=jax.tree_util.tree_unflatten(treedef,[jnp.asarray(saved[f'arr_{i}']) for i in range(len(leaves))]);restored=True
|
| 71 |
+
if rngfile.exists() and not args.reset_rng:rng.bit_generator.state=json.loads(rngfile.read_text());rng_restored=True
|
| 72 |
+
if args.gradient_block_size:
|
| 73 |
+
from checkpoint_gradient import make_loss_and_grad as checkpoint_gradient
|
| 74 |
+
gradient=checkpoint_gradient(14,args.gradient_block_size)
|
| 75 |
+
else:gradient=make_loss_and_grad(14)
|
| 76 |
+
decode=make_decoder(14)
|
| 77 |
+
@jax.jit
|
| 78 |
+
def batch_gradient(parameters,ds,ys,base,context,static,valid,masks,measured,grid,measurement_indices,counts,example_weights):
|
| 79 |
+
p,pullback=jax.vjp(lambda w:probabilities(w,ds,base,context,static,valid,grid,measurement_indices,counts),parameters)
|
| 80 |
+
loss,pred,g=gradient(ds,ys,p,masks,measured)
|
| 81 |
+
grads=pullback(g*example_weights[None,:]/jnp.sum(example_weights))[0]
|
| 82 |
+
return grads,jnp.mean(loss),jnp.mean((pred>=.5)!=ys),jnp.sum(loss*example_weights)/jnp.sum(example_weights)
|
| 83 |
+
@jax.jit
|
| 84 |
+
def apply_gradient(parameters,state,grads):
|
| 85 |
+
changes,state=optimizer.update(grads,state,parameters)
|
| 86 |
+
return optax.apply_updates(parameters,changes),state,optax.global_norm(grads)
|
| 87 |
+
@jax.jit
|
| 88 |
+
def infer(parameters,ds,base,context,static,valid,masks,measured,grid,measurement_indices,counts):
|
| 89 |
+
p=probabilities(parameters,ds,base,context,static,valid,grid,measurement_indices,counts)
|
| 90 |
+
return decode(ds,p,masks,measured)
|
| 91 |
+
feature_names=['context','static','valid','masks','measured','grid','measurement_indices','counts']
|
| 92 |
+
def evaluate(step):
|
| 93 |
+
results=[];start=time.time()
|
| 94 |
+
for item in dataset:
|
| 95 |
+
n=min(args.validation_shots,len(item['validation_labels']))
|
| 96 |
+
ix=np.random.default_rng(20261102).choice(len(item['validation_labels']),n,replace=False)
|
| 97 |
+
length=((int(item['operation_count'])+511)//512)*512
|
| 98 |
+
features=[item[k][:length] for k in feature_names[:5]]+[item[k] for k in feature_names[5:]]
|
| 99 |
+
parts=[]
|
| 100 |
+
for begin in range(0,n,args.validation_batch):
|
| 101 |
+
selected=ix[begin:begin+args.validation_batch];size=len(selected)
|
| 102 |
+
ds=np.pad(item['validation_dets'][selected],((0,args.validation_batch-size),(0,0)))
|
| 103 |
+
base=np.pad(item['validation_base_logits'][selected,:length],((0,args.validation_batch-size),(0,0)))
|
| 104 |
+
parts.append(np.asarray(infer(parameters,ds,base,*features))[:size])
|
| 105 |
+
p=np.concatenate(parts);y=item['validation_labels'][ix].astype(np.float64)
|
| 106 |
+
pp=np.clip(p.astype(np.float64),1e-7,1-1e-7)
|
| 107 |
+
results.append({'condition':item['row']['name'],'failure':float(np.mean((p>=.5)!=y)),
|
| 108 |
+
'negative_log_likelihood':float(np.mean(-y*np.log(pp)-(1-y)*np.log1p(-pp)))})
|
| 109 |
+
result={'step':step,'validation_failure':float(np.mean([r['failure'] for r in results])),
|
| 110 |
+
'negative_log_likelihood':float(np.mean([r['negative_log_likelihood'] for r in results])),
|
| 111 |
+
'seconds':time.time()-start,'conditions':results}
|
| 112 |
+
(args.output/f'validation-{step}.json').write_text(json.dumps(result,indent=2)+'\n')
|
| 113 |
+
np.savez(args.output/f'weights-{step}.npz',**{k:np.asarray(v) for k,v in parameters.items()})
|
| 114 |
+
leaves,_=jax.tree_util.tree_flatten(state);np.savez(args.output/f'optimizer-{step}.npz',**{f'arr_{i}':np.asarray(v) for i,v in enumerate(leaves)})
|
| 115 |
+
(args.output/f'rng-{step}.json').write_text(json.dumps(rng.bit_generator.state)+'\n')
|
| 116 |
+
(args.output/f'checkpoint-{step}.json').write_text(json.dumps({'step':step,'training_samples':step*args.batch*args.accumulate_conditions,
|
| 117 |
+
'unique_training_rows_seen_in_this_phase':sum(int(mask.sum()) for mask in seen),
|
| 118 |
+
'weights_sha256':hashlib.sha256((args.output/f'weights-{step}.npz').read_bytes()).hexdigest(),'complete':True})+'\n')
|
| 119 |
+
print(json.dumps({k:v for k,v in result.items() if k!='conditions'}),flush=True)
|
| 120 |
+
evaluate(0);records=[]
|
| 121 |
+
for step in range(1,args.steps+1):
|
| 122 |
+
total_grads=None;loss=0.;error=0.;objective=0.
|
| 123 |
+
for _ in range(args.accumulate_conditions):
|
| 124 |
+
condition_index=int(rng.integers(len(dataset)));item=dataset[condition_index]
|
| 125 |
+
ix=rng.integers(len(item['train_labels']),size=args.batch);seen[condition_index][ix]=True
|
| 126 |
+
length=((int(item['operation_count'])+511)//512)*512 if args.bucket_operations else len(item['valid'])
|
| 127 |
+
features=[item[k][:length] for k in feature_names[:5]]+[item[k] for k in feature_names[5:]]
|
| 128 |
+
physical=item['train_physical_probabilities'][ix]
|
| 129 |
+
example_weights=(args.uncertainty_weight_floor+(1-args.uncertainty_weight_floor)*4*physical*(1-physical)).astype(np.float32)
|
| 130 |
+
grads,batch_loss,batch_error,batch_objective=batch_gradient(parameters,item['train_dets'][ix],item['train_labels'][ix],item['train_base_logits'][ix,:length],*features,example_weights)
|
| 131 |
+
total_grads=grads if total_grads is None else jax.tree_util.tree_map(jnp.add,total_grads,grads)
|
| 132 |
+
loss+=batch_loss/args.accumulate_conditions;error+=batch_error/args.accumulate_conditions
|
| 133 |
+
objective+=batch_objective/args.accumulate_conditions
|
| 134 |
+
total_grads=jax.tree_util.tree_map(lambda g:g/args.accumulate_conditions,total_grads)
|
| 135 |
+
parameters,state,norm=apply_gradient(parameters,state,total_grads)
|
| 136 |
+
if step==1 or step%16==0:
|
| 137 |
+
r={'step':step,'loss':float(loss),'objective':float(objective),'error':float(error),'gradient_norm':float(norm),'elapsed':time.time()-started}
|
| 138 |
+
assert np.isfinite(r['loss']);records.append(r);print(json.dumps(r),flush=True)
|
| 139 |
+
if step%args.eval_every==0 or step==args.steps:evaluate(step)
|
| 140 |
+
provenance={'initialization':(f'Continue from the recorded session-trained checkpoint; original random initialization seed {args.initial_seed}' if args.init_weights else
|
| 141 |
+
f'All parameters initialized in this session: variance-scaled normal hidden layers, Normal(0,.001) output weights, zero biases, seed {args.initial_seed}'),
|
| 142 |
+
'prior_pass':args.prior_pass,'initial_seed':args.initial_seed,
|
| 143 |
+
'training_source_sha256':source_hashes,'runtime_versions':config['runtime_versions'],
|
| 144 |
+
'hidden_width':actual_hidden,
|
| 145 |
+
'input_features':input_features,'feature_mode':feature_mode,
|
| 146 |
+
'architecture':f'Two {actual_hidden}-unit SiLU layers; {input_features} features; bounded 2*tanh correction to relevant-CSS edge logits from the recorded physical feedback pass; exact width-14 contraction predicts logical probability. D5 joint conditioning remains approximate.',
|
| 147 |
+
'training':('All supplied training shots per each of all26 d5 conditions; uniform condition and within-condition sampling for optimizer batches.' if args.training_cache else
|
| 148 |
+
'4096 training shots per each of all 26 d5 conditions, sampled without replacement with seed 20261023. Uniform condition and within-condition sampling for optimizer batches.'),
|
| 149 |
+
'training_cache':str(args.training_cache) if args.training_cache else None,
|
| 150 |
+
'training_cache_provenance':json.loads((args.training_cache/'provenance.json').read_text()) if args.training_cache else None,
|
| 151 |
+
'training_shots':sum(len(item['train_labels']) for item in dataset),
|
| 152 |
+
'training_pool_interpretation':'Eligible training rows; optimizer samples conditions and rows with replacement. Distinct rows used in this phase are recorded separately.',
|
| 153 |
+
'unique_training_rows_seen_in_this_phase':sum(int(mask.sum()) for mask in seen),
|
| 154 |
+
'unique_rows_by_condition':{item['row']['name']:int(mask.sum()) for item,mask in zip(dataset,seen)},
|
| 155 |
+
'gradient_block_size':args.gradient_block_size,
|
| 156 |
+
'bucket_operations':args.bucket_operations,
|
| 157 |
+
'accumulate_conditions':args.accumulate_conditions,
|
| 158 |
+
'effective_batch_size':args.batch*args.accumulate_conditions,
|
| 159 |
+
'uncertainty_weight_floor':args.uncertainty_weight_floor,
|
| 160 |
+
'example_weighting':('Uniform BCE' if args.uncertainty_weight_floor==1 else
|
| 161 |
+
'Frozen physical pass3 confidence gives w=floor+(1-floor)*4*p*(1-p), normalized within each condition batch. All weights positive; full validation remains unweighted.'),
|
| 162 |
+
'loss':'Conditional logical binary cross entropy, differentiated through exact relevant-CSS contraction; physical CSS feedback prior held fixed',
|
| 163 |
+
'steps':args.steps,'batch':args.batch,'learning_rate':args.learning_rate,'sampling_seed':args.seed,
|
| 164 |
+
'optimizer':'AdamW, weight decay 1e-4, global gradient norm clip 1','optimizer_restored':restored,
|
| 165 |
+
'rng_restored':rng_restored,
|
| 166 |
+
'explicit_optimizer_reset':args.reset_optimizer,'explicit_rng_reset':args.reset_rng,
|
| 167 |
+
'sampling_state_source':str(rngfile) if rng_restored else f'Fresh NumPy default_rng seed {args.seed}',
|
| 168 |
+
'starting_checkpoint':str(args.init_weights) if args.init_weights else None,
|
| 169 |
+
'starting_checkpoint_sha256':hashlib.sha256(args.init_weights.read_bytes()).hexdigest() if args.init_weights else None,
|
| 170 |
+
'starting_training_provenance':json.loads((args.init_weights.parent/'provenance.json').read_text()) if args.init_weights else None,
|
| 171 |
+
'validation':'Uniform subset per all 26 conditions, sample seed 20261102; full validation required before publication',
|
| 172 |
+
'validation_shots_per_condition':args.validation_shots,'test_data_used':False,'records':records}
|
| 173 |
+
(args.output/'provenance.json').write_text(json.dumps(provenance,indent=2)+'\n')
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
if __name__=='__main__':main()
|
tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S040/training_sources/fresh2_full/learned_exact__checkpoint_gradient.py
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Exact logical BCE gradient with block recomputation of frontier histories."""
|
| 2 |
+
import jax
|
| 3 |
+
import jax.numpy as jnp
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
def make_loss_and_grad(width, block_size=32):
|
| 7 |
+
indices = jnp.arange(1 << width, dtype=jnp.int32)
|
| 8 |
+
|
| 9 |
+
@jax.jit
|
| 10 |
+
def evaluate(dets, labels, probabilities, masks, measured):
|
| 11 |
+
nops, batch = probabilities.shape
|
| 12 |
+
padding = (-nops) % block_size
|
| 13 |
+
p = jnp.pad(probabilities, ((0, padding), (0, 0)))
|
| 14 |
+
m = jnp.pad(masks, (0, padding))
|
| 15 |
+
d = jnp.pad(measured, (0, padding), constant_values=-1)
|
| 16 |
+
blocks = (p.reshape(-1, block_size, batch), m.reshape(-1, block_size),
|
| 17 |
+
d.reshape(-1, block_size))
|
| 18 |
+
|
| 19 |
+
def forward(f, args):
|
| 20 |
+
probability, mask, detector = args
|
| 21 |
+
|
| 22 |
+
def error(f):
|
| 23 |
+
out = (1 - probability[:, None]) * f + probability[:, None] * f[:, indices ^ mask]
|
| 24 |
+
return out, jnp.ones(batch)
|
| 25 |
+
|
| 26 |
+
def project(f):
|
| 27 |
+
dst = (indices[None, :] & ~mask) | (dets[:, detector, None].astype(jnp.int32) * mask)
|
| 28 |
+
g = jnp.take_along_axis(f, dst, axis=1) * ((indices & mask) == 0)
|
| 29 |
+
norm = jnp.maximum(g.sum(axis=1), 1e-30)
|
| 30 |
+
return g / norm[:, None], norm
|
| 31 |
+
|
| 32 |
+
out, norm = jax.lax.cond(detector < 0, error, project, f)
|
| 33 |
+
return out, (f, norm)
|
| 34 |
+
|
| 35 |
+
def forward_block(f, args):
|
| 36 |
+
def step(carry, item):
|
| 37 |
+
result, _ = forward(carry, item)
|
| 38 |
+
return result, None
|
| 39 |
+
out, _ = jax.lax.scan(step, f, args)
|
| 40 |
+
return out, f
|
| 41 |
+
|
| 42 |
+
initial = jnp.zeros((batch, 1 << width), jnp.float32).at[:, 0].set(1)
|
| 43 |
+
f, checkpoints = jax.lax.scan(forward_block, initial, blocks)
|
| 44 |
+
indicator = ((indices[None, :] & 1) == labels[:, None])
|
| 45 |
+
correct = jnp.maximum(jnp.sum(f * indicator, axis=1), 1e-10)
|
| 46 |
+
prediction = jnp.sum(f[:, 1::2], axis=1)
|
| 47 |
+
terminal = 1 - indicator / correct[:, None]
|
| 48 |
+
|
| 49 |
+
def backward(b, args):
|
| 50 |
+
probability, mask, detector, old, norm = args
|
| 51 |
+
|
| 52 |
+
def error(b):
|
| 53 |
+
flipped = b[:, indices ^ mask]
|
| 54 |
+
grad = jnp.sum(old * (flipped - b), axis=1)
|
| 55 |
+
return (1 - probability[:, None]) * b + probability[:, None] * flipped, grad
|
| 56 |
+
|
| 57 |
+
def project(b):
|
| 58 |
+
obs = ((indices[None, :] & mask) == dets[:, detector, None].astype(jnp.int32) * mask)
|
| 59 |
+
values = b[:, indices & ~mask]
|
| 60 |
+
mean = jnp.sum(old * obs * values, axis=1) / norm
|
| 61 |
+
return (values - mean[:, None]) * obs / norm[:, None], jnp.zeros(batch)
|
| 62 |
+
|
| 63 |
+
return jax.lax.cond(detector < 0, error, project, b)
|
| 64 |
+
|
| 65 |
+
def backward_block(b, args):
|
| 66 |
+
probabilities, masks, measured, checkpoint = args
|
| 67 |
+
_, (history, norms) = jax.lax.scan(forward, checkpoint, (probabilities, masks, measured))
|
| 68 |
+
return jax.lax.scan(backward, b, (probabilities, masks, measured, history, norms), reverse=True)
|
| 69 |
+
|
| 70 |
+
_, gradients = jax.lax.scan(backward_block, terminal, (*blocks, checkpoints), reverse=True)
|
| 71 |
+
return -jnp.log(correct), prediction, gradients.reshape(-1, batch)[:nops]
|
| 72 |
+
|
| 73 |
+
return evaluate
|
tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S040/training_sources/fresh2_full/learned_exact__gradient.py
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Differentiable conditional logical likelihood through exact DEM elimination."""
|
| 2 |
+
import jax
|
| 3 |
+
import jax.numpy as jnp
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
def make_loss_and_grad(width):
|
| 7 |
+
indices=jnp.arange(1<<width,dtype=jnp.int32)
|
| 8 |
+
@jax.jit
|
| 9 |
+
def evaluate(dets,labels,probabilities,masks,measured):
|
| 10 |
+
# Per-shot error probabilities have shape [operations,batch].
|
| 11 |
+
f=jnp.zeros((len(dets),1<<width),jnp.float32).at[:,0].set(1)
|
| 12 |
+
def forward(f,args):
|
| 13 |
+
p,mask,d=args
|
| 14 |
+
def error(f):
|
| 15 |
+
return (1-p[:,None])*f+p[:,None]*f[:,indices^mask],jnp.ones(len(dets))
|
| 16 |
+
def project(f):
|
| 17 |
+
dst=(indices[None,:]&~mask)|(dets[:,d,None].astype(jnp.int32)*mask)
|
| 18 |
+
g=jnp.take_along_axis(f,dst,axis=1)*((indices&mask)==0)
|
| 19 |
+
norm=jnp.maximum(g.sum(axis=1),1e-30)
|
| 20 |
+
return g/norm[:,None],norm
|
| 21 |
+
out,norm=jax.lax.cond(d<0,error,project,f)
|
| 22 |
+
return out,(f,norm)
|
| 23 |
+
f,(history,norms)=jax.lax.scan(forward,f,(probabilities,masks,measured))
|
| 24 |
+
indicator=((indices[None,:]&1)==labels[:,None])
|
| 25 |
+
correct=jnp.maximum(jnp.sum(f*indicator,axis=1),1e-10)
|
| 26 |
+
predicted=jnp.sum(f[:,1::2],axis=1)
|
| 27 |
+
initial=1-indicator/correct[:,None]
|
| 28 |
+
def backward(b,args):
|
| 29 |
+
p,mask,d,old,norm=args
|
| 30 |
+
def error(b):
|
| 31 |
+
flipped=b[:,indices^mask]
|
| 32 |
+
grad=jnp.sum(old*(flipped-b),axis=1)
|
| 33 |
+
return (1-p[:,None])*b+p[:,None]*flipped,grad
|
| 34 |
+
def project(b):
|
| 35 |
+
obs=((indices[None,:]&mask)==dets[:,d,None].astype(jnp.int32)*mask)
|
| 36 |
+
values=b[:,indices&~mask]
|
| 37 |
+
mean=jnp.sum(old*obs*values,axis=1)/norm
|
| 38 |
+
prior=(values-mean[:,None])*obs/norm[:,None]
|
| 39 |
+
return prior,jnp.zeros(len(dets))
|
| 40 |
+
return jax.lax.cond(d<0,error,project,b)
|
| 41 |
+
_,grad=jax.lax.scan(backward,initial,(probabilities,masks,measured,history,norms),reverse=True)
|
| 42 |
+
return -jnp.log(correct),predicted,grad
|
| 43 |
+
return evaluate
|
tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S040/training_sources/fresh_specialize1/exact_d3__exact.py
ADDED
|
@@ -0,0 +1,213 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Exact detector-error-model contraction by bounded-frontier elimination."""
|
| 2 |
+
import collections
|
| 3 |
+
import numpy as np
|
| 4 |
+
import stim
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def parse_errors(dem):
|
| 8 |
+
errors = []
|
| 9 |
+
for ins in dem.flattened():
|
| 10 |
+
if ins.type != 'error':
|
| 11 |
+
continue
|
| 12 |
+
ds, logical = set(), 0
|
| 13 |
+
for t in ins.targets_copy():
|
| 14 |
+
if t.is_relative_detector_id():
|
| 15 |
+
ds.symmetric_difference_update([t.val])
|
| 16 |
+
elif t.is_logical_observable_id():
|
| 17 |
+
assert t.val == 0
|
| 18 |
+
logical ^= 1
|
| 19 |
+
errors.append((ds, logical, ins.args_copy()[0]))
|
| 20 |
+
return errors
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def elimination_order(dem, errors):
|
| 24 |
+
blocks = collections.defaultdict(list)
|
| 25 |
+
for d, c in dem.get_detector_coordinates().items():
|
| 26 |
+
blocks[c[-1]].append(d)
|
| 27 |
+
pending = [ds for ds, _, _ in errors if ds]
|
| 28 |
+
active, used, order = set(), set(), []
|
| 29 |
+
for _, block in sorted(blocks.items()):
|
| 30 |
+
remain = set(block)
|
| 31 |
+
while remain:
|
| 32 |
+
def score(d):
|
| 33 |
+
new = set().union(*(e for e in pending if d in e)) - used
|
| 34 |
+
return len(active | new), -sum(d in e for e in pending), d
|
| 35 |
+
d = min(remain, key=score)
|
| 36 |
+
related = [e for e in pending if d in e]
|
| 37 |
+
active |= set().union(*related) - used
|
| 38 |
+
active.discard(d)
|
| 39 |
+
pending = [e for e in pending if d not in e]
|
| 40 |
+
used.add(d)
|
| 41 |
+
remain.remove(d)
|
| 42 |
+
order.append(d)
|
| 43 |
+
assert sorted(order) == list(range(dem.num_detectors))
|
| 44 |
+
return order
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def make_plan(dem):
|
| 48 |
+
errors = parse_errors(dem)
|
| 49 |
+
order = elimination_order(dem, errors)
|
| 50 |
+
rank = {d: i for i, d in enumerate(order)}
|
| 51 |
+
groups = collections.defaultdict(list)
|
| 52 |
+
for source_index, (ds, logical, p) in enumerate(errors):
|
| 53 |
+
first = min(ds, key=rank.get) if ds else order[0]
|
| 54 |
+
groups[first].append((ds, logical, p, source_index))
|
| 55 |
+
slots, probabilities, masks, measured, source_indices = {}, [], [], [], []
|
| 56 |
+
width = 1
|
| 57 |
+
for d in order:
|
| 58 |
+
related = groups[d]
|
| 59 |
+
needed = set().union(*(ds for ds, _, _, _ in related)) | {d}
|
| 60 |
+
for node in sorted(needed):
|
| 61 |
+
if node not in slots:
|
| 62 |
+
free = next(i for i in range(1, 64) if i not in slots.values())
|
| 63 |
+
slots[node] = free
|
| 64 |
+
width = max(width, free+1)
|
| 65 |
+
for ds, logical, p, source_index in related:
|
| 66 |
+
mask = logical
|
| 67 |
+
for node in ds:
|
| 68 |
+
mask ^= 1 << slots[node]
|
| 69 |
+
probabilities.append(p)
|
| 70 |
+
masks.append(mask)
|
| 71 |
+
measured.append(-1)
|
| 72 |
+
source_indices.append(source_index)
|
| 73 |
+
probabilities.append(0)
|
| 74 |
+
masks.append(1 << slots.pop(d))
|
| 75 |
+
measured.append(d)
|
| 76 |
+
source_indices.append(-1)
|
| 77 |
+
assert not slots
|
| 78 |
+
return {'probabilities': np.array(probabilities, np.float32),
|
| 79 |
+
'masks': np.array(masks, np.int32), 'measured': np.array(measured, np.int32),
|
| 80 |
+
'width': np.array(width, np.int32), 'num_detectors': np.array(dem.num_detectors, np.int32),
|
| 81 |
+
'source_indices': np.array(source_indices, np.int32),
|
| 82 |
+
'order': np.array(order, np.int32)}
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def make_decoder(width):
|
| 86 |
+
import jax
|
| 87 |
+
import jax.numpy as jnp
|
| 88 |
+
indices = jnp.arange(1 << width, dtype=jnp.int32)
|
| 89 |
+
@jax.jit
|
| 90 |
+
def decode(dets, probabilities, masks, measured):
|
| 91 |
+
f = jnp.zeros((dets.shape[0], 1 << width), jnp.float32).at[:, 0].set(1)
|
| 92 |
+
def step(f, args):
|
| 93 |
+
p, mask, d = args
|
| 94 |
+
def error(f):
|
| 95 |
+
prob = p[:, None] if p.ndim else p
|
| 96 |
+
return (1-prob)*f + prob*f[:, indices ^ mask]
|
| 97 |
+
def project(f):
|
| 98 |
+
obs = dets[:, d].astype(jnp.int32)
|
| 99 |
+
dst = (indices[None, :] & ~mask) | (obs[:, None]*mask)
|
| 100 |
+
g = jnp.take_along_axis(f, dst, axis=1) * ((indices & mask)==0)
|
| 101 |
+
return g / jnp.maximum(jnp.sum(g, axis=1, keepdims=True), 1e-30)
|
| 102 |
+
return jax.lax.cond(d < 0, error, project, f), None
|
| 103 |
+
f, _ = jax.lax.scan(step, f, (probabilities, masks, measured))
|
| 104 |
+
return jnp.sum(f[:, 1::2], axis=1) / jnp.maximum(jnp.sum(f, axis=1), 1e-30)
|
| 105 |
+
return decode
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def make_marginals(width):
|
| 109 |
+
"""Per-shot derivatives of log syndrome probability give all error marginals."""
|
| 110 |
+
import jax
|
| 111 |
+
import jax.numpy as jnp
|
| 112 |
+
indices = jnp.arange(1 << width, dtype=jnp.int32)
|
| 113 |
+
def log_partition(dets, probabilities, masks, measured):
|
| 114 |
+
f = jnp.zeros(1 << width, jnp.float32).at[0].set(1)
|
| 115 |
+
def step(carry, args):
|
| 116 |
+
f, logz = carry
|
| 117 |
+
p, mask, d = args
|
| 118 |
+
def error(carry):
|
| 119 |
+
f, logz = carry
|
| 120 |
+
return ((1-p)*f + p*f[indices ^ mask], logz)
|
| 121 |
+
def project(carry):
|
| 122 |
+
f, logz = carry
|
| 123 |
+
dst = (indices & ~mask) | (dets[d].astype(jnp.int32)*mask)
|
| 124 |
+
g = f[dst] * ((indices & mask)==0)
|
| 125 |
+
norm = jnp.maximum(jnp.sum(g), 1e-30)
|
| 126 |
+
return g/norm, logz+jnp.log(norm)
|
| 127 |
+
return jax.lax.cond(d<0, error, project, carry), None
|
| 128 |
+
(_, logz), _ = jax.lax.scan(jax.checkpoint(step), (f, jnp.float32(0)), (probabilities, masks, measured))
|
| 129 |
+
return logz
|
| 130 |
+
return jax.jit(jax.vmap(jax.value_and_grad(log_partition, argnums=1), in_axes=(0,None,None,None)))
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
def make_marginals_fb(width, return_observable=False):
|
| 134 |
+
"""Forward/backward contraction without generic gather-gradient scatter."""
|
| 135 |
+
import jax
|
| 136 |
+
import jax.numpy as jnp
|
| 137 |
+
indices = jnp.arange(1 << width, dtype=jnp.int32)
|
| 138 |
+
# The syndrome likelihood marginalizes the unobserved logical bit. Keep
|
| 139 |
+
# that bit in the forward state for its output, but omit it from histories
|
| 140 |
+
# and backward messages, halving the largest buffers.
|
| 141 |
+
backward_width=width-1 if return_observable else width
|
| 142 |
+
backward_indices=jnp.arange(1 << backward_width,dtype=jnp.int32)
|
| 143 |
+
@jax.jit
|
| 144 |
+
def marginals(dets, probabilities, masks, measured):
|
| 145 |
+
f=jnp.zeros((dets.shape[0],1<<width),jnp.float32).at[:,0].set(1)
|
| 146 |
+
def forward(carry,args):
|
| 147 |
+
f,logz=carry
|
| 148 |
+
p,mask,d=args
|
| 149 |
+
def error(carry):
|
| 150 |
+
f,logz=carry
|
| 151 |
+
prob=p[:,None] if p.ndim else p
|
| 152 |
+
return ((1-prob)*f+prob*f[:,indices^mask],logz)
|
| 153 |
+
def project(carry):
|
| 154 |
+
f,logz=carry
|
| 155 |
+
dst=(indices[None,:]&~mask)|(dets[:,d,None].astype(jnp.int32)*mask)
|
| 156 |
+
g=jnp.take_along_axis(f,dst,axis=1)*((indices&mask)==0)
|
| 157 |
+
norm=jnp.maximum(g.sum(axis=1),1e-30)
|
| 158 |
+
return g/norm[:,None],logz+jnp.log(norm)
|
| 159 |
+
out=jax.lax.cond(d<0,error,project,carry)
|
| 160 |
+
return out,(f[:,::2]+f[:,1::2]) if return_observable else f
|
| 161 |
+
(final,logz),history=jax.lax.scan(forward,(f,jnp.zeros(len(dets))),(probabilities,masks,measured))
|
| 162 |
+
def backward(b,args):
|
| 163 |
+
p,mask,d,f=args
|
| 164 |
+
def error(b):
|
| 165 |
+
flipped=b[:,backward_indices^mask]
|
| 166 |
+
prob=p[:,None] if p.ndim else p
|
| 167 |
+
prior=(1-prob)*b+prob*flipped
|
| 168 |
+
norm=jnp.maximum(jnp.sum(f*prior,axis=1),1e-30)
|
| 169 |
+
q=p*jnp.sum(f*flipped,axis=1)/norm
|
| 170 |
+
grad=(q-p)/jnp.maximum(p*(1-p),1e-20)
|
| 171 |
+
return prior/norm[:,None],grad
|
| 172 |
+
def project(b):
|
| 173 |
+
prior=b[:,backward_indices&~mask]*((backward_indices[None,:]&mask)==(dets[:,d,None].astype(jnp.int32)*mask))
|
| 174 |
+
norm=jnp.maximum(jnp.sum(f*prior,axis=1),1e-30)
|
| 175 |
+
return prior/norm[:,None],jnp.zeros(len(dets))
|
| 176 |
+
return jax.lax.cond(d<0,error,project,b)
|
| 177 |
+
backward_masks=masks>>1 if return_observable else masks
|
| 178 |
+
_,grad=jax.lax.scan(backward,jnp.ones((len(dets),1<<backward_width),jnp.float32),
|
| 179 |
+
(probabilities,backward_masks,measured,history),reverse=True)
|
| 180 |
+
if return_observable:
|
| 181 |
+
return logz,grad.T,jnp.sum(final[:,1::2],axis=1)/jnp.maximum(jnp.sum(final,axis=1),1e-30)
|
| 182 |
+
return logz,grad.T
|
| 183 |
+
return marginals
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
def predict(plan, packed, decoder=None, batch=256):
|
| 187 |
+
import jax
|
| 188 |
+
decoder = decoder or make_decoder(int(plan['width']))
|
| 189 |
+
dets = np.unpackbits(packed, bitorder='little', axis=1, count=int(plan['num_detectors']))
|
| 190 |
+
args = [jax.device_put(plan[k]) for k in ['probabilities', 'masks', 'measured']]
|
| 191 |
+
result = []
|
| 192 |
+
for start in range(0, len(dets), batch):
|
| 193 |
+
ds = dets[start:start+batch]
|
| 194 |
+
ds = np.pad(ds, ((0, batch-len(ds)), (0, 0)))
|
| 195 |
+
result.append(np.asarray(decoder(ds, *args))[:min(batch, len(dets)-start)])
|
| 196 |
+
return np.concatenate(result)
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
if __name__ == '__main__':
|
| 200 |
+
import sys, time
|
| 201 |
+
from pathlib import Path
|
| 202 |
+
import jax
|
| 203 |
+
print(jax.devices(), flush=True)
|
| 204 |
+
path = Path(sys.argv[1])
|
| 205 |
+
dem = stim.DetectorErrorModel.from_file(path/'pij_from_even_for_odd.dem')
|
| 206 |
+
plan = make_plan(dem)
|
| 207 |
+
print({k: v.shape if v.ndim else int(v) for k, v in plan.items()}, flush=True)
|
| 208 |
+
a = np.load(path/'arrays.npz')
|
| 209 |
+
decoder = make_decoder(int(plan['width']))
|
| 210 |
+
for i in range(2):
|
| 211 |
+
t = time.time()
|
| 212 |
+
p = predict(plan, a['detectors'][:1024], decoder)
|
| 213 |
+
print({'seconds': time.time()-t, 'failure': np.mean((p>=.5)!=a['labels'][:len(p)]), 'min': p.min(), 'max': p.max()}, flush=True)
|
tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S040/training_sources/fresh_specialize1/learned_exact__data.py
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pathlib import Path
|
| 2 |
+
import json,sys
|
| 3 |
+
import numpy as np
|
| 4 |
+
import stim
|
| 5 |
+
sys.path.insert(0,'/workspace/research/exact_d3')
|
| 6 |
+
from exact import make_plan,parse_errors
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def _attach_arrays(item,root,splits):
|
| 10 |
+
row=item['row']
|
| 11 |
+
for split in splits:
|
| 12 |
+
a=np.load(root/split/row['arrays']);ds=np.unpackbits(a['detectors'],axis=1,count=row['num_detectors'],bitorder='little')
|
| 13 |
+
item[split+'_dets']=np.pad(ds,((0,0),(0,201-ds.shape[1])))
|
| 14 |
+
item[split+'_labels']=a['labels']
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def load_all(max_ops=3072,splits=('train','validation')):
|
| 18 |
+
assert set(splits)<=set(['train','validation'])
|
| 19 |
+
root=Path('/workspace/data')
|
| 20 |
+
rows=[r for r in json.loads((root/'train/manifest.json').read_text())['conditions'] if r['distance']==3]
|
| 21 |
+
groups=sorted({r['group'] for r in rows});result=[]
|
| 22 |
+
cache=Path('/workspace/research/learned_exact')/f'feature_cache-v2-{max_ops}'
|
| 23 |
+
cache.mkdir(exist_ok=True)
|
| 24 |
+
for row in rows:
|
| 25 |
+
cached=cache/f"{row['name']}-{row['noise_sha256'][:12]}-{row['circuit_sha256'][:12]}.npz"
|
| 26 |
+
if cached.exists():
|
| 27 |
+
item=dict(np.load(cached,allow_pickle=False));item['row']=row
|
| 28 |
+
_attach_arrays(item,root,splits);result.append(item);continue
|
| 29 |
+
dem=stim.DetectorErrorModel.from_file(root/'train'/row['noise']);plan=make_plan(dem)
|
| 30 |
+
assert int(plan['width'])<=10
|
| 31 |
+
count=len(plan['masks']);assert count<=max_ops,(row['name'],count)
|
| 32 |
+
coords=dem.get_detector_coordinates()
|
| 33 |
+
circuit=stim.Circuit.from_file(root/'train'/row['circuit'])
|
| 34 |
+
qubit_coords=circuit.get_final_qubit_coordinates()
|
| 35 |
+
first_measurement=next(ins for ins in circuit.flattened() if ins.name in ['M','MX','MR','MRX'])
|
| 36 |
+
spaces=sorted(tuple(qubit_coords[t.value][:2]) for t in first_measurement.targets_copy())
|
| 37 |
+
assert len(spaces)==8
|
| 38 |
+
idx={(int(c[2]),tuple(c[:2])):d for d,c in coords.items()}
|
| 39 |
+
errors=parse_errors(dem)
|
| 40 |
+
context=np.full((max_ops,40),200,np.int32)
|
| 41 |
+
static=np.zeros((max_ops,57),np.float32)
|
| 42 |
+
for op,source in enumerate(plan['source_indices']):
|
| 43 |
+
if source<0:continue
|
| 44 |
+
ds,logical,p=errors[source]
|
| 45 |
+
t=min(int(coords[d][2]) for d in ds) if ds else 0
|
| 46 |
+
for dt in range(-2,3):
|
| 47 |
+
for s,spatial in enumerate(spaces):context[op,(dt+2)*8+s]=idx.get((t+dt,spatial),200)
|
| 48 |
+
for d in ds:
|
| 49 |
+
c=coords[d];static[op,(int(c[2])-t+2)*8+spaces.index(tuple(c[:2]))]=1
|
| 50 |
+
static[op,40]=np.log(max(p,1e-7)/(1-max(p,1e-7)))/8
|
| 51 |
+
static[op,41]=logical;static[op,42]=len(ds)/4
|
| 52 |
+
static[op,43]=t/25;static[op,44]=row['rounds']/25
|
| 53 |
+
static[op,45]=t==0;static[op,46]=t>=row['rounds']-1
|
| 54 |
+
static[op,47+groups.index(row['group'])]=1
|
| 55 |
+
static[op,55]=row['basis']=='X';static[op,56]=1
|
| 56 |
+
masks=np.pad(plan['masks'],(0,max_ops-count))
|
| 57 |
+
measured=np.pad(plan['measured'],(0,max_ops-count),constant_values=-1)
|
| 58 |
+
p=np.pad(plan['probabilities'],(0,max_ops-count))
|
| 59 |
+
valid=((p>0)&(measured<0)).astype(np.float32)
|
| 60 |
+
logits=np.log(np.clip(p,1e-7,1-1e-7)/np.clip(1-p,1e-7,1-1e-7)).astype(np.float32)
|
| 61 |
+
item={'row':row,'context':context,'static':static,'masks':masks,'measured':measured,'base_logits':logits,'valid':valid}
|
| 62 |
+
grid=np.full((26,8),200,np.int32)
|
| 63 |
+
measurement_indices=np.full(201,208,np.int32)
|
| 64 |
+
for detector,c in coords.items():
|
| 65 |
+
t=int(c[2]);s=spaces.index(tuple(c[:2]));grid[t,s]=detector
|
| 66 |
+
measurement_indices[detector]=t*8+s
|
| 67 |
+
item['grid']=grid;item['measurement_indices']=measurement_indices
|
| 68 |
+
item['counts']=np.maximum((grid!=200).sum(axis=0),1).astype(np.float32)
|
| 69 |
+
temporary=cached.with_suffix('.tmp.npz')
|
| 70 |
+
np.savez(temporary,**{k:v for k,v in item.items() if k!='row'});temporary.replace(cached)
|
| 71 |
+
_attach_arrays(item,root,splits)
|
| 72 |
+
result.append(item)
|
| 73 |
+
return result
|
tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S040/training_sources/fresh_specialize1/learned_exact__fresh_specialize_train.py
ADDED
|
@@ -0,0 +1,161 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Derived from specialize_train.py SHA256 5a2e7ba25969f4599cb65d60cbd53544fd77d7a6926ec0d03662b72b151acf95; fresh-seed parent provenance only, unchanged update equations.
|
| 2 |
+
"""Fine-tune eight existing session-trained d3 models on their respective groups."""
|
| 3 |
+
import os
|
| 4 |
+
os.environ['OPENBLAS_NUM_THREADS']='1'
|
| 5 |
+
os.environ['OMP_NUM_THREADS']='1'
|
| 6 |
+
os.environ['XLA_PYTHON_CLIENT_PREALLOCATE']='false'
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
import argparse, hashlib, json, shutil, sys, time
|
| 9 |
+
import numpy as np
|
| 10 |
+
import jax, jax.numpy as jnp, optax
|
| 11 |
+
from data import load_all
|
| 12 |
+
from temporal_model import probabilities
|
| 13 |
+
from gradient import make_loss_and_grad
|
| 14 |
+
sys.path.insert(0,'/workspace/research/exact_d3')
|
| 15 |
+
from exact import make_decoder
|
| 16 |
+
|
| 17 |
+
FIELDS=['context','static','base_logits','valid','masks','measured','grid','measurement_indices','counts']
|
| 18 |
+
|
| 19 |
+
def sha(path):
|
| 20 |
+
return hashlib.sha256(Path(path).read_bytes()).hexdigest()
|
| 21 |
+
|
| 22 |
+
def main():
|
| 23 |
+
parser=argparse.ArgumentParser()
|
| 24 |
+
parser.add_argument('--package',type=Path,required=True)
|
| 25 |
+
parser.add_argument('--output',type=Path,required=True)
|
| 26 |
+
parser.add_argument('--steps',type=int,default=256)
|
| 27 |
+
parser.add_argument('--eval-every',type=int,default=128)
|
| 28 |
+
parser.add_argument('--batch',type=int,default=1024)
|
| 29 |
+
parser.add_argument('--validation-shots',type=int,default=1024)
|
| 30 |
+
parser.add_argument('--validation-batch',type=int,default=1024)
|
| 31 |
+
parser.add_argument('--learning-rate',type=float,default=.0001)
|
| 32 |
+
parser.add_argument('--seed',type=int,default=20261200)
|
| 33 |
+
parser.add_argument('--groups',nargs='+')
|
| 34 |
+
args=parser.parse_args()
|
| 35 |
+
assert args.steps>0 and args.eval_every>0 and args.batch>0
|
| 36 |
+
args.output.mkdir(parents=True,exist_ok=False)
|
| 37 |
+
config=json.loads((args.package/'model_config.json').read_text())
|
| 38 |
+
groups=sorted(config['temporal_contextual'])
|
| 39 |
+
if args.groups:
|
| 40 |
+
assert set(args.groups)<=set(groups)
|
| 41 |
+
groups=[g for g in groups if g in args.groups]
|
| 42 |
+
assert groups
|
| 43 |
+
source=Path(__file__).resolve();research=source.parent.parent
|
| 44 |
+
source_hashes={}
|
| 45 |
+
snapshot=args.output/'training_source';snapshot.mkdir()
|
| 46 |
+
for path in [source,source.parent/'temporal_model.py',source.parent/'data.py',
|
| 47 |
+
source.parent/'gradient.py',research/'exact_d3/exact.py']:
|
| 48 |
+
name=str(path.relative_to(research)).replace('/','__')
|
| 49 |
+
shutil.copyfile(path,snapshot/name);source_hashes[name]=sha(path)
|
| 50 |
+
parents=args.output/'parents';parents.mkdir()
|
| 51 |
+
shutil.copyfile(args.package/'training_provenance.json',parents/'training_provenance.json')
|
| 52 |
+
shutil.copyfile(args.package/'model_config.json',parents/'model_config.json')
|
| 53 |
+
run_config={k:str(v) if isinstance(v,Path) else v for k,v in vars(args).items()}
|
| 54 |
+
run_config.update(training_source_sha256=source_hashes,
|
| 55 |
+
runtime_versions={'jax':jax.__version__,'numpy':np.__version__,'optax':optax.__version__},
|
| 56 |
+
parent_config_sha256=sha(parents/'model_config.json'),
|
| 57 |
+
parent_provenance_sha256=sha(parents/'training_provenance.json'),
|
| 58 |
+
train_manifest_sha256=sha('/workspace/data/train/manifest.json'),
|
| 59 |
+
validation_manifest_sha256=sha('/workspace/data/validation/manifest.json'),
|
| 60 |
+
groups=groups)
|
| 61 |
+
(args.output/'run_config.json').write_text(json.dumps(run_config,indent=2)+'\n')
|
| 62 |
+
started=time.time();dataset=load_all()
|
| 63 |
+
dataset=[item for item in dataset if item['row']['group'] in groups]
|
| 64 |
+
assert len(dataset)==13*len(groups)
|
| 65 |
+
optimizer=optax.chain(optax.clip_by_global_norm(1.),optax.adamw(args.learning_rate,weight_decay=1e-4))
|
| 66 |
+
exact_gradient=make_loss_and_grad(10);exact_decode=make_decoder(10)
|
| 67 |
+
|
| 68 |
+
@jax.jit
|
| 69 |
+
def update(parameters,state,ds,ys,context,static,base_logits,valid,masks,measured,grid,measurement_indices,counts):
|
| 70 |
+
p,pullback=jax.vjp(lambda w:probabilities(w,ds,context,static,base_logits,valid,grid,measurement_indices,counts),parameters)
|
| 71 |
+
loss,pred,g=exact_gradient(ds,ys,p,masks,measured)
|
| 72 |
+
grads=pullback(g/len(ds))[0]
|
| 73 |
+
changes,state=optimizer.update(grads,state,parameters)
|
| 74 |
+
return optax.apply_updates(parameters,changes),state,jnp.mean(loss),jnp.mean((pred>=.5)!=ys),optax.global_norm(grads)
|
| 75 |
+
|
| 76 |
+
@jax.jit
|
| 77 |
+
def infer(parameters,ds,context,static,base_logits,valid,masks,measured,grid,measurement_indices,counts):
|
| 78 |
+
p=probabilities(parameters,ds,context,static,base_logits,valid,grid,measurement_indices,counts)
|
| 79 |
+
return exact_decode(ds,p,masks,measured)
|
| 80 |
+
|
| 81 |
+
reports={}
|
| 82 |
+
for group_index,group in enumerate(groups):
|
| 83 |
+
items=[item for item in dataset if item['row']['group']==group]
|
| 84 |
+
assert sorted(item['row']['rounds'] for item in items)==list(range(1,26,2))
|
| 85 |
+
out=args.output/group;out.mkdir()
|
| 86 |
+
settings=config['temporal_contextual'][group]
|
| 87 |
+
parent=args.package/settings['weights'];parent_copy=parents/f'{group}.npz'
|
| 88 |
+
shutil.copyfile(parent,parent_copy)
|
| 89 |
+
parameters={k:jnp.asarray(v) for k,v in dict(np.load(parent_copy,allow_pickle=False)).items()}
|
| 90 |
+
state=optimizer.init(parameters)
|
| 91 |
+
seed=args.seed+sorted(config['temporal_contextual']).index(group)
|
| 92 |
+
rng=np.random.default_rng(seed);seen=[np.zeros(len(i['train_labels']),bool) for i in items]
|
| 93 |
+
records=[]
|
| 94 |
+
|
| 95 |
+
def evaluate(step):
|
| 96 |
+
results=[];begin=time.time()
|
| 97 |
+
for item in items:
|
| 98 |
+
n=min(args.validation_shots,len(item['validation_labels']))
|
| 99 |
+
ix=np.random.default_rng(20261028).choice(len(item['validation_labels']),n,replace=False)
|
| 100 |
+
vd=item['validation_dets'][ix];vy=item['validation_labels'][ix];parts=[]
|
| 101 |
+
for start in range(0,n,args.validation_batch):
|
| 102 |
+
ds=vd[start:start+args.validation_batch];size=len(ds)
|
| 103 |
+
ds=np.pad(ds,((0,args.validation_batch-size),(0,0)))
|
| 104 |
+
parts.append(np.asarray(infer(parameters,ds,*[item[k] for k in FIELDS]))[:size])
|
| 105 |
+
p=np.concatenate(parts);pp=np.clip(p.astype(np.float64),1e-7,1-1e-7);yy=vy.astype(np.float64)
|
| 106 |
+
results.append({'condition':item['row']['name'],'failure':float(np.mean((p>=.5)!=vy)),
|
| 107 |
+
'negative_log_likelihood':float(np.mean(-yy*np.log(pp)-(1-yy)*np.log1p(-pp)))})
|
| 108 |
+
result={'group':group,'step':step,'validation_failure':float(np.mean([r['failure'] for r in results])),
|
| 109 |
+
'negative_log_likelihood':float(np.mean([r['negative_log_likelihood'] for r in results])),
|
| 110 |
+
'seconds':time.time()-begin,'conditions':results}
|
| 111 |
+
(out/f'validation-{step}.json').write_text(json.dumps(result,indent=2)+'\n')
|
| 112 |
+
np.savez(out/f'weights-{step}.npz',**{k:np.asarray(v) for k,v in parameters.items()})
|
| 113 |
+
leaves,_=jax.tree_util.tree_flatten(state)
|
| 114 |
+
np.savez(out/f'optimizer-{step}.npz',**{f'arr_{i}':np.asarray(v) for i,v in enumerate(leaves)})
|
| 115 |
+
(out/f'rng-{step}.json').write_text(json.dumps(rng.bit_generator.state)+'\n')
|
| 116 |
+
checkpoint={'group':group,'step':step,'training_draws':step*args.batch,
|
| 117 |
+
'unique_training_rows_seen_in_this_phase':sum(int(x.sum()) for x in seen),
|
| 118 |
+
'unique_rows_by_condition':{i['row']['name']:int(x.sum()) for i,x in zip(items,seen)},
|
| 119 |
+
'weights':f'weights-{step}.npz','weights_sha256':sha(out/f'weights-{step}.npz'),'complete':True}
|
| 120 |
+
(out/f'checkpoint-{step}.json').write_text(json.dumps(checkpoint,indent=2)+'\n')
|
| 121 |
+
print(json.dumps({k:v for k,v in result.items() if k!='conditions'}),flush=True)
|
| 122 |
+
|
| 123 |
+
evaluate(0)
|
| 124 |
+
for step in range(1,args.steps+1):
|
| 125 |
+
ci=int(rng.integers(len(items)));item=items[ci]
|
| 126 |
+
ix=rng.integers(len(item['train_labels']),size=args.batch);seen[ci][ix]=True
|
| 127 |
+
parameters,state,loss,error,norm=update(parameters,state,item['train_dets'][ix],item['train_labels'][ix],*[item[k] for k in FIELDS])
|
| 128 |
+
if step==1 or step%16==0:
|
| 129 |
+
record={'group':group,'step':step,'loss':float(loss),'error':float(error),
|
| 130 |
+
'gradient_norm':float(norm),'elapsed':time.time()-started}
|
| 131 |
+
assert np.isfinite(record['loss']);records.append(record);print(json.dumps(record),flush=True)
|
| 132 |
+
if step%args.eval_every==0 or step==args.steps:evaluate(step)
|
| 133 |
+
provenance={'initialization':'Continue the temporal component of the selected session-trained group decoder; no new random parameters',
|
| 134 |
+
'original_initialization':'Fresh rich trunk seed20261300 and temporal encoder seed20261301; parent may be a recorded within-trajectory parameter average; all fitting occurred in this session',
|
| 135 |
+
'group':group,'parent_model':settings,'parent_weights_sha256':sha(parent_copy),
|
| 136 |
+
'parent_provenance_sha256':run_config['parent_provenance_sha256'],
|
| 137 |
+
'parent_record':'../parents/training_provenance.json',
|
| 138 |
+
'training':'Uniform sampling over all13 odd round counts for this geometry/basis group, supplied training labels only',
|
| 139 |
+
'eligible_training_shots':sum(len(i['train_labels']) for i in items),
|
| 140 |
+
'training_draws':args.steps*args.batch,
|
| 141 |
+
'unique_training_rows_seen_in_this_phase':sum(int(x.sum()) for x in seen),
|
| 142 |
+
'unique_rows_by_condition':{i['row']['name']:int(x.sum()) for i,x in zip(items,seen)},
|
| 143 |
+
'steps':args.steps,'batch_size':args.batch,'learning_rate':args.learning_rate,
|
| 144 |
+
'optimizer':'Fresh AdamW moments for every group, weight decay1e-4, global norm clip1',
|
| 145 |
+
'optimizer_restored':False,'rng_restored':False,'sampling_seed':seed,
|
| 146 |
+
'validation':'Fixed random screen per condition using seed20261028; full validation is used by the separate selector',
|
| 147 |
+
'validation_shots_requested_per_condition':args.validation_shots,
|
| 148 |
+
'loss':'Uniform binary conditional logical likelihood through exact frontier contraction',
|
| 149 |
+
'training_source_sha256':source_hashes,'test_data_used':False,'log':records}
|
| 150 |
+
(out/'provenance.json').write_text(json.dumps(provenance,indent=2)+'\n');reports[group]=provenance
|
| 151 |
+
(args.output/'provenance.json').write_text(json.dumps({'experiment':'group-specific d3 continuation','groups':reports,
|
| 152 |
+
'initialization':'Continue session-trained selected temporal components; no new random parameters',
|
| 153 |
+
'training':'Each group samples uniformly over its own13 durations; supplied training labels only',
|
| 154 |
+
'eligible_training_shots':sum(len(i['train_labels']) for i in dataset),
|
| 155 |
+
'steps':args.steps*len(groups),'steps_per_group':args.steps,'batch_size':args.batch,
|
| 156 |
+
'learning_rate':args.learning_rate,'optimizer_restored':False,'rng_restored':False,
|
| 157 |
+
'training_source_sha256':source_hashes,
|
| 158 |
+
'run_config':run_config,'parent_record':'parents/training_provenance.json','new_random_parameters':0,
|
| 159 |
+
'training_draws':args.steps*args.batch*len(groups),'test_data_used':False},indent=2)+'\n')
|
| 160 |
+
|
| 161 |
+
if __name__=='__main__':main()
|
tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S040/training_sources/fresh_specialize1/learned_exact__gradient.py
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Differentiable conditional logical likelihood through exact DEM elimination."""
|
| 2 |
+
import jax
|
| 3 |
+
import jax.numpy as jnp
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
def make_loss_and_grad(width):
|
| 7 |
+
indices=jnp.arange(1<<width,dtype=jnp.int32)
|
| 8 |
+
@jax.jit
|
| 9 |
+
def evaluate(dets,labels,probabilities,masks,measured):
|
| 10 |
+
# Per-shot error probabilities have shape [operations,batch].
|
| 11 |
+
f=jnp.zeros((len(dets),1<<width),jnp.float32).at[:,0].set(1)
|
| 12 |
+
def forward(f,args):
|
| 13 |
+
p,mask,d=args
|
| 14 |
+
def error(f):
|
| 15 |
+
return (1-p[:,None])*f+p[:,None]*f[:,indices^mask],jnp.ones(len(dets))
|
| 16 |
+
def project(f):
|
| 17 |
+
dst=(indices[None,:]&~mask)|(dets[:,d,None].astype(jnp.int32)*mask)
|
| 18 |
+
g=jnp.take_along_axis(f,dst,axis=1)*((indices&mask)==0)
|
| 19 |
+
norm=jnp.maximum(g.sum(axis=1),1e-30)
|
| 20 |
+
return g/norm[:,None],norm
|
| 21 |
+
out,norm=jax.lax.cond(d<0,error,project,f)
|
| 22 |
+
return out,(f,norm)
|
| 23 |
+
f,(history,norms)=jax.lax.scan(forward,f,(probabilities,masks,measured))
|
| 24 |
+
indicator=((indices[None,:]&1)==labels[:,None])
|
| 25 |
+
correct=jnp.maximum(jnp.sum(f*indicator,axis=1),1e-10)
|
| 26 |
+
predicted=jnp.sum(f[:,1::2],axis=1)
|
| 27 |
+
initial=1-indicator/correct[:,None]
|
| 28 |
+
def backward(b,args):
|
| 29 |
+
p,mask,d,old,norm=args
|
| 30 |
+
def error(b):
|
| 31 |
+
flipped=b[:,indices^mask]
|
| 32 |
+
grad=jnp.sum(old*(flipped-b),axis=1)
|
| 33 |
+
return (1-p[:,None])*b+p[:,None]*flipped,grad
|
| 34 |
+
def project(b):
|
| 35 |
+
obs=((indices[None,:]&mask)==dets[:,d,None].astype(jnp.int32)*mask)
|
| 36 |
+
values=b[:,indices&~mask]
|
| 37 |
+
mean=jnp.sum(old*obs*values,axis=1)/norm
|
| 38 |
+
prior=(values-mean[:,None])*obs/norm[:,None]
|
| 39 |
+
return prior,jnp.zeros(len(dets))
|
| 40 |
+
return jax.lax.cond(d<0,error,project,b)
|
| 41 |
+
_,grad=jax.lax.scan(backward,initial,(probabilities,masks,measured,history,norms),reverse=True)
|
| 42 |
+
return -jnp.log(correct),predicted,grad
|
| 43 |
+
return evaluate
|
tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S040/training_sources/fresh_specialize1/learned_exact__temporal_model.py
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Long temporal context for contextual exact d3 decoding."""
|
| 2 |
+
import numpy as np
|
| 3 |
+
import jax
|
| 4 |
+
import jax.numpy as jnp
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def initialize_from_rich(path,seed=20261104,channels=32):
|
| 8 |
+
parameters={k:jnp.asarray(v) for k,v in dict(np.load(path,allow_pickle=False)).items()}
|
| 9 |
+
keys=jax.random.split(jax.random.key(seed),6)
|
| 10 |
+
parameters['w1']=jnp.concatenate([parameters['w1'],jax.random.normal(keys[0],(channels,parameters['w1'].shape[1]))*.001],axis=0)
|
| 11 |
+
parameters['temporal_in']=jax.random.normal(keys[1],(24,channels))*jnp.sqrt(2/24)
|
| 12 |
+
parameters['temporal_bias']=jnp.zeros(channels)
|
| 13 |
+
for i in range(4):
|
| 14 |
+
parameters[f'temporal_conv_{i}']=jax.random.normal(keys[i+2],(3,channels,channels))*jnp.sqrt(1/(3*channels))
|
| 15 |
+
parameters[f'temporal_conv_bias_{i}']=jnp.zeros(channels)
|
| 16 |
+
return parameters
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def probabilities(parameters,dets,context_indices,static,base_logits,valid,grid,measurement_indices,counts):
|
| 20 |
+
event_grid=dets[:,grid]
|
| 21 |
+
measurement_grid=(jnp.cumsum(event_grid.astype(jnp.int32),axis=1)&1).astype(jnp.float32)
|
| 22 |
+
observed=(grid!=200).astype(jnp.float32)
|
| 23 |
+
frames=jnp.concatenate([event_grid.astype(jnp.float32),measurement_grid*observed[None,:,:],
|
| 24 |
+
jnp.broadcast_to(observed[None,:,:],event_grid.shape)],axis=-1)
|
| 25 |
+
temporal=jax.nn.silu(frames@parameters['temporal_in']+parameters['temporal_bias'])
|
| 26 |
+
for i,dilation in enumerate([1,2,4,8]):
|
| 27 |
+
mean=jnp.mean(temporal,axis=-1,keepdims=True)
|
| 28 |
+
normalized=(temporal-mean)*jax.lax.rsqrt(jnp.mean((temporal-mean)**2,axis=-1,keepdims=True)+1e-5)
|
| 29 |
+
value=jax.lax.conv_general_dilated(normalized,parameters[f'temporal_conv_{i}'],(1,),padding='SAME',
|
| 30 |
+
rhs_dilation=(dilation,),dimension_numbers=('NWC','WIO','NWC'))
|
| 31 |
+
temporal=temporal+jax.nn.silu(value+parameters[f'temporal_conv_bias_{i}'])
|
| 32 |
+
times=jnp.clip(jnp.rint(static[:,43]*25).astype(jnp.int32),0,25)
|
| 33 |
+
temporal_context=temporal[:,times,:]
|
| 34 |
+
measured=jnp.pad(measurement_grid.reshape(len(dets),208),((0,0),(0,1)))
|
| 35 |
+
events=dets[:,context_indices].astype(jnp.float32)
|
| 36 |
+
measurements=measured[:,measurement_indices[context_indices]].astype(jnp.float32)
|
| 37 |
+
density=jnp.sum(event_grid,axis=1)/counts[None,:]
|
| 38 |
+
features=jnp.concatenate([events,measurements,
|
| 39 |
+
jnp.broadcast_to(density[:,None,:],(len(dets),len(context_indices),8)),
|
| 40 |
+
jnp.broadcast_to(static[None,:,:],(len(dets),*static.shape)),temporal_context],axis=-1)
|
| 41 |
+
h=jax.nn.silu(features@parameters['w1']+parameters['b1'])
|
| 42 |
+
h=jax.nn.silu(h@parameters['w2']+parameters['b2'])
|
| 43 |
+
delta=4*jnp.tanh((h@parameters['w3']+parameters['b3'])[...,0])
|
| 44 |
+
return (jax.nn.sigmoid(base_logits[None,:]+delta)*valid[None,:]).T
|
tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S040/training_sources/fresh_specialize1/parent_training_provenance.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S040/training_sources/fresh_specialize1/run_config.json
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"package": "/run-state/workspace/research/learned_exact/fresh_specialize1_parents",
|
| 3 |
+
"output": "/run-state/workspace/research/learned_exact/fresh_specialize1",
|
| 4 |
+
"steps": 256,
|
| 5 |
+
"eval_every": 128,
|
| 6 |
+
"batch": 1024,
|
| 7 |
+
"validation_shots": 1024,
|
| 8 |
+
"validation_batch": 1024,
|
| 9 |
+
"learning_rate": 0.0001,
|
| 10 |
+
"seed": 20261340,
|
| 11 |
+
"groups": [
|
| 12 |
+
"d3_bX_center_3_5",
|
| 13 |
+
"d3_bX_center_5_3",
|
| 14 |
+
"d3_bX_center_5_7",
|
| 15 |
+
"d3_bX_center_7_5",
|
| 16 |
+
"d3_bZ_center_3_5",
|
| 17 |
+
"d3_bZ_center_5_3",
|
| 18 |
+
"d3_bZ_center_5_7",
|
| 19 |
+
"d3_bZ_center_7_5"
|
| 20 |
+
],
|
| 21 |
+
"training_source_sha256": {
|
| 22 |
+
"learned_exact__fresh_specialize_train.py": "a9e0de6a3ea39c5bc1b4cc81a8b112273a2f237df0e97f8ba6ccb4d70a632a5f",
|
| 23 |
+
"learned_exact__temporal_model.py": "76fd01d5ae50f7d0b5790800898e7103ddb86db8f6a2ace883407515add2e186",
|
| 24 |
+
"learned_exact__data.py": "6f88582230aec7bbf35170a672ff615cac0cf18c0a690b2983874bb4c02c75e6",
|
| 25 |
+
"learned_exact__gradient.py": "ecb6b45698480386fa124fe878db7dbfa246d1969fd720ec26daff9547da2001",
|
| 26 |
+
"exact_d3__exact.py": "869dfacb295c419c156d1070fc2afdd6e20d02ac1840e45e72346b2b289f4825"
|
| 27 |
+
},
|
| 28 |
+
"runtime_versions": {
|
| 29 |
+
"jax": "0.7.2",
|
| 30 |
+
"numpy": "2.3.3",
|
| 31 |
+
"optax": "0.2.6"
|
| 32 |
+
},
|
| 33 |
+
"parent_config_sha256": "7aaeceb1cb1b1de03d151539dfaf13bd195361484e553a8c0e7085eb3d563127",
|
| 34 |
+
"parent_provenance_sha256": "579a7c41148f2721b361f395a2fd70e17cf344be6528560fb13c54b713ffbdb0",
|
| 35 |
+
"train_manifest_sha256": "ce46c21e3595cfc5885bbe2b6481105317d2e6267498ec4572601469825914b8",
|
| 36 |
+
"validation_manifest_sha256": "482bb7268c6c827ebbf1f756ee6994750acfcd011adab08eaa2ada703e5faea1"
|
| 37 |
+
}
|
tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S040/training_sources/fresh_temporal1_full/exact_d3__exact.py
ADDED
|
@@ -0,0 +1,213 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Exact detector-error-model contraction by bounded-frontier elimination."""
|
| 2 |
+
import collections
|
| 3 |
+
import numpy as np
|
| 4 |
+
import stim
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def parse_errors(dem):
|
| 8 |
+
errors = []
|
| 9 |
+
for ins in dem.flattened():
|
| 10 |
+
if ins.type != 'error':
|
| 11 |
+
continue
|
| 12 |
+
ds, logical = set(), 0
|
| 13 |
+
for t in ins.targets_copy():
|
| 14 |
+
if t.is_relative_detector_id():
|
| 15 |
+
ds.symmetric_difference_update([t.val])
|
| 16 |
+
elif t.is_logical_observable_id():
|
| 17 |
+
assert t.val == 0
|
| 18 |
+
logical ^= 1
|
| 19 |
+
errors.append((ds, logical, ins.args_copy()[0]))
|
| 20 |
+
return errors
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def elimination_order(dem, errors):
|
| 24 |
+
blocks = collections.defaultdict(list)
|
| 25 |
+
for d, c in dem.get_detector_coordinates().items():
|
| 26 |
+
blocks[c[-1]].append(d)
|
| 27 |
+
pending = [ds for ds, _, _ in errors if ds]
|
| 28 |
+
active, used, order = set(), set(), []
|
| 29 |
+
for _, block in sorted(blocks.items()):
|
| 30 |
+
remain = set(block)
|
| 31 |
+
while remain:
|
| 32 |
+
def score(d):
|
| 33 |
+
new = set().union(*(e for e in pending if d in e)) - used
|
| 34 |
+
return len(active | new), -sum(d in e for e in pending), d
|
| 35 |
+
d = min(remain, key=score)
|
| 36 |
+
related = [e for e in pending if d in e]
|
| 37 |
+
active |= set().union(*related) - used
|
| 38 |
+
active.discard(d)
|
| 39 |
+
pending = [e for e in pending if d not in e]
|
| 40 |
+
used.add(d)
|
| 41 |
+
remain.remove(d)
|
| 42 |
+
order.append(d)
|
| 43 |
+
assert sorted(order) == list(range(dem.num_detectors))
|
| 44 |
+
return order
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def make_plan(dem):
|
| 48 |
+
errors = parse_errors(dem)
|
| 49 |
+
order = elimination_order(dem, errors)
|
| 50 |
+
rank = {d: i for i, d in enumerate(order)}
|
| 51 |
+
groups = collections.defaultdict(list)
|
| 52 |
+
for source_index, (ds, logical, p) in enumerate(errors):
|
| 53 |
+
first = min(ds, key=rank.get) if ds else order[0]
|
| 54 |
+
groups[first].append((ds, logical, p, source_index))
|
| 55 |
+
slots, probabilities, masks, measured, source_indices = {}, [], [], [], []
|
| 56 |
+
width = 1
|
| 57 |
+
for d in order:
|
| 58 |
+
related = groups[d]
|
| 59 |
+
needed = set().union(*(ds for ds, _, _, _ in related)) | {d}
|
| 60 |
+
for node in sorted(needed):
|
| 61 |
+
if node not in slots:
|
| 62 |
+
free = next(i for i in range(1, 64) if i not in slots.values())
|
| 63 |
+
slots[node] = free
|
| 64 |
+
width = max(width, free+1)
|
| 65 |
+
for ds, logical, p, source_index in related:
|
| 66 |
+
mask = logical
|
| 67 |
+
for node in ds:
|
| 68 |
+
mask ^= 1 << slots[node]
|
| 69 |
+
probabilities.append(p)
|
| 70 |
+
masks.append(mask)
|
| 71 |
+
measured.append(-1)
|
| 72 |
+
source_indices.append(source_index)
|
| 73 |
+
probabilities.append(0)
|
| 74 |
+
masks.append(1 << slots.pop(d))
|
| 75 |
+
measured.append(d)
|
| 76 |
+
source_indices.append(-1)
|
| 77 |
+
assert not slots
|
| 78 |
+
return {'probabilities': np.array(probabilities, np.float32),
|
| 79 |
+
'masks': np.array(masks, np.int32), 'measured': np.array(measured, np.int32),
|
| 80 |
+
'width': np.array(width, np.int32), 'num_detectors': np.array(dem.num_detectors, np.int32),
|
| 81 |
+
'source_indices': np.array(source_indices, np.int32),
|
| 82 |
+
'order': np.array(order, np.int32)}
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def make_decoder(width):
|
| 86 |
+
import jax
|
| 87 |
+
import jax.numpy as jnp
|
| 88 |
+
indices = jnp.arange(1 << width, dtype=jnp.int32)
|
| 89 |
+
@jax.jit
|
| 90 |
+
def decode(dets, probabilities, masks, measured):
|
| 91 |
+
f = jnp.zeros((dets.shape[0], 1 << width), jnp.float32).at[:, 0].set(1)
|
| 92 |
+
def step(f, args):
|
| 93 |
+
p, mask, d = args
|
| 94 |
+
def error(f):
|
| 95 |
+
prob = p[:, None] if p.ndim else p
|
| 96 |
+
return (1-prob)*f + prob*f[:, indices ^ mask]
|
| 97 |
+
def project(f):
|
| 98 |
+
obs = dets[:, d].astype(jnp.int32)
|
| 99 |
+
dst = (indices[None, :] & ~mask) | (obs[:, None]*mask)
|
| 100 |
+
g = jnp.take_along_axis(f, dst, axis=1) * ((indices & mask)==0)
|
| 101 |
+
return g / jnp.maximum(jnp.sum(g, axis=1, keepdims=True), 1e-30)
|
| 102 |
+
return jax.lax.cond(d < 0, error, project, f), None
|
| 103 |
+
f, _ = jax.lax.scan(step, f, (probabilities, masks, measured))
|
| 104 |
+
return jnp.sum(f[:, 1::2], axis=1) / jnp.maximum(jnp.sum(f, axis=1), 1e-30)
|
| 105 |
+
return decode
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def make_marginals(width):
|
| 109 |
+
"""Per-shot derivatives of log syndrome probability give all error marginals."""
|
| 110 |
+
import jax
|
| 111 |
+
import jax.numpy as jnp
|
| 112 |
+
indices = jnp.arange(1 << width, dtype=jnp.int32)
|
| 113 |
+
def log_partition(dets, probabilities, masks, measured):
|
| 114 |
+
f = jnp.zeros(1 << width, jnp.float32).at[0].set(1)
|
| 115 |
+
def step(carry, args):
|
| 116 |
+
f, logz = carry
|
| 117 |
+
p, mask, d = args
|
| 118 |
+
def error(carry):
|
| 119 |
+
f, logz = carry
|
| 120 |
+
return ((1-p)*f + p*f[indices ^ mask], logz)
|
| 121 |
+
def project(carry):
|
| 122 |
+
f, logz = carry
|
| 123 |
+
dst = (indices & ~mask) | (dets[d].astype(jnp.int32)*mask)
|
| 124 |
+
g = f[dst] * ((indices & mask)==0)
|
| 125 |
+
norm = jnp.maximum(jnp.sum(g), 1e-30)
|
| 126 |
+
return g/norm, logz+jnp.log(norm)
|
| 127 |
+
return jax.lax.cond(d<0, error, project, carry), None
|
| 128 |
+
(_, logz), _ = jax.lax.scan(jax.checkpoint(step), (f, jnp.float32(0)), (probabilities, masks, measured))
|
| 129 |
+
return logz
|
| 130 |
+
return jax.jit(jax.vmap(jax.value_and_grad(log_partition, argnums=1), in_axes=(0,None,None,None)))
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
def make_marginals_fb(width, return_observable=False):
|
| 134 |
+
"""Forward/backward contraction without generic gather-gradient scatter."""
|
| 135 |
+
import jax
|
| 136 |
+
import jax.numpy as jnp
|
| 137 |
+
indices = jnp.arange(1 << width, dtype=jnp.int32)
|
| 138 |
+
# The syndrome likelihood marginalizes the unobserved logical bit. Keep
|
| 139 |
+
# that bit in the forward state for its output, but omit it from histories
|
| 140 |
+
# and backward messages, halving the largest buffers.
|
| 141 |
+
backward_width=width-1 if return_observable else width
|
| 142 |
+
backward_indices=jnp.arange(1 << backward_width,dtype=jnp.int32)
|
| 143 |
+
@jax.jit
|
| 144 |
+
def marginals(dets, probabilities, masks, measured):
|
| 145 |
+
f=jnp.zeros((dets.shape[0],1<<width),jnp.float32).at[:,0].set(1)
|
| 146 |
+
def forward(carry,args):
|
| 147 |
+
f,logz=carry
|
| 148 |
+
p,mask,d=args
|
| 149 |
+
def error(carry):
|
| 150 |
+
f,logz=carry
|
| 151 |
+
prob=p[:,None] if p.ndim else p
|
| 152 |
+
return ((1-prob)*f+prob*f[:,indices^mask],logz)
|
| 153 |
+
def project(carry):
|
| 154 |
+
f,logz=carry
|
| 155 |
+
dst=(indices[None,:]&~mask)|(dets[:,d,None].astype(jnp.int32)*mask)
|
| 156 |
+
g=jnp.take_along_axis(f,dst,axis=1)*((indices&mask)==0)
|
| 157 |
+
norm=jnp.maximum(g.sum(axis=1),1e-30)
|
| 158 |
+
return g/norm[:,None],logz+jnp.log(norm)
|
| 159 |
+
out=jax.lax.cond(d<0,error,project,carry)
|
| 160 |
+
return out,(f[:,::2]+f[:,1::2]) if return_observable else f
|
| 161 |
+
(final,logz),history=jax.lax.scan(forward,(f,jnp.zeros(len(dets))),(probabilities,masks,measured))
|
| 162 |
+
def backward(b,args):
|
| 163 |
+
p,mask,d,f=args
|
| 164 |
+
def error(b):
|
| 165 |
+
flipped=b[:,backward_indices^mask]
|
| 166 |
+
prob=p[:,None] if p.ndim else p
|
| 167 |
+
prior=(1-prob)*b+prob*flipped
|
| 168 |
+
norm=jnp.maximum(jnp.sum(f*prior,axis=1),1e-30)
|
| 169 |
+
q=p*jnp.sum(f*flipped,axis=1)/norm
|
| 170 |
+
grad=(q-p)/jnp.maximum(p*(1-p),1e-20)
|
| 171 |
+
return prior/norm[:,None],grad
|
| 172 |
+
def project(b):
|
| 173 |
+
prior=b[:,backward_indices&~mask]*((backward_indices[None,:]&mask)==(dets[:,d,None].astype(jnp.int32)*mask))
|
| 174 |
+
norm=jnp.maximum(jnp.sum(f*prior,axis=1),1e-30)
|
| 175 |
+
return prior/norm[:,None],jnp.zeros(len(dets))
|
| 176 |
+
return jax.lax.cond(d<0,error,project,b)
|
| 177 |
+
backward_masks=masks>>1 if return_observable else masks
|
| 178 |
+
_,grad=jax.lax.scan(backward,jnp.ones((len(dets),1<<backward_width),jnp.float32),
|
| 179 |
+
(probabilities,backward_masks,measured,history),reverse=True)
|
| 180 |
+
if return_observable:
|
| 181 |
+
return logz,grad.T,jnp.sum(final[:,1::2],axis=1)/jnp.maximum(jnp.sum(final,axis=1),1e-30)
|
| 182 |
+
return logz,grad.T
|
| 183 |
+
return marginals
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
def predict(plan, packed, decoder=None, batch=256):
|
| 187 |
+
import jax
|
| 188 |
+
decoder = decoder or make_decoder(int(plan['width']))
|
| 189 |
+
dets = np.unpackbits(packed, bitorder='little', axis=1, count=int(plan['num_detectors']))
|
| 190 |
+
args = [jax.device_put(plan[k]) for k in ['probabilities', 'masks', 'measured']]
|
| 191 |
+
result = []
|
| 192 |
+
for start in range(0, len(dets), batch):
|
| 193 |
+
ds = dets[start:start+batch]
|
| 194 |
+
ds = np.pad(ds, ((0, batch-len(ds)), (0, 0)))
|
| 195 |
+
result.append(np.asarray(decoder(ds, *args))[:min(batch, len(dets)-start)])
|
| 196 |
+
return np.concatenate(result)
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
if __name__ == '__main__':
|
| 200 |
+
import sys, time
|
| 201 |
+
from pathlib import Path
|
| 202 |
+
import jax
|
| 203 |
+
print(jax.devices(), flush=True)
|
| 204 |
+
path = Path(sys.argv[1])
|
| 205 |
+
dem = stim.DetectorErrorModel.from_file(path/'pij_from_even_for_odd.dem')
|
| 206 |
+
plan = make_plan(dem)
|
| 207 |
+
print({k: v.shape if v.ndim else int(v) for k, v in plan.items()}, flush=True)
|
| 208 |
+
a = np.load(path/'arrays.npz')
|
| 209 |
+
decoder = make_decoder(int(plan['width']))
|
| 210 |
+
for i in range(2):
|
| 211 |
+
t = time.time()
|
| 212 |
+
p = predict(plan, a['detectors'][:1024], decoder)
|
| 213 |
+
print({'seconds': time.time()-t, 'failure': np.mean((p>=.5)!=a['labels'][:len(p)]), 'min': p.min(), 'max': p.max()}, flush=True)
|
tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S040/training_sources/fresh_temporal1_full/learned_exact__data.py
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pathlib import Path
|
| 2 |
+
import json,sys
|
| 3 |
+
import numpy as np
|
| 4 |
+
import stim
|
| 5 |
+
sys.path.insert(0,'/workspace/research/exact_d3')
|
| 6 |
+
from exact import make_plan,parse_errors
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def _attach_arrays(item,root,splits):
|
| 10 |
+
row=item['row']
|
| 11 |
+
for split in splits:
|
| 12 |
+
a=np.load(root/split/row['arrays']);ds=np.unpackbits(a['detectors'],axis=1,count=row['num_detectors'],bitorder='little')
|
| 13 |
+
item[split+'_dets']=np.pad(ds,((0,0),(0,201-ds.shape[1])))
|
| 14 |
+
item[split+'_labels']=a['labels']
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def load_all(max_ops=3072,splits=('train','validation')):
|
| 18 |
+
assert set(splits)<=set(['train','validation'])
|
| 19 |
+
root=Path('/workspace/data')
|
| 20 |
+
rows=[r for r in json.loads((root/'train/manifest.json').read_text())['conditions'] if r['distance']==3]
|
| 21 |
+
groups=sorted({r['group'] for r in rows});result=[]
|
| 22 |
+
cache=Path('/workspace/research/learned_exact')/f'feature_cache-v2-{max_ops}'
|
| 23 |
+
cache.mkdir(exist_ok=True)
|
| 24 |
+
for row in rows:
|
| 25 |
+
cached=cache/f"{row['name']}-{row['noise_sha256'][:12]}-{row['circuit_sha256'][:12]}.npz"
|
| 26 |
+
if cached.exists():
|
| 27 |
+
item=dict(np.load(cached,allow_pickle=False));item['row']=row
|
| 28 |
+
_attach_arrays(item,root,splits);result.append(item);continue
|
| 29 |
+
dem=stim.DetectorErrorModel.from_file(root/'train'/row['noise']);plan=make_plan(dem)
|
| 30 |
+
assert int(plan['width'])<=10
|
| 31 |
+
count=len(plan['masks']);assert count<=max_ops,(row['name'],count)
|
| 32 |
+
coords=dem.get_detector_coordinates()
|
| 33 |
+
circuit=stim.Circuit.from_file(root/'train'/row['circuit'])
|
| 34 |
+
qubit_coords=circuit.get_final_qubit_coordinates()
|
| 35 |
+
first_measurement=next(ins for ins in circuit.flattened() if ins.name in ['M','MX','MR','MRX'])
|
| 36 |
+
spaces=sorted(tuple(qubit_coords[t.value][:2]) for t in first_measurement.targets_copy())
|
| 37 |
+
assert len(spaces)==8
|
| 38 |
+
idx={(int(c[2]),tuple(c[:2])):d for d,c in coords.items()}
|
| 39 |
+
errors=parse_errors(dem)
|
| 40 |
+
context=np.full((max_ops,40),200,np.int32)
|
| 41 |
+
static=np.zeros((max_ops,57),np.float32)
|
| 42 |
+
for op,source in enumerate(plan['source_indices']):
|
| 43 |
+
if source<0:continue
|
| 44 |
+
ds,logical,p=errors[source]
|
| 45 |
+
t=min(int(coords[d][2]) for d in ds) if ds else 0
|
| 46 |
+
for dt in range(-2,3):
|
| 47 |
+
for s,spatial in enumerate(spaces):context[op,(dt+2)*8+s]=idx.get((t+dt,spatial),200)
|
| 48 |
+
for d in ds:
|
| 49 |
+
c=coords[d];static[op,(int(c[2])-t+2)*8+spaces.index(tuple(c[:2]))]=1
|
| 50 |
+
static[op,40]=np.log(max(p,1e-7)/(1-max(p,1e-7)))/8
|
| 51 |
+
static[op,41]=logical;static[op,42]=len(ds)/4
|
| 52 |
+
static[op,43]=t/25;static[op,44]=row['rounds']/25
|
| 53 |
+
static[op,45]=t==0;static[op,46]=t>=row['rounds']-1
|
| 54 |
+
static[op,47+groups.index(row['group'])]=1
|
| 55 |
+
static[op,55]=row['basis']=='X';static[op,56]=1
|
| 56 |
+
masks=np.pad(plan['masks'],(0,max_ops-count))
|
| 57 |
+
measured=np.pad(plan['measured'],(0,max_ops-count),constant_values=-1)
|
| 58 |
+
p=np.pad(plan['probabilities'],(0,max_ops-count))
|
| 59 |
+
valid=((p>0)&(measured<0)).astype(np.float32)
|
| 60 |
+
logits=np.log(np.clip(p,1e-7,1-1e-7)/np.clip(1-p,1e-7,1-1e-7)).astype(np.float32)
|
| 61 |
+
item={'row':row,'context':context,'static':static,'masks':masks,'measured':measured,'base_logits':logits,'valid':valid}
|
| 62 |
+
grid=np.full((26,8),200,np.int32)
|
| 63 |
+
measurement_indices=np.full(201,208,np.int32)
|
| 64 |
+
for detector,c in coords.items():
|
| 65 |
+
t=int(c[2]);s=spaces.index(tuple(c[:2]));grid[t,s]=detector
|
| 66 |
+
measurement_indices[detector]=t*8+s
|
| 67 |
+
item['grid']=grid;item['measurement_indices']=measurement_indices
|
| 68 |
+
item['counts']=np.maximum((grid!=200).sum(axis=0),1).astype(np.float32)
|
| 69 |
+
temporary=cached.with_suffix('.tmp.npz')
|
| 70 |
+
np.savez(temporary,**{k:v for k,v in item.items() if k!='row'});temporary.replace(cached)
|
| 71 |
+
_attach_arrays(item,root,splits)
|
| 72 |
+
result.append(item)
|
| 73 |
+
return result
|
tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S040/training_sources/fresh_temporal1_full/learned_exact__fresh_temporal_initialization.py
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Fresh independent d3 trunk and temporal encoder; no checkpoint loading."""
|
| 2 |
+
import jax
|
| 3 |
+
import jax.numpy as jnp
|
| 4 |
+
from model import initialize as initialize_trunk
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def initialize(seed=20261300, encoder_seed=20261301, channels=32):
|
| 8 |
+
parameters = initialize_trunk(seed, 145, hidden=128)
|
| 9 |
+
keys = jax.random.split(jax.random.key(encoder_seed), 6)
|
| 10 |
+
parameters['w1'] = jnp.concatenate([parameters['w1'], jax.random.normal(keys[0], (channels, 128)) * .001], axis=0)
|
| 11 |
+
parameters['temporal_in'] = jax.random.normal(keys[1], (24, channels)) * jnp.sqrt(2 / 24)
|
| 12 |
+
parameters['temporal_bias'] = jnp.zeros(channels)
|
| 13 |
+
for i in range(4):
|
| 14 |
+
parameters[f'temporal_conv_{i}'] = jax.random.normal(keys[i + 2], (3, channels, channels)) * jnp.sqrt(1 / (3 * channels))
|
| 15 |
+
parameters[f'temporal_conv_bias_{i}'] = jnp.zeros(channels)
|
| 16 |
+
return parameters
|
tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S040/training_sources/fresh_temporal1_full/learned_exact__fresh_temporal_train.py
ADDED
|
@@ -0,0 +1,140 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
os.environ['OPENBLAS_NUM_THREADS']='1'
|
| 3 |
+
os.environ['OMP_NUM_THREADS']='1'
|
| 4 |
+
os.environ['XLA_PYTHON_CLIENT_PREALLOCATE']='false'
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
import argparse,json,time,sys,hashlib,shutil
|
| 7 |
+
import numpy as np
|
| 8 |
+
import jax,jax.numpy as jnp,optax
|
| 9 |
+
from temporal_model import probabilities
|
| 10 |
+
from fresh_temporal_initialization import initialize
|
| 11 |
+
from data import load_all
|
| 12 |
+
from gradient import make_loss_and_grad
|
| 13 |
+
sys.path.insert(0,'/workspace/research/exact_d3')
|
| 14 |
+
from exact import make_decoder
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def main():
|
| 18 |
+
parser=argparse.ArgumentParser();parser.add_argument('--steps',type=int,default=512);parser.add_argument('--batch',type=int,default=128)
|
| 19 |
+
parser.add_argument('--output',type=Path,required=True);parser.add_argument('--validation-shots',type=int,default=1024)
|
| 20 |
+
parser.add_argument('--init-weights',type=Path)
|
| 21 |
+
parser.add_argument('--initial-seed',type=int,default=20261300)
|
| 22 |
+
parser.add_argument('--encoder-seed',type=int,default=20261301)
|
| 23 |
+
parser.add_argument('--learning-rate',type=float,default=1e-3)
|
| 24 |
+
parser.add_argument('--eval-every',type=int,default=256)
|
| 25 |
+
parser.add_argument('--seed',type=int,default=20261025)
|
| 26 |
+
parser.add_argument('--validation-batch',type=int,default=1024)
|
| 27 |
+
parser.add_argument('--uniform-validation',action='store_true')
|
| 28 |
+
args=parser.parse_args();args.output.mkdir(parents=True,exist_ok=True)
|
| 29 |
+
run_config={k:str(v) if isinstance(v,Path) else v for k,v in vars(args).items()}
|
| 30 |
+
run_config['original_random_seed']=args.initial_seed
|
| 31 |
+
run_config['feature_mode']='events+measurements+global_density+temporal_convolutions'
|
| 32 |
+
run_config['temporal_seed']=args.encoder_seed
|
| 33 |
+
run_config['hidden_width']=128
|
| 34 |
+
run_config['logit_correction_bound']=4
|
| 35 |
+
run_config['starting_checkpoint_sha256']=hashlib.sha256(args.init_weights.read_bytes()).hexdigest() if args.init_weights else None
|
| 36 |
+
run_config['train_manifest_sha256']=hashlib.sha256(Path('/workspace/data/train/manifest.json').read_bytes()).hexdigest()
|
| 37 |
+
run_config['validation_manifest_sha256']=hashlib.sha256(Path('/workspace/data/validation/manifest.json').read_bytes()).hexdigest()
|
| 38 |
+
source_root=Path(__file__).resolve().parent;research=source_root.parent
|
| 39 |
+
snapshot=args.output/'training_source';snapshot.mkdir(exist_ok=True)
|
| 40 |
+
source_hashes={}
|
| 41 |
+
for source in [Path(__file__).resolve(),source_root/'temporal_model.py',source_root/'fresh_temporal_initialization.py',source_root/'model.py',source_root/'data.py',source_root/'gradient.py',research/'exact_d3/exact.py']:
|
| 42 |
+
name=str(source.relative_to(research)).replace('/','__')
|
| 43 |
+
shutil.copyfile(source,snapshot/name);source_hashes[name]=hashlib.sha256(source.read_bytes()).hexdigest()
|
| 44 |
+
run_config['training_source_sha256']=source_hashes
|
| 45 |
+
run_config['runtime_versions']={'jax':jax.__version__,'numpy':np.__version__,'optax':optax.__version__}
|
| 46 |
+
(args.output/'run_config.json').write_text(json.dumps(run_config,indent=2)+'\n')
|
| 47 |
+
t=time.time();dataset=load_all();print(json.dumps({'loaded':len(dataset),'seconds':time.time()-t}),flush=True)
|
| 48 |
+
seen=[np.zeros(len(item['train_labels']),bool) for item in dataset]
|
| 49 |
+
parameters=initialize(args.initial_seed,args.encoder_seed)
|
| 50 |
+
if args.init_weights:
|
| 51 |
+
parent_config=json.loads((args.init_weights.parent/'run_config.json').read_text())
|
| 52 |
+
assert parent_config['initial_seed']==args.initial_seed and parent_config['encoder_seed']==args.encoder_seed
|
| 53 |
+
parameters={k:jnp.asarray(v) for k,v in dict(np.load(args.init_weights,allow_pickle=False)).items()}
|
| 54 |
+
optimizer=optax.chain(optax.clip_by_global_norm(1.),optax.adamw(learning_rate=args.learning_rate,weight_decay=1e-4))
|
| 55 |
+
state=optimizer.init(parameters);exact_gradient=make_loss_and_grad(10)
|
| 56 |
+
rng=np.random.default_rng(args.seed);optimizer_restored=False;rng_restored=False
|
| 57 |
+
if args.init_weights:
|
| 58 |
+
optfile=args.init_weights.with_name(args.init_weights.name.replace('weights-','optimizer-'))
|
| 59 |
+
if optfile.exists():
|
| 60 |
+
leaves,treedef=jax.tree_util.tree_flatten(state);saved=np.load(optfile,allow_pickle=False)
|
| 61 |
+
assert len(leaves)==len(saved.files)
|
| 62 |
+
state=jax.tree_util.tree_unflatten(treedef,[jnp.asarray(saved[f'arr_{i}']) for i in range(len(leaves))]);optimizer_restored=True
|
| 63 |
+
rngfile=args.init_weights.with_name(args.init_weights.name.replace('weights-','rng-')).with_suffix('.json')
|
| 64 |
+
if rngfile.exists():rng.bit_generator.state=json.loads(rngfile.read_text());rng_restored=True
|
| 65 |
+
@jax.jit
|
| 66 |
+
def update(parameters,state,ds,ys,context,static,base_logits,valid,masks,measured,grid,measurement_indices,counts):
|
| 67 |
+
p,pullback=jax.vjp(lambda w:probabilities(w,ds,context,static,base_logits,valid,grid,measurement_indices,counts),parameters)
|
| 68 |
+
loss,pred,g=exact_gradient(ds,ys,p,masks,measured)
|
| 69 |
+
grads=pullback(g/len(ds))[0]
|
| 70 |
+
changes,state=optimizer.update(grads,state,parameters)
|
| 71 |
+
parameters=optax.apply_updates(parameters,changes)
|
| 72 |
+
return parameters,state,jnp.mean(loss),jnp.mean((pred>=.5)!=ys),optax.global_norm(grads)
|
| 73 |
+
exact_decode=make_decoder(10)
|
| 74 |
+
@jax.jit
|
| 75 |
+
def infer(parameters,ds,context,static,base_logits,valid,masks,measured,grid,measurement_indices,counts):
|
| 76 |
+
p=probabilities(parameters,ds,context,static,base_logits,valid,grid,measurement_indices,counts)
|
| 77 |
+
return exact_decode(ds,p,masks,measured)
|
| 78 |
+
def evaluate(step):
|
| 79 |
+
results=[];start=time.time()
|
| 80 |
+
for item in dataset:
|
| 81 |
+
n=min(args.validation_shots,len(item['validation_labels']));pred=[]
|
| 82 |
+
selected=np.random.default_rng(20261028).choice(len(item['validation_labels']),n,replace=False) if args.uniform_validation else np.arange(n)
|
| 83 |
+
vd=item['validation_dets'][selected];vy=item['validation_labels'][selected]
|
| 84 |
+
for begin in range(0,n,args.validation_batch):
|
| 85 |
+
ds=vd[begin:begin+args.validation_batch];size=len(ds)
|
| 86 |
+
ds=np.pad(ds,((0,args.validation_batch-size),(0,0)))
|
| 87 |
+
p=np.asarray(infer(parameters,ds,*[item[k] for k in ['context','static','base_logits','valid','masks','measured','grid','measurement_indices','counts']]))[:size]
|
| 88 |
+
pred.append(p)
|
| 89 |
+
p=np.concatenate(pred)
|
| 90 |
+
pp=np.clip(p.astype(np.float64),1e-7,1-1e-7);yy=vy.astype(np.float64)
|
| 91 |
+
results.append({'condition':item['row']['name'],'failure':float(np.mean((p>=.5)!=vy)),
|
| 92 |
+
'negative_log_likelihood':float(np.mean(-yy*np.log(pp)-(1-yy)*np.log1p(-pp))),
|
| 93 |
+
'brier':float(np.mean((p-vy)**2))})
|
| 94 |
+
result={'step':step,'validation_failure':float(np.mean([r['failure'] for r in results])),
|
| 95 |
+
'negative_log_likelihood':float(np.mean([r['negative_log_likelihood'] for r in results])),
|
| 96 |
+
'seconds':time.time()-start,'conditions':results}
|
| 97 |
+
(args.output/f'validation-{step}.json').write_text(json.dumps(result,indent=2)+'\n')
|
| 98 |
+
np.savez(args.output/f'weights-{step}.npz',**{k:np.asarray(v) for k,v in parameters.items()})
|
| 99 |
+
leaves,_=jax.tree_util.tree_flatten(state)
|
| 100 |
+
np.savez(args.output/f'optimizer-{step}.npz',**{f'arr_{i}':np.asarray(v) for i,v in enumerate(leaves)})
|
| 101 |
+
(args.output/f'rng-{step}.json').write_text(json.dumps(rng.bit_generator.state)+'\n')
|
| 102 |
+
(args.output/f'checkpoint-{step}.json').write_text(json.dumps({'step':step,'new_training_shots':step*args.batch,
|
| 103 |
+
'unique_training_rows_seen_in_this_phase':sum(int(x.sum()) for x in seen),
|
| 104 |
+
'weights':f'weights-{step}.npz','weights_sha256':hashlib.sha256((args.output/f'weights-{step}.npz').read_bytes()).hexdigest(),
|
| 105 |
+
'validation':f'validation-{step}.json','complete':True},indent=2)+'\n')
|
| 106 |
+
print(json.dumps({k:v for k,v in result.items() if k!='conditions'}),flush=True)
|
| 107 |
+
evaluate(0)
|
| 108 |
+
records=[]
|
| 109 |
+
for step in range(1,args.steps+1):
|
| 110 |
+
condition_index=int(rng.integers(len(dataset)));item=dataset[condition_index]
|
| 111 |
+
ix=rng.integers(len(item['train_labels']),size=args.batch);seen[condition_index][ix]=True
|
| 112 |
+
parameters,state,loss,error,norm=update(parameters,state,item['train_dets'][ix],item['train_labels'][ix],
|
| 113 |
+
*[item[k] for k in ['context','static','base_logits','valid','masks','measured','grid','measurement_indices','counts']])
|
| 114 |
+
if step%16==0 or step==1:
|
| 115 |
+
record={'step':step,'loss':float(loss),'error':float(error),'gradient_norm':float(norm),'elapsed':time.time()-t}
|
| 116 |
+
records.append(record);print(json.dumps(record),flush=True)
|
| 117 |
+
if not np.isfinite(record['loss']):raise ValueError('Nonfinite training loss')
|
| 118 |
+
if step%args.eval_every==0 or step==args.steps:evaluate(step)
|
| 119 |
+
provenance={'initialization':('Continue from this session\'s trained checkpoint' if args.init_weights else 'Entire rich trunk and temporal encoder initialized randomly in this session; no learned checkpoint loaded'),
|
| 120 |
+
'original_initialization':f'Fresh128-unit rich trunk NumPy seed{args.initial_seed}: hidden weights Normal(0,1/sqrt(fan-in)),output Normal(0,.001),zero biases. Fresh32-channel temporal encoder JAX seed{args.encoder_seed}: variance-scaled normal input/convolution weights,zero biases; appendedinput rows Normal(0,.001).',
|
| 121 |
+
'initial_seed':args.initial_seed,'encoder_seed':args.encoder_seed,
|
| 122 |
+
'architecture':'Rich 128-unit MLP plus 32-channel temporal encoder: four residual kernel3 convolutions with dilations1/2/4/8 and channel normalization. Receptive field31 rounds. Encoder sees events, measurements and presence masks. Per-edge 177 input features. Output4*tanh.',
|
| 123 |
+
'training':'Uniform condition sampling from all 104 d3 conditions; batch drawn from the supplied training split only',
|
| 124 |
+
'training_source_sha256':source_hashes,'runtime_versions':run_config['runtime_versions'],
|
| 125 |
+
'eligible_training_shots':sum(len(item['train_labels']) for item in dataset),
|
| 126 |
+
'unique_training_rows_seen_in_this_phase':sum(int(x.sum()) for x in seen),
|
| 127 |
+
'unique_rows_by_condition':{item['row']['name']:int(x.sum()) for item,x in zip(dataset,seen)},
|
| 128 |
+
'steps':args.steps,'batch_size':args.batch,'optimizer':'AdamW, weight decay 1e-4, global gradient norm clip 1',
|
| 129 |
+
'learning_rate':args.learning_rate,'sampling_seed':args.seed,'optimizer_restored':optimizer_restored,'rng_restored':rng_restored,
|
| 130 |
+
'sampling_state_source':str(rngfile) if rng_restored else f'Fresh NumPy default_rng seed {args.seed}',
|
| 131 |
+
'session_trained_starting_checkpoint':str(args.init_weights) if args.init_weights else None,
|
| 132 |
+
'starting_checkpoint_sha256':hashlib.sha256(args.init_weights.read_bytes()).hexdigest() if args.init_weights else None,
|
| 133 |
+
'starting_training_provenance':json.loads((args.init_weights.parent/'provenance.json').read_text()) if args.init_weights else None,
|
| 134 |
+
'loss':'Binary conditional logical likelihood computed by exact frontier elimination',
|
| 135 |
+
'validation_shots_per_condition':args.validation_shots,'uniform_validation':args.uniform_validation,
|
| 136 |
+
'uniform_validation_seed':20261028 if args.uniform_validation else None,'test_data_used':False,'log':records}
|
| 137 |
+
(args.output/'provenance.json').write_text(json.dumps(provenance,indent=2)+'\n')
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
if __name__=='__main__':main()
|
tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S040/training_sources/fresh_temporal1_full/learned_exact__gradient.py
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Differentiable conditional logical likelihood through exact DEM elimination."""
|
| 2 |
+
import jax
|
| 3 |
+
import jax.numpy as jnp
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
def make_loss_and_grad(width):
|
| 7 |
+
indices=jnp.arange(1<<width,dtype=jnp.int32)
|
| 8 |
+
@jax.jit
|
| 9 |
+
def evaluate(dets,labels,probabilities,masks,measured):
|
| 10 |
+
# Per-shot error probabilities have shape [operations,batch].
|
| 11 |
+
f=jnp.zeros((len(dets),1<<width),jnp.float32).at[:,0].set(1)
|
| 12 |
+
def forward(f,args):
|
| 13 |
+
p,mask,d=args
|
| 14 |
+
def error(f):
|
| 15 |
+
return (1-p[:,None])*f+p[:,None]*f[:,indices^mask],jnp.ones(len(dets))
|
| 16 |
+
def project(f):
|
| 17 |
+
dst=(indices[None,:]&~mask)|(dets[:,d,None].astype(jnp.int32)*mask)
|
| 18 |
+
g=jnp.take_along_axis(f,dst,axis=1)*((indices&mask)==0)
|
| 19 |
+
norm=jnp.maximum(g.sum(axis=1),1e-30)
|
| 20 |
+
return g/norm[:,None],norm
|
| 21 |
+
out,norm=jax.lax.cond(d<0,error,project,f)
|
| 22 |
+
return out,(f,norm)
|
| 23 |
+
f,(history,norms)=jax.lax.scan(forward,f,(probabilities,masks,measured))
|
| 24 |
+
indicator=((indices[None,:]&1)==labels[:,None])
|
| 25 |
+
correct=jnp.maximum(jnp.sum(f*indicator,axis=1),1e-10)
|
| 26 |
+
predicted=jnp.sum(f[:,1::2],axis=1)
|
| 27 |
+
initial=1-indicator/correct[:,None]
|
| 28 |
+
def backward(b,args):
|
| 29 |
+
p,mask,d,old,norm=args
|
| 30 |
+
def error(b):
|
| 31 |
+
flipped=b[:,indices^mask]
|
| 32 |
+
grad=jnp.sum(old*(flipped-b),axis=1)
|
| 33 |
+
return (1-p[:,None])*b+p[:,None]*flipped,grad
|
| 34 |
+
def project(b):
|
| 35 |
+
obs=((indices[None,:]&mask)==dets[:,d,None].astype(jnp.int32)*mask)
|
| 36 |
+
values=b[:,indices&~mask]
|
| 37 |
+
mean=jnp.sum(old*obs*values,axis=1)/norm
|
| 38 |
+
prior=(values-mean[:,None])*obs/norm[:,None]
|
| 39 |
+
return prior,jnp.zeros(len(dets))
|
| 40 |
+
return jax.lax.cond(d<0,error,project,b)
|
| 41 |
+
_,grad=jax.lax.scan(backward,initial,(probabilities,masks,measured,history,norms),reverse=True)
|
| 42 |
+
return -jnp.log(correct),predicted,grad
|
| 43 |
+
return evaluate
|
tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S040/training_sources/fresh_temporal1_full/learned_exact__model.py
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""A small contextual network reweights hyperedges before exact decoding."""
|
| 2 |
+
import numpy as np
|
| 3 |
+
import jax
|
| 4 |
+
import jax.numpy as jnp
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def initialize(seed,input_width,hidden=32):
|
| 8 |
+
rng=np.random.default_rng(seed)
|
| 9 |
+
return {'w1':jnp.asarray(rng.normal(0,1/np.sqrt(input_width),(input_width,hidden)),jnp.float32),
|
| 10 |
+
'b1':jnp.zeros(hidden),'w2':jnp.asarray(rng.normal(0,1/np.sqrt(hidden),(hidden,hidden)),jnp.float32),
|
| 11 |
+
'b2':jnp.zeros(hidden),'w3':jnp.asarray(rng.normal(0,.001,(hidden,1)),jnp.float32),'b3':jnp.zeros(1)}
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def probabilities(parameters,dets,context_indices,static,base_logits,valid):
|
| 15 |
+
observed=dets[:,context_indices].astype(jnp.float32)
|
| 16 |
+
features=jnp.concatenate([observed,jnp.broadcast_to(static[None,:,:],(len(dets),*static.shape))],axis=-1)
|
| 17 |
+
hidden=jax.nn.silu(features@parameters['w1']+parameters['b1'])
|
| 18 |
+
hidden=jax.nn.silu(hidden@parameters['w2']+parameters['b2'])
|
| 19 |
+
delta=2*jnp.tanh((hidden@parameters['w3']+parameters['b3'])[...,0])
|
| 20 |
+
p=jax.nn.sigmoid(base_logits[None,:]+delta)*valid[None,:]
|
| 21 |
+
return p.T
|
tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S040/training_sources/fresh_temporal1_full/learned_exact__temporal_model.py
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Long temporal context for contextual exact d3 decoding."""
|
| 2 |
+
import numpy as np
|
| 3 |
+
import jax
|
| 4 |
+
import jax.numpy as jnp
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def initialize_from_rich(path,seed=20261104,channels=32):
|
| 8 |
+
parameters={k:jnp.asarray(v) for k,v in dict(np.load(path,allow_pickle=False)).items()}
|
| 9 |
+
keys=jax.random.split(jax.random.key(seed),6)
|
| 10 |
+
parameters['w1']=jnp.concatenate([parameters['w1'],jax.random.normal(keys[0],(channels,parameters['w1'].shape[1]))*.001],axis=0)
|
| 11 |
+
parameters['temporal_in']=jax.random.normal(keys[1],(24,channels))*jnp.sqrt(2/24)
|
| 12 |
+
parameters['temporal_bias']=jnp.zeros(channels)
|
| 13 |
+
for i in range(4):
|
| 14 |
+
parameters[f'temporal_conv_{i}']=jax.random.normal(keys[i+2],(3,channels,channels))*jnp.sqrt(1/(3*channels))
|
| 15 |
+
parameters[f'temporal_conv_bias_{i}']=jnp.zeros(channels)
|
| 16 |
+
return parameters
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def probabilities(parameters,dets,context_indices,static,base_logits,valid,grid,measurement_indices,counts):
|
| 20 |
+
event_grid=dets[:,grid]
|
| 21 |
+
measurement_grid=(jnp.cumsum(event_grid.astype(jnp.int32),axis=1)&1).astype(jnp.float32)
|
| 22 |
+
observed=(grid!=200).astype(jnp.float32)
|
| 23 |
+
frames=jnp.concatenate([event_grid.astype(jnp.float32),measurement_grid*observed[None,:,:],
|
| 24 |
+
jnp.broadcast_to(observed[None,:,:],event_grid.shape)],axis=-1)
|
| 25 |
+
temporal=jax.nn.silu(frames@parameters['temporal_in']+parameters['temporal_bias'])
|
| 26 |
+
for i,dilation in enumerate([1,2,4,8]):
|
| 27 |
+
mean=jnp.mean(temporal,axis=-1,keepdims=True)
|
| 28 |
+
normalized=(temporal-mean)*jax.lax.rsqrt(jnp.mean((temporal-mean)**2,axis=-1,keepdims=True)+1e-5)
|
| 29 |
+
value=jax.lax.conv_general_dilated(normalized,parameters[f'temporal_conv_{i}'],(1,),padding='SAME',
|
| 30 |
+
rhs_dilation=(dilation,),dimension_numbers=('NWC','WIO','NWC'))
|
| 31 |
+
temporal=temporal+jax.nn.silu(value+parameters[f'temporal_conv_bias_{i}'])
|
| 32 |
+
times=jnp.clip(jnp.rint(static[:,43]*25).astype(jnp.int32),0,25)
|
| 33 |
+
temporal_context=temporal[:,times,:]
|
| 34 |
+
measured=jnp.pad(measurement_grid.reshape(len(dets),208),((0,0),(0,1)))
|
| 35 |
+
events=dets[:,context_indices].astype(jnp.float32)
|
| 36 |
+
measurements=measured[:,measurement_indices[context_indices]].astype(jnp.float32)
|
| 37 |
+
density=jnp.sum(event_grid,axis=1)/counts[None,:]
|
| 38 |
+
features=jnp.concatenate([events,measurements,
|
| 39 |
+
jnp.broadcast_to(density[:,None,:],(len(dets),len(context_indices),8)),
|
| 40 |
+
jnp.broadcast_to(static[None,:,:],(len(dets),*static.shape)),temporal_context],axis=-1)
|
| 41 |
+
h=jax.nn.silu(features@parameters['w1']+parameters['b1'])
|
| 42 |
+
h=jax.nn.silu(h@parameters['w2']+parameters['b2'])
|
| 43 |
+
delta=4*jnp.tanh((h@parameters['w3']+parameters['b3'])[...,0])
|
| 44 |
+
return (jax.nn.sigmoid(base_logits[None,:]+delta)*valid[None,:]).T
|
tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S040/training_sources/fresh_temporal1_swa/exact_d3__exact.py
ADDED
|
@@ -0,0 +1,213 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Exact detector-error-model contraction by bounded-frontier elimination."""
|
| 2 |
+
import collections
|
| 3 |
+
import numpy as np
|
| 4 |
+
import stim
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def parse_errors(dem):
|
| 8 |
+
errors = []
|
| 9 |
+
for ins in dem.flattened():
|
| 10 |
+
if ins.type != 'error':
|
| 11 |
+
continue
|
| 12 |
+
ds, logical = set(), 0
|
| 13 |
+
for t in ins.targets_copy():
|
| 14 |
+
if t.is_relative_detector_id():
|
| 15 |
+
ds.symmetric_difference_update([t.val])
|
| 16 |
+
elif t.is_logical_observable_id():
|
| 17 |
+
assert t.val == 0
|
| 18 |
+
logical ^= 1
|
| 19 |
+
errors.append((ds, logical, ins.args_copy()[0]))
|
| 20 |
+
return errors
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def elimination_order(dem, errors):
|
| 24 |
+
blocks = collections.defaultdict(list)
|
| 25 |
+
for d, c in dem.get_detector_coordinates().items():
|
| 26 |
+
blocks[c[-1]].append(d)
|
| 27 |
+
pending = [ds for ds, _, _ in errors if ds]
|
| 28 |
+
active, used, order = set(), set(), []
|
| 29 |
+
for _, block in sorted(blocks.items()):
|
| 30 |
+
remain = set(block)
|
| 31 |
+
while remain:
|
| 32 |
+
def score(d):
|
| 33 |
+
new = set().union(*(e for e in pending if d in e)) - used
|
| 34 |
+
return len(active | new), -sum(d in e for e in pending), d
|
| 35 |
+
d = min(remain, key=score)
|
| 36 |
+
related = [e for e in pending if d in e]
|
| 37 |
+
active |= set().union(*related) - used
|
| 38 |
+
active.discard(d)
|
| 39 |
+
pending = [e for e in pending if d not in e]
|
| 40 |
+
used.add(d)
|
| 41 |
+
remain.remove(d)
|
| 42 |
+
order.append(d)
|
| 43 |
+
assert sorted(order) == list(range(dem.num_detectors))
|
| 44 |
+
return order
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def make_plan(dem):
|
| 48 |
+
errors = parse_errors(dem)
|
| 49 |
+
order = elimination_order(dem, errors)
|
| 50 |
+
rank = {d: i for i, d in enumerate(order)}
|
| 51 |
+
groups = collections.defaultdict(list)
|
| 52 |
+
for source_index, (ds, logical, p) in enumerate(errors):
|
| 53 |
+
first = min(ds, key=rank.get) if ds else order[0]
|
| 54 |
+
groups[first].append((ds, logical, p, source_index))
|
| 55 |
+
slots, probabilities, masks, measured, source_indices = {}, [], [], [], []
|
| 56 |
+
width = 1
|
| 57 |
+
for d in order:
|
| 58 |
+
related = groups[d]
|
| 59 |
+
needed = set().union(*(ds for ds, _, _, _ in related)) | {d}
|
| 60 |
+
for node in sorted(needed):
|
| 61 |
+
if node not in slots:
|
| 62 |
+
free = next(i for i in range(1, 64) if i not in slots.values())
|
| 63 |
+
slots[node] = free
|
| 64 |
+
width = max(width, free+1)
|
| 65 |
+
for ds, logical, p, source_index in related:
|
| 66 |
+
mask = logical
|
| 67 |
+
for node in ds:
|
| 68 |
+
mask ^= 1 << slots[node]
|
| 69 |
+
probabilities.append(p)
|
| 70 |
+
masks.append(mask)
|
| 71 |
+
measured.append(-1)
|
| 72 |
+
source_indices.append(source_index)
|
| 73 |
+
probabilities.append(0)
|
| 74 |
+
masks.append(1 << slots.pop(d))
|
| 75 |
+
measured.append(d)
|
| 76 |
+
source_indices.append(-1)
|
| 77 |
+
assert not slots
|
| 78 |
+
return {'probabilities': np.array(probabilities, np.float32),
|
| 79 |
+
'masks': np.array(masks, np.int32), 'measured': np.array(measured, np.int32),
|
| 80 |
+
'width': np.array(width, np.int32), 'num_detectors': np.array(dem.num_detectors, np.int32),
|
| 81 |
+
'source_indices': np.array(source_indices, np.int32),
|
| 82 |
+
'order': np.array(order, np.int32)}
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def make_decoder(width):
|
| 86 |
+
import jax
|
| 87 |
+
import jax.numpy as jnp
|
| 88 |
+
indices = jnp.arange(1 << width, dtype=jnp.int32)
|
| 89 |
+
@jax.jit
|
| 90 |
+
def decode(dets, probabilities, masks, measured):
|
| 91 |
+
f = jnp.zeros((dets.shape[0], 1 << width), jnp.float32).at[:, 0].set(1)
|
| 92 |
+
def step(f, args):
|
| 93 |
+
p, mask, d = args
|
| 94 |
+
def error(f):
|
| 95 |
+
prob = p[:, None] if p.ndim else p
|
| 96 |
+
return (1-prob)*f + prob*f[:, indices ^ mask]
|
| 97 |
+
def project(f):
|
| 98 |
+
obs = dets[:, d].astype(jnp.int32)
|
| 99 |
+
dst = (indices[None, :] & ~mask) | (obs[:, None]*mask)
|
| 100 |
+
g = jnp.take_along_axis(f, dst, axis=1) * ((indices & mask)==0)
|
| 101 |
+
return g / jnp.maximum(jnp.sum(g, axis=1, keepdims=True), 1e-30)
|
| 102 |
+
return jax.lax.cond(d < 0, error, project, f), None
|
| 103 |
+
f, _ = jax.lax.scan(step, f, (probabilities, masks, measured))
|
| 104 |
+
return jnp.sum(f[:, 1::2], axis=1) / jnp.maximum(jnp.sum(f, axis=1), 1e-30)
|
| 105 |
+
return decode
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def make_marginals(width):
|
| 109 |
+
"""Per-shot derivatives of log syndrome probability give all error marginals."""
|
| 110 |
+
import jax
|
| 111 |
+
import jax.numpy as jnp
|
| 112 |
+
indices = jnp.arange(1 << width, dtype=jnp.int32)
|
| 113 |
+
def log_partition(dets, probabilities, masks, measured):
|
| 114 |
+
f = jnp.zeros(1 << width, jnp.float32).at[0].set(1)
|
| 115 |
+
def step(carry, args):
|
| 116 |
+
f, logz = carry
|
| 117 |
+
p, mask, d = args
|
| 118 |
+
def error(carry):
|
| 119 |
+
f, logz = carry
|
| 120 |
+
return ((1-p)*f + p*f[indices ^ mask], logz)
|
| 121 |
+
def project(carry):
|
| 122 |
+
f, logz = carry
|
| 123 |
+
dst = (indices & ~mask) | (dets[d].astype(jnp.int32)*mask)
|
| 124 |
+
g = f[dst] * ((indices & mask)==0)
|
| 125 |
+
norm = jnp.maximum(jnp.sum(g), 1e-30)
|
| 126 |
+
return g/norm, logz+jnp.log(norm)
|
| 127 |
+
return jax.lax.cond(d<0, error, project, carry), None
|
| 128 |
+
(_, logz), _ = jax.lax.scan(jax.checkpoint(step), (f, jnp.float32(0)), (probabilities, masks, measured))
|
| 129 |
+
return logz
|
| 130 |
+
return jax.jit(jax.vmap(jax.value_and_grad(log_partition, argnums=1), in_axes=(0,None,None,None)))
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
def make_marginals_fb(width, return_observable=False):
|
| 134 |
+
"""Forward/backward contraction without generic gather-gradient scatter."""
|
| 135 |
+
import jax
|
| 136 |
+
import jax.numpy as jnp
|
| 137 |
+
indices = jnp.arange(1 << width, dtype=jnp.int32)
|
| 138 |
+
# The syndrome likelihood marginalizes the unobserved logical bit. Keep
|
| 139 |
+
# that bit in the forward state for its output, but omit it from histories
|
| 140 |
+
# and backward messages, halving the largest buffers.
|
| 141 |
+
backward_width=width-1 if return_observable else width
|
| 142 |
+
backward_indices=jnp.arange(1 << backward_width,dtype=jnp.int32)
|
| 143 |
+
@jax.jit
|
| 144 |
+
def marginals(dets, probabilities, masks, measured):
|
| 145 |
+
f=jnp.zeros((dets.shape[0],1<<width),jnp.float32).at[:,0].set(1)
|
| 146 |
+
def forward(carry,args):
|
| 147 |
+
f,logz=carry
|
| 148 |
+
p,mask,d=args
|
| 149 |
+
def error(carry):
|
| 150 |
+
f,logz=carry
|
| 151 |
+
prob=p[:,None] if p.ndim else p
|
| 152 |
+
return ((1-prob)*f+prob*f[:,indices^mask],logz)
|
| 153 |
+
def project(carry):
|
| 154 |
+
f,logz=carry
|
| 155 |
+
dst=(indices[None,:]&~mask)|(dets[:,d,None].astype(jnp.int32)*mask)
|
| 156 |
+
g=jnp.take_along_axis(f,dst,axis=1)*((indices&mask)==0)
|
| 157 |
+
norm=jnp.maximum(g.sum(axis=1),1e-30)
|
| 158 |
+
return g/norm[:,None],logz+jnp.log(norm)
|
| 159 |
+
out=jax.lax.cond(d<0,error,project,carry)
|
| 160 |
+
return out,(f[:,::2]+f[:,1::2]) if return_observable else f
|
| 161 |
+
(final,logz),history=jax.lax.scan(forward,(f,jnp.zeros(len(dets))),(probabilities,masks,measured))
|
| 162 |
+
def backward(b,args):
|
| 163 |
+
p,mask,d,f=args
|
| 164 |
+
def error(b):
|
| 165 |
+
flipped=b[:,backward_indices^mask]
|
| 166 |
+
prob=p[:,None] if p.ndim else p
|
| 167 |
+
prior=(1-prob)*b+prob*flipped
|
| 168 |
+
norm=jnp.maximum(jnp.sum(f*prior,axis=1),1e-30)
|
| 169 |
+
q=p*jnp.sum(f*flipped,axis=1)/norm
|
| 170 |
+
grad=(q-p)/jnp.maximum(p*(1-p),1e-20)
|
| 171 |
+
return prior/norm[:,None],grad
|
| 172 |
+
def project(b):
|
| 173 |
+
prior=b[:,backward_indices&~mask]*((backward_indices[None,:]&mask)==(dets[:,d,None].astype(jnp.int32)*mask))
|
| 174 |
+
norm=jnp.maximum(jnp.sum(f*prior,axis=1),1e-30)
|
| 175 |
+
return prior/norm[:,None],jnp.zeros(len(dets))
|
| 176 |
+
return jax.lax.cond(d<0,error,project,b)
|
| 177 |
+
backward_masks=masks>>1 if return_observable else masks
|
| 178 |
+
_,grad=jax.lax.scan(backward,jnp.ones((len(dets),1<<backward_width),jnp.float32),
|
| 179 |
+
(probabilities,backward_masks,measured,history),reverse=True)
|
| 180 |
+
if return_observable:
|
| 181 |
+
return logz,grad.T,jnp.sum(final[:,1::2],axis=1)/jnp.maximum(jnp.sum(final,axis=1),1e-30)
|
| 182 |
+
return logz,grad.T
|
| 183 |
+
return marginals
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
def predict(plan, packed, decoder=None, batch=256):
|
| 187 |
+
import jax
|
| 188 |
+
decoder = decoder or make_decoder(int(plan['width']))
|
| 189 |
+
dets = np.unpackbits(packed, bitorder='little', axis=1, count=int(plan['num_detectors']))
|
| 190 |
+
args = [jax.device_put(plan[k]) for k in ['probabilities', 'masks', 'measured']]
|
| 191 |
+
result = []
|
| 192 |
+
for start in range(0, len(dets), batch):
|
| 193 |
+
ds = dets[start:start+batch]
|
| 194 |
+
ds = np.pad(ds, ((0, batch-len(ds)), (0, 0)))
|
| 195 |
+
result.append(np.asarray(decoder(ds, *args))[:min(batch, len(dets)-start)])
|
| 196 |
+
return np.concatenate(result)
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
if __name__ == '__main__':
|
| 200 |
+
import sys, time
|
| 201 |
+
from pathlib import Path
|
| 202 |
+
import jax
|
| 203 |
+
print(jax.devices(), flush=True)
|
| 204 |
+
path = Path(sys.argv[1])
|
| 205 |
+
dem = stim.DetectorErrorModel.from_file(path/'pij_from_even_for_odd.dem')
|
| 206 |
+
plan = make_plan(dem)
|
| 207 |
+
print({k: v.shape if v.ndim else int(v) for k, v in plan.items()}, flush=True)
|
| 208 |
+
a = np.load(path/'arrays.npz')
|
| 209 |
+
decoder = make_decoder(int(plan['width']))
|
| 210 |
+
for i in range(2):
|
| 211 |
+
t = time.time()
|
| 212 |
+
p = predict(plan, a['detectors'][:1024], decoder)
|
| 213 |
+
print({'seconds': time.time()-t, 'failure': np.mean((p>=.5)!=a['labels'][:len(p)]), 'min': p.min(), 'max': p.max()}, flush=True)
|
tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S040/training_sources/fresh_temporal1_swa/learned_exact__average_fresh_temporal.py
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Predefined parameter averages of the d3 temporal continuation checkpoints."""
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
import hashlib,json,shutil
|
| 4 |
+
import numpy as np
|
| 5 |
+
root=Path(__file__).resolve().parent;source=root/'fresh_temporal1_full';out=root/'fresh_temporal1_swa'
|
| 6 |
+
out.mkdir()
|
| 7 |
+
parent=json.loads((source/'provenance.json').read_text())
|
| 8 |
+
specifications={'mean2':[4096,6144],'mean3':[2048,4096,6144]}
|
| 9 |
+
records={}
|
| 10 |
+
for label,steps in specifications.items():
|
| 11 |
+
checkpoints=[dict(np.load(source/f'weights-{step}.npz',allow_pickle=False)) for step in steps]
|
| 12 |
+
assert all(set(w)==set(checkpoints[0]) for w in checkpoints)
|
| 13 |
+
weights={key:np.mean(np.stack([w[key].astype(np.float64) for w in checkpoints]),axis=0).astype(np.float32)
|
| 14 |
+
for key in checkpoints[0]}
|
| 15 |
+
assert all(np.isfinite(value).all() for value in weights.values())
|
| 16 |
+
assert all(all(w[k].shape==checkpoints[0][k].shape for k in weights) for w in checkpoints)
|
| 17 |
+
path=out/f'weights-{label}.npz';np.savez(path,**weights)
|
| 18 |
+
record={'checkpoint_label':label,'kind':'uniform_parameter_average','optimizer_updates_in_derived_run':0,
|
| 19 |
+
'source_optimizer_steps':steps,'source_training_run':'fresh_temporal1_full',
|
| 20 |
+
'source_weights_sha256':{str(step):hashlib.sha256((source/f'weights-{step}.npz').read_bytes()).hexdigest() for step in steps},
|
| 21 |
+
'source_checkpoint_records':{str(step):json.loads((source/f'checkpoint-{step}.json').read_text()) for step in steps},
|
| 22 |
+
'weights_sha256':hashlib.sha256(path.read_bytes()).hexdigest(),'complete':True}
|
| 23 |
+
records[label]=record;(out/f'checkpoint-{label}.json').write_text(json.dumps(record,indent=2)+'\n')
|
| 24 |
+
shutil.copytree(source/'training_source',out/'training_source')
|
| 25 |
+
shutil.copyfile(Path(__file__),out/'training_source/learned_exact__average_fresh_temporal.py')
|
| 26 |
+
provenance={'initialization':'Uniform averages of the same session-trained temporal trajectory; no external weights',
|
| 27 |
+
'optimizer_updates_in_derived_run':0,'source_training_provenance':parent,'derived_checkpoints':records,'declared_plan':json.loads((root/'fresh_temporal1_swa_plan.json').read_text()),
|
| 28 |
+
'selection':'Predefined last-two and last-three noninitial fresh_temporal1_full checkpoint means, declared before later checkpoints completed; all104conditions evaluated before group selection',
|
| 29 |
+
'test_data_used':False,'derivation_source_sha256':hashlib.sha256(Path(__file__).read_bytes()).hexdigest()}
|
| 30 |
+
(out/'provenance.json').write_text(json.dumps(provenance,indent=2)+'\n')
|
| 31 |
+
print(json.dumps({'run':str(out),'labels':list(records),'new_optimizer_updates':0}),flush=True)
|
tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S040/training_sources/fresh_temporal1_swa/learned_exact__data.py
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pathlib import Path
|
| 2 |
+
import json,sys
|
| 3 |
+
import numpy as np
|
| 4 |
+
import stim
|
| 5 |
+
sys.path.insert(0,'/workspace/research/exact_d3')
|
| 6 |
+
from exact import make_plan,parse_errors
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def _attach_arrays(item,root,splits):
|
| 10 |
+
row=item['row']
|
| 11 |
+
for split in splits:
|
| 12 |
+
a=np.load(root/split/row['arrays']);ds=np.unpackbits(a['detectors'],axis=1,count=row['num_detectors'],bitorder='little')
|
| 13 |
+
item[split+'_dets']=np.pad(ds,((0,0),(0,201-ds.shape[1])))
|
| 14 |
+
item[split+'_labels']=a['labels']
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def load_all(max_ops=3072,splits=('train','validation')):
|
| 18 |
+
assert set(splits)<=set(['train','validation'])
|
| 19 |
+
root=Path('/workspace/data')
|
| 20 |
+
rows=[r for r in json.loads((root/'train/manifest.json').read_text())['conditions'] if r['distance']==3]
|
| 21 |
+
groups=sorted({r['group'] for r in rows});result=[]
|
| 22 |
+
cache=Path('/workspace/research/learned_exact')/f'feature_cache-v2-{max_ops}'
|
| 23 |
+
cache.mkdir(exist_ok=True)
|
| 24 |
+
for row in rows:
|
| 25 |
+
cached=cache/f"{row['name']}-{row['noise_sha256'][:12]}-{row['circuit_sha256'][:12]}.npz"
|
| 26 |
+
if cached.exists():
|
| 27 |
+
item=dict(np.load(cached,allow_pickle=False));item['row']=row
|
| 28 |
+
_attach_arrays(item,root,splits);result.append(item);continue
|
| 29 |
+
dem=stim.DetectorErrorModel.from_file(root/'train'/row['noise']);plan=make_plan(dem)
|
| 30 |
+
assert int(plan['width'])<=10
|
| 31 |
+
count=len(plan['masks']);assert count<=max_ops,(row['name'],count)
|
| 32 |
+
coords=dem.get_detector_coordinates()
|
| 33 |
+
circuit=stim.Circuit.from_file(root/'train'/row['circuit'])
|
| 34 |
+
qubit_coords=circuit.get_final_qubit_coordinates()
|
| 35 |
+
first_measurement=next(ins for ins in circuit.flattened() if ins.name in ['M','MX','MR','MRX'])
|
| 36 |
+
spaces=sorted(tuple(qubit_coords[t.value][:2]) for t in first_measurement.targets_copy())
|
| 37 |
+
assert len(spaces)==8
|
| 38 |
+
idx={(int(c[2]),tuple(c[:2])):d for d,c in coords.items()}
|
| 39 |
+
errors=parse_errors(dem)
|
| 40 |
+
context=np.full((max_ops,40),200,np.int32)
|
| 41 |
+
static=np.zeros((max_ops,57),np.float32)
|
| 42 |
+
for op,source in enumerate(plan['source_indices']):
|
| 43 |
+
if source<0:continue
|
| 44 |
+
ds,logical,p=errors[source]
|
| 45 |
+
t=min(int(coords[d][2]) for d in ds) if ds else 0
|
| 46 |
+
for dt in range(-2,3):
|
| 47 |
+
for s,spatial in enumerate(spaces):context[op,(dt+2)*8+s]=idx.get((t+dt,spatial),200)
|
| 48 |
+
for d in ds:
|
| 49 |
+
c=coords[d];static[op,(int(c[2])-t+2)*8+spaces.index(tuple(c[:2]))]=1
|
| 50 |
+
static[op,40]=np.log(max(p,1e-7)/(1-max(p,1e-7)))/8
|
| 51 |
+
static[op,41]=logical;static[op,42]=len(ds)/4
|
| 52 |
+
static[op,43]=t/25;static[op,44]=row['rounds']/25
|
| 53 |
+
static[op,45]=t==0;static[op,46]=t>=row['rounds']-1
|
| 54 |
+
static[op,47+groups.index(row['group'])]=1
|
| 55 |
+
static[op,55]=row['basis']=='X';static[op,56]=1
|
| 56 |
+
masks=np.pad(plan['masks'],(0,max_ops-count))
|
| 57 |
+
measured=np.pad(plan['measured'],(0,max_ops-count),constant_values=-1)
|
| 58 |
+
p=np.pad(plan['probabilities'],(0,max_ops-count))
|
| 59 |
+
valid=((p>0)&(measured<0)).astype(np.float32)
|
| 60 |
+
logits=np.log(np.clip(p,1e-7,1-1e-7)/np.clip(1-p,1e-7,1-1e-7)).astype(np.float32)
|
| 61 |
+
item={'row':row,'context':context,'static':static,'masks':masks,'measured':measured,'base_logits':logits,'valid':valid}
|
| 62 |
+
grid=np.full((26,8),200,np.int32)
|
| 63 |
+
measurement_indices=np.full(201,208,np.int32)
|
| 64 |
+
for detector,c in coords.items():
|
| 65 |
+
t=int(c[2]);s=spaces.index(tuple(c[:2]));grid[t,s]=detector
|
| 66 |
+
measurement_indices[detector]=t*8+s
|
| 67 |
+
item['grid']=grid;item['measurement_indices']=measurement_indices
|
| 68 |
+
item['counts']=np.maximum((grid!=200).sum(axis=0),1).astype(np.float32)
|
| 69 |
+
temporary=cached.with_suffix('.tmp.npz')
|
| 70 |
+
np.savez(temporary,**{k:v for k,v in item.items() if k!='row'});temporary.replace(cached)
|
| 71 |
+
_attach_arrays(item,root,splits)
|
| 72 |
+
result.append(item)
|
| 73 |
+
return result
|
tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S040/training_sources/fresh_temporal1_swa/learned_exact__fresh_temporal_initialization.py
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Fresh independent d3 trunk and temporal encoder; no checkpoint loading."""
|
| 2 |
+
import jax
|
| 3 |
+
import jax.numpy as jnp
|
| 4 |
+
from model import initialize as initialize_trunk
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def initialize(seed=20261300, encoder_seed=20261301, channels=32):
|
| 8 |
+
parameters = initialize_trunk(seed, 145, hidden=128)
|
| 9 |
+
keys = jax.random.split(jax.random.key(encoder_seed), 6)
|
| 10 |
+
parameters['w1'] = jnp.concatenate([parameters['w1'], jax.random.normal(keys[0], (channels, 128)) * .001], axis=0)
|
| 11 |
+
parameters['temporal_in'] = jax.random.normal(keys[1], (24, channels)) * jnp.sqrt(2 / 24)
|
| 12 |
+
parameters['temporal_bias'] = jnp.zeros(channels)
|
| 13 |
+
for i in range(4):
|
| 14 |
+
parameters[f'temporal_conv_{i}'] = jax.random.normal(keys[i + 2], (3, channels, channels)) * jnp.sqrt(1 / (3 * channels))
|
| 15 |
+
parameters[f'temporal_conv_bias_{i}'] = jnp.zeros(channels)
|
| 16 |
+
return parameters
|
tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S040/training_sources/fresh_temporal1_swa/learned_exact__fresh_temporal_train.py
ADDED
|
@@ -0,0 +1,140 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
os.environ['OPENBLAS_NUM_THREADS']='1'
|
| 3 |
+
os.environ['OMP_NUM_THREADS']='1'
|
| 4 |
+
os.environ['XLA_PYTHON_CLIENT_PREALLOCATE']='false'
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
import argparse,json,time,sys,hashlib,shutil
|
| 7 |
+
import numpy as np
|
| 8 |
+
import jax,jax.numpy as jnp,optax
|
| 9 |
+
from temporal_model import probabilities
|
| 10 |
+
from fresh_temporal_initialization import initialize
|
| 11 |
+
from data import load_all
|
| 12 |
+
from gradient import make_loss_and_grad
|
| 13 |
+
sys.path.insert(0,'/workspace/research/exact_d3')
|
| 14 |
+
from exact import make_decoder
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def main():
|
| 18 |
+
parser=argparse.ArgumentParser();parser.add_argument('--steps',type=int,default=512);parser.add_argument('--batch',type=int,default=128)
|
| 19 |
+
parser.add_argument('--output',type=Path,required=True);parser.add_argument('--validation-shots',type=int,default=1024)
|
| 20 |
+
parser.add_argument('--init-weights',type=Path)
|
| 21 |
+
parser.add_argument('--initial-seed',type=int,default=20261300)
|
| 22 |
+
parser.add_argument('--encoder-seed',type=int,default=20261301)
|
| 23 |
+
parser.add_argument('--learning-rate',type=float,default=1e-3)
|
| 24 |
+
parser.add_argument('--eval-every',type=int,default=256)
|
| 25 |
+
parser.add_argument('--seed',type=int,default=20261025)
|
| 26 |
+
parser.add_argument('--validation-batch',type=int,default=1024)
|
| 27 |
+
parser.add_argument('--uniform-validation',action='store_true')
|
| 28 |
+
args=parser.parse_args();args.output.mkdir(parents=True,exist_ok=True)
|
| 29 |
+
run_config={k:str(v) if isinstance(v,Path) else v for k,v in vars(args).items()}
|
| 30 |
+
run_config['original_random_seed']=args.initial_seed
|
| 31 |
+
run_config['feature_mode']='events+measurements+global_density+temporal_convolutions'
|
| 32 |
+
run_config['temporal_seed']=args.encoder_seed
|
| 33 |
+
run_config['hidden_width']=128
|
| 34 |
+
run_config['logit_correction_bound']=4
|
| 35 |
+
run_config['starting_checkpoint_sha256']=hashlib.sha256(args.init_weights.read_bytes()).hexdigest() if args.init_weights else None
|
| 36 |
+
run_config['train_manifest_sha256']=hashlib.sha256(Path('/workspace/data/train/manifest.json').read_bytes()).hexdigest()
|
| 37 |
+
run_config['validation_manifest_sha256']=hashlib.sha256(Path('/workspace/data/validation/manifest.json').read_bytes()).hexdigest()
|
| 38 |
+
source_root=Path(__file__).resolve().parent;research=source_root.parent
|
| 39 |
+
snapshot=args.output/'training_source';snapshot.mkdir(exist_ok=True)
|
| 40 |
+
source_hashes={}
|
| 41 |
+
for source in [Path(__file__).resolve(),source_root/'temporal_model.py',source_root/'fresh_temporal_initialization.py',source_root/'model.py',source_root/'data.py',source_root/'gradient.py',research/'exact_d3/exact.py']:
|
| 42 |
+
name=str(source.relative_to(research)).replace('/','__')
|
| 43 |
+
shutil.copyfile(source,snapshot/name);source_hashes[name]=hashlib.sha256(source.read_bytes()).hexdigest()
|
| 44 |
+
run_config['training_source_sha256']=source_hashes
|
| 45 |
+
run_config['runtime_versions']={'jax':jax.__version__,'numpy':np.__version__,'optax':optax.__version__}
|
| 46 |
+
(args.output/'run_config.json').write_text(json.dumps(run_config,indent=2)+'\n')
|
| 47 |
+
t=time.time();dataset=load_all();print(json.dumps({'loaded':len(dataset),'seconds':time.time()-t}),flush=True)
|
| 48 |
+
seen=[np.zeros(len(item['train_labels']),bool) for item in dataset]
|
| 49 |
+
parameters=initialize(args.initial_seed,args.encoder_seed)
|
| 50 |
+
if args.init_weights:
|
| 51 |
+
parent_config=json.loads((args.init_weights.parent/'run_config.json').read_text())
|
| 52 |
+
assert parent_config['initial_seed']==args.initial_seed and parent_config['encoder_seed']==args.encoder_seed
|
| 53 |
+
parameters={k:jnp.asarray(v) for k,v in dict(np.load(args.init_weights,allow_pickle=False)).items()}
|
| 54 |
+
optimizer=optax.chain(optax.clip_by_global_norm(1.),optax.adamw(learning_rate=args.learning_rate,weight_decay=1e-4))
|
| 55 |
+
state=optimizer.init(parameters);exact_gradient=make_loss_and_grad(10)
|
| 56 |
+
rng=np.random.default_rng(args.seed);optimizer_restored=False;rng_restored=False
|
| 57 |
+
if args.init_weights:
|
| 58 |
+
optfile=args.init_weights.with_name(args.init_weights.name.replace('weights-','optimizer-'))
|
| 59 |
+
if optfile.exists():
|
| 60 |
+
leaves,treedef=jax.tree_util.tree_flatten(state);saved=np.load(optfile,allow_pickle=False)
|
| 61 |
+
assert len(leaves)==len(saved.files)
|
| 62 |
+
state=jax.tree_util.tree_unflatten(treedef,[jnp.asarray(saved[f'arr_{i}']) for i in range(len(leaves))]);optimizer_restored=True
|
| 63 |
+
rngfile=args.init_weights.with_name(args.init_weights.name.replace('weights-','rng-')).with_suffix('.json')
|
| 64 |
+
if rngfile.exists():rng.bit_generator.state=json.loads(rngfile.read_text());rng_restored=True
|
| 65 |
+
@jax.jit
|
| 66 |
+
def update(parameters,state,ds,ys,context,static,base_logits,valid,masks,measured,grid,measurement_indices,counts):
|
| 67 |
+
p,pullback=jax.vjp(lambda w:probabilities(w,ds,context,static,base_logits,valid,grid,measurement_indices,counts),parameters)
|
| 68 |
+
loss,pred,g=exact_gradient(ds,ys,p,masks,measured)
|
| 69 |
+
grads=pullback(g/len(ds))[0]
|
| 70 |
+
changes,state=optimizer.update(grads,state,parameters)
|
| 71 |
+
parameters=optax.apply_updates(parameters,changes)
|
| 72 |
+
return parameters,state,jnp.mean(loss),jnp.mean((pred>=.5)!=ys),optax.global_norm(grads)
|
| 73 |
+
exact_decode=make_decoder(10)
|
| 74 |
+
@jax.jit
|
| 75 |
+
def infer(parameters,ds,context,static,base_logits,valid,masks,measured,grid,measurement_indices,counts):
|
| 76 |
+
p=probabilities(parameters,ds,context,static,base_logits,valid,grid,measurement_indices,counts)
|
| 77 |
+
return exact_decode(ds,p,masks,measured)
|
| 78 |
+
def evaluate(step):
|
| 79 |
+
results=[];start=time.time()
|
| 80 |
+
for item in dataset:
|
| 81 |
+
n=min(args.validation_shots,len(item['validation_labels']));pred=[]
|
| 82 |
+
selected=np.random.default_rng(20261028).choice(len(item['validation_labels']),n,replace=False) if args.uniform_validation else np.arange(n)
|
| 83 |
+
vd=item['validation_dets'][selected];vy=item['validation_labels'][selected]
|
| 84 |
+
for begin in range(0,n,args.validation_batch):
|
| 85 |
+
ds=vd[begin:begin+args.validation_batch];size=len(ds)
|
| 86 |
+
ds=np.pad(ds,((0,args.validation_batch-size),(0,0)))
|
| 87 |
+
p=np.asarray(infer(parameters,ds,*[item[k] for k in ['context','static','base_logits','valid','masks','measured','grid','measurement_indices','counts']]))[:size]
|
| 88 |
+
pred.append(p)
|
| 89 |
+
p=np.concatenate(pred)
|
| 90 |
+
pp=np.clip(p.astype(np.float64),1e-7,1-1e-7);yy=vy.astype(np.float64)
|
| 91 |
+
results.append({'condition':item['row']['name'],'failure':float(np.mean((p>=.5)!=vy)),
|
| 92 |
+
'negative_log_likelihood':float(np.mean(-yy*np.log(pp)-(1-yy)*np.log1p(-pp))),
|
| 93 |
+
'brier':float(np.mean((p-vy)**2))})
|
| 94 |
+
result={'step':step,'validation_failure':float(np.mean([r['failure'] for r in results])),
|
| 95 |
+
'negative_log_likelihood':float(np.mean([r['negative_log_likelihood'] for r in results])),
|
| 96 |
+
'seconds':time.time()-start,'conditions':results}
|
| 97 |
+
(args.output/f'validation-{step}.json').write_text(json.dumps(result,indent=2)+'\n')
|
| 98 |
+
np.savez(args.output/f'weights-{step}.npz',**{k:np.asarray(v) for k,v in parameters.items()})
|
| 99 |
+
leaves,_=jax.tree_util.tree_flatten(state)
|
| 100 |
+
np.savez(args.output/f'optimizer-{step}.npz',**{f'arr_{i}':np.asarray(v) for i,v in enumerate(leaves)})
|
| 101 |
+
(args.output/f'rng-{step}.json').write_text(json.dumps(rng.bit_generator.state)+'\n')
|
| 102 |
+
(args.output/f'checkpoint-{step}.json').write_text(json.dumps({'step':step,'new_training_shots':step*args.batch,
|
| 103 |
+
'unique_training_rows_seen_in_this_phase':sum(int(x.sum()) for x in seen),
|
| 104 |
+
'weights':f'weights-{step}.npz','weights_sha256':hashlib.sha256((args.output/f'weights-{step}.npz').read_bytes()).hexdigest(),
|
| 105 |
+
'validation':f'validation-{step}.json','complete':True},indent=2)+'\n')
|
| 106 |
+
print(json.dumps({k:v for k,v in result.items() if k!='conditions'}),flush=True)
|
| 107 |
+
evaluate(0)
|
| 108 |
+
records=[]
|
| 109 |
+
for step in range(1,args.steps+1):
|
| 110 |
+
condition_index=int(rng.integers(len(dataset)));item=dataset[condition_index]
|
| 111 |
+
ix=rng.integers(len(item['train_labels']),size=args.batch);seen[condition_index][ix]=True
|
| 112 |
+
parameters,state,loss,error,norm=update(parameters,state,item['train_dets'][ix],item['train_labels'][ix],
|
| 113 |
+
*[item[k] for k in ['context','static','base_logits','valid','masks','measured','grid','measurement_indices','counts']])
|
| 114 |
+
if step%16==0 or step==1:
|
| 115 |
+
record={'step':step,'loss':float(loss),'error':float(error),'gradient_norm':float(norm),'elapsed':time.time()-t}
|
| 116 |
+
records.append(record);print(json.dumps(record),flush=True)
|
| 117 |
+
if not np.isfinite(record['loss']):raise ValueError('Nonfinite training loss')
|
| 118 |
+
if step%args.eval_every==0 or step==args.steps:evaluate(step)
|
| 119 |
+
provenance={'initialization':('Continue from this session\'s trained checkpoint' if args.init_weights else 'Entire rich trunk and temporal encoder initialized randomly in this session; no learned checkpoint loaded'),
|
| 120 |
+
'original_initialization':f'Fresh128-unit rich trunk NumPy seed{args.initial_seed}: hidden weights Normal(0,1/sqrt(fan-in)),output Normal(0,.001),zero biases. Fresh32-channel temporal encoder JAX seed{args.encoder_seed}: variance-scaled normal input/convolution weights,zero biases; appendedinput rows Normal(0,.001).',
|
| 121 |
+
'initial_seed':args.initial_seed,'encoder_seed':args.encoder_seed,
|
| 122 |
+
'architecture':'Rich 128-unit MLP plus 32-channel temporal encoder: four residual kernel3 convolutions with dilations1/2/4/8 and channel normalization. Receptive field31 rounds. Encoder sees events, measurements and presence masks. Per-edge 177 input features. Output4*tanh.',
|
| 123 |
+
'training':'Uniform condition sampling from all 104 d3 conditions; batch drawn from the supplied training split only',
|
| 124 |
+
'training_source_sha256':source_hashes,'runtime_versions':run_config['runtime_versions'],
|
| 125 |
+
'eligible_training_shots':sum(len(item['train_labels']) for item in dataset),
|
| 126 |
+
'unique_training_rows_seen_in_this_phase':sum(int(x.sum()) for x in seen),
|
| 127 |
+
'unique_rows_by_condition':{item['row']['name']:int(x.sum()) for item,x in zip(dataset,seen)},
|
| 128 |
+
'steps':args.steps,'batch_size':args.batch,'optimizer':'AdamW, weight decay 1e-4, global gradient norm clip 1',
|
| 129 |
+
'learning_rate':args.learning_rate,'sampling_seed':args.seed,'optimizer_restored':optimizer_restored,'rng_restored':rng_restored,
|
| 130 |
+
'sampling_state_source':str(rngfile) if rng_restored else f'Fresh NumPy default_rng seed {args.seed}',
|
| 131 |
+
'session_trained_starting_checkpoint':str(args.init_weights) if args.init_weights else None,
|
| 132 |
+
'starting_checkpoint_sha256':hashlib.sha256(args.init_weights.read_bytes()).hexdigest() if args.init_weights else None,
|
| 133 |
+
'starting_training_provenance':json.loads((args.init_weights.parent/'provenance.json').read_text()) if args.init_weights else None,
|
| 134 |
+
'loss':'Binary conditional logical likelihood computed by exact frontier elimination',
|
| 135 |
+
'validation_shots_per_condition':args.validation_shots,'uniform_validation':args.uniform_validation,
|
| 136 |
+
'uniform_validation_seed':20261028 if args.uniform_validation else None,'test_data_used':False,'log':records}
|
| 137 |
+
(args.output/'provenance.json').write_text(json.dumps(provenance,indent=2)+'\n')
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
if __name__=='__main__':main()
|
tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S040/training_sources/fresh_temporal1_swa/learned_exact__gradient.py
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Differentiable conditional logical likelihood through exact DEM elimination."""
|
| 2 |
+
import jax
|
| 3 |
+
import jax.numpy as jnp
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
def make_loss_and_grad(width):
|
| 7 |
+
indices=jnp.arange(1<<width,dtype=jnp.int32)
|
| 8 |
+
@jax.jit
|
| 9 |
+
def evaluate(dets,labels,probabilities,masks,measured):
|
| 10 |
+
# Per-shot error probabilities have shape [operations,batch].
|
| 11 |
+
f=jnp.zeros((len(dets),1<<width),jnp.float32).at[:,0].set(1)
|
| 12 |
+
def forward(f,args):
|
| 13 |
+
p,mask,d=args
|
| 14 |
+
def error(f):
|
| 15 |
+
return (1-p[:,None])*f+p[:,None]*f[:,indices^mask],jnp.ones(len(dets))
|
| 16 |
+
def project(f):
|
| 17 |
+
dst=(indices[None,:]&~mask)|(dets[:,d,None].astype(jnp.int32)*mask)
|
| 18 |
+
g=jnp.take_along_axis(f,dst,axis=1)*((indices&mask)==0)
|
| 19 |
+
norm=jnp.maximum(g.sum(axis=1),1e-30)
|
| 20 |
+
return g/norm[:,None],norm
|
| 21 |
+
out,norm=jax.lax.cond(d<0,error,project,f)
|
| 22 |
+
return out,(f,norm)
|
| 23 |
+
f,(history,norms)=jax.lax.scan(forward,f,(probabilities,masks,measured))
|
| 24 |
+
indicator=((indices[None,:]&1)==labels[:,None])
|
| 25 |
+
correct=jnp.maximum(jnp.sum(f*indicator,axis=1),1e-10)
|
| 26 |
+
predicted=jnp.sum(f[:,1::2],axis=1)
|
| 27 |
+
initial=1-indicator/correct[:,None]
|
| 28 |
+
def backward(b,args):
|
| 29 |
+
p,mask,d,old,norm=args
|
| 30 |
+
def error(b):
|
| 31 |
+
flipped=b[:,indices^mask]
|
| 32 |
+
grad=jnp.sum(old*(flipped-b),axis=1)
|
| 33 |
+
return (1-p[:,None])*b+p[:,None]*flipped,grad
|
| 34 |
+
def project(b):
|
| 35 |
+
obs=((indices[None,:]&mask)==dets[:,d,None].astype(jnp.int32)*mask)
|
| 36 |
+
values=b[:,indices&~mask]
|
| 37 |
+
mean=jnp.sum(old*obs*values,axis=1)/norm
|
| 38 |
+
prior=(values-mean[:,None])*obs/norm[:,None]
|
| 39 |
+
return prior,jnp.zeros(len(dets))
|
| 40 |
+
return jax.lax.cond(d<0,error,project,b)
|
| 41 |
+
_,grad=jax.lax.scan(backward,initial,(probabilities,masks,measured,history,norms),reverse=True)
|
| 42 |
+
return -jnp.log(correct),predicted,grad
|
| 43 |
+
return evaluate
|