s42chen's picture
Publish 11 evaluated Astra histories with reproducible checkpoint artifacts (part 54)
b75888f verified
Raw History Blame Contribute Delete
6.62 kB
"""Fit matching ensemble from random coefficients using the hardware training split."""
import os
os.environ['OPENBLAS_NUM_THREADS'] = '1'
os.environ['OMP_NUM_THREADS'] = '1'
from concurrent.futures import ProcessPoolExecutor, as_completed
from pathlib import Path
import json, time, hashlib, shutil, importlib.metadata
import numpy as np
import stim
from scipy.optimize import minimize
from scipy.special import expit
from decoder import match_features, predict_features
ROOT = Path(__file__).resolve().parent
DATA = Path('/workspace/data')
def features(row):
path = ROOT/'cache'/f"{row['name']}.npz"
if path.exists():
return row['name']
dem = stim.DetectorErrorModel.from_file(DATA/'train'/row['noise'])
content = {}
for split in ('train', 'validation'):
with np.load(DATA/split/row['arrays'], allow_pickle=False) as a:
content[split+'_x'] = match_features(dem, a['detectors'], row['rounds'])
content[split+'_y'] = a['labels']
np.savez(path, **content)
return row['name']
def main():
start = time.time()
rows = json.loads((DATA/'train/manifest.json').read_text())['conditions']
(ROOT/'cache').mkdir(exist_ok=True)
with ProcessPoolExecutor(max_workers=16) as pool:
futures = [pool.submit(features, row) for row in rows]
for i, future in enumerate(as_completed(futures)):
print(json.dumps({'features_done': i+1, 'condition': future.result(), 'seconds': time.time()-start}), flush=True)
pkg = ROOT/'package'
pkg.mkdir(exist_ok=True)
(pkg/'weights').mkdir(exist_ok=True)
(pkg/'dems').mkdir(exist_ok=True)
config = {'architecture': 'per-group logistic ensemble of MWPM, correlated MWPM, and two constrained logical cosets',
'feature_version': 1, 'groups': {}, 'conditions': {}}
history = []
for group in sorted({r['group'] for r in rows}):
members = [r for r in rows if r['group'] == group]
cache = [np.load(ROOT/'cache'/f"{r['name']}.npz") for r in members]
x = np.concatenate([a['train_x'] for a in cache]).astype(np.float64)
y = np.concatenate([a['train_y'] for a in cache]).astype(np.float64)
vx = np.concatenate([a['validation_x'] for a in cache]).astype(np.float64)
vy = np.concatenate([a['validation_y'] for a in cache])
scale = np.maximum(np.sqrt(np.mean(x*x, axis=0)), 0.01)
x /= scale
rng = np.random.default_rng(20261021)
initial = rng.normal(0, 0.01, x.shape[1])
def objective(w):
z = x @ w
loss = np.mean(np.logaddexp(0, z)-y*z) + 1e-5*np.sum(w*w)
grad = x.T @ (expit(z)-y)/len(y) + 2e-5*w
return loss, grad
fit = minimize(objective, initial, jac=True, method='L-BFGS-B', options={'maxiter': 300, 'ftol': 1e-12})
state = {'coef': fit.x.astype(np.float32), 'scale': scale.astype(np.float32)}
p = predict_features(vx, state)
metrics = {'group': group, 'train_loss': float(fit.fun), 'iterations': int(fit.nit),
'failure': float(np.mean((p>=.5)!=vy)),
'plain_failure': float(np.mean((vx[:,2]>0)!=vy)),
'correlated_failure': float(np.mean((vx[:,3]>0)!=vy)),
'coset_failure': float(np.mean((vx[:,1]>0)!=vy)),
'optimizer_success': bool(fit.success)}
history.append(metrics)
print(json.dumps(metrics), flush=True)
np.savez(pkg/'weights'/f'{group}.npz', **state)
config['groups'][group] = f'weights/{group}.npz'
for row in rows:
target = f"dems/{row['name']}.dem"
shutil.copyfile(DATA/'train'/row['noise'], pkg/target)
config['conditions'][row['name']] = {'dem': target, 'circuit_sha256': row['circuit_sha256']}
shutil.copyfile(ROOT/'decoder.py', pkg/'decoder.py')
shutil.copyfile(ROOT/'train.py', pkg/'training_code.py')
(pkg/'infer.sh').write_text('#!/bin/sh\nset -eu\nexport OPENBLAS_NUM_THREADS=1 OMP_NUM_THREADS=1\nROOT="$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)"\nexec python "$ROOT/decoder.py" "$1" "$2"\n')
(pkg/'infer.sh').chmod(0o755)
(pkg/'README.md').write_text('# Learned matching ensemble\n\nRun `bash infer.sh INPUT_ROOT OUTPUT_ROOT`. Ten logistic specialists are trained from random initialization on all supplied hardware training shots. Features combine matching decisions, constrained logical-coset weight gaps, event density and duration. No IDs enter the model. Fitted DEMs are included for all 130 conditions. Training and validation history is in training_provenance.json.\n')
deps = ['numpy', 'scipy', 'stim', 'pymatching']
(pkg/'requirements.lock').write_text('\n'.join(f'{d}=={importlib.metadata.version(d)}' for d in deps)+'\n')
sha = lambda p: hashlib.sha256(p.read_bytes()).hexdigest()
provenance = {'initialization': {'distribution': 'Normal(0,0.01)', 'seed': 20261021, 'pretrained_weights': False},
'training_data': 'all 19880 supplied training shots per condition; all 130 conditions',
'train_manifest_sha256': sha(DATA/'train/manifest.json'),
'validation_manifest_sha256': sha(DATA/'validation/manifest.json'),
'calibration_exception': 'Supplied even-fitted DEMs include validation syndromes but no logical labels or test data.',
'optimizer': 'L-BFGS-B binary cross entropy plus 1e-5 L2, maximum 300 iterations',
'selection': 'First trained candidate; validation reported without parameter fitting or hyperparameter selection',
'test_data_used': False, 'released_per_shot_predictions_used': False,
'history': history, 'elapsed_seconds': time.time()-start}
for name, obj in [('model_config.json', config), ('training_provenance.json', provenance)]:
(pkg/name).write_text(json.dumps(obj, indent=2)+'\n')
checkpoints = [{'path': str(p.relative_to(pkg)), 'sha256': sha(p), 'format': 'npz' if p.suffix=='.npz' else 'stim-dem'}
for p in sorted((pkg/'weights').glob('*'))+sorted((pkg/'dems').glob('*'))]
(pkg/'model_manifest.json').write_text(json.dumps({'schema': 'surface-code-decoding-model/v1', 'checkpoints': checkpoints,
'model_config': 'model_config.json', 'training_provenance': 'training_provenance.json'}, indent=2)+'\n')
p = 1-np.mean([np.mean([h['failure'] for h in history if h['group'].startswith(d)]) for d in ['d3', 'd5']])
print(json.dumps({'P': p, 'package': str(pkg), 'seconds': time.time()-start}), flush=True)
if __name__ == '__main__':
main()