File size: 6,377 Bytes
32d1b4a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
"""Select contextual specialists on full validation and assemble a candidate."""
import os
os.environ['OPENBLAS_NUM_THREADS']='1'
from pathlib import Path
import json,shutil,hashlib,sys
import numpy as np
from data import load_all
root=Path(__file__).resolve().parent
base=Path('/workspace/research/exact_d3/package3')
pkg=root/'package';shutil.copytree(base,pkg,dirs_exist_ok=True)
config=json.loads((pkg/'model_config.json').read_text());config['contextual']={}
rows=[r for r in json.loads(Path('/workspace/data/validation/manifest.json').read_text())['conditions'] if r['distance']==3]
groups=sorted({r['group'] for r in rows})
previous=json.loads((base/'validation_report.json').read_text())
reports={step:json.loads((root/f'validation{step}/report.json').read_text()) for step in [256,512]}
previous_by_name={name:r['errors']/r['total'] for name,r in previous['per_condition'].items()}
candidate_by_name={step:{r['condition']:r['failure'] for r in report['conditions']} for step,report in reports.items()}
history=[];selected_predictions=root/'selected-predictions';selected_predictions.mkdir(exist_ok=True)
for group in groups:
    members=[r for r in rows if r['group']==group]
    failures={'previous':float(np.mean([previous_by_name[r['name']] for r in members]))}
    failures.update({str(step):float(np.mean([candidate_by_name[step][r['name']] for r in members])) for step in reports})
    choice=min(failures,key=failures.get)
    if choice!='previous':config['contextual'][group]={'weights':f'weights/contextual-{choice}.npz','pilot_step':int(choice)}
    source=Path('/workspace/research/exact_d3/validation3-predictions') if choice=='previous' else root/f'validation{choice}'
    for r in members:shutil.copyfile(source/f"{r['name']}.npz",selected_predictions/f"{r['name']}.npz")
    record={'group':group,'candidates':failures,'selected':choice};history.append(record);print(json.dumps(record),flush=True)
for p in Path('/workspace/research/exact_d3/validation3-predictions').glob('*_d5_*.npz'):shutil.copyfile(p,selected_predictions/p.name)
(pkg/'contextual_plans').mkdir(exist_ok=True)
for item in load_all():
    row=item['row']
    if row['group'] not in config['contextual']:continue
    used=int(np.flatnonzero((item['valid']>0)|(item['measured']>=0))[-1])+1;length=((used+511)//512)*512
    path=f"contextual_plans/{row['name']}.npz"
    np.savez(pkg/path,**{k:item[k][:length] for k in ['context','static','base_logits','valid','masks','measured']})
    config['conditions'][row['name']]['contextual_plan']=path
for step in {r['pilot_step'] for r in config['contextual'].values()}:
    shutil.copyfile(root/'pilot'/f'weights-{step}.npz',pkg/'weights'/f'contextual-{step}.npz')
shutil.copyfile(root/'model.py',pkg/'context_model.py');shutil.copyfile(root/'contextual.py',pkg/'contextual.py')
source=(pkg/'hybrid3.py').read_text()
source=source.replace('decoders={};started=time.time()',
    'decoders={};started=time.time()\n    from contextual import ContextualDecoder\n    contextual_decoder=ContextualDecoder()')
needle="        kind=config['kinds'][row['group']]"
replacement="""        if row['group'] in config.get('contextual',{}):
            p=contextual_decoder.predict(package,record,config['contextual'][row['group']],packed,row['num_detectors'])
            np.savez(output/f"{row['name']}.npz",sample_ids=ids,probabilities=p)
            print(json.dumps({'condition':row['name'],'elapsed_seconds':time.time()-started}),flush=True)
            continue
        kind=config['kinds'][row['group']]"""
assert needle in source;source=source.replace(needle,replacement);(pkg/'hybrid3.py').write_text(source)
config['architecture']='Neural contextual exact contraction for selected d3 groups; fixed exact contraction and ensembles otherwise; soft-conditioned CSS contractions for d5'
(pkg/'model_config.json').write_text(json.dumps(config,indent=2)+'\n')
provenance=json.loads((pkg/'training_provenance.json').read_text())
provenance['contextual_d3_pilot']={'training':json.loads((root/'pilot/provenance.json').read_text()),
    'selection':'Per-group minimum failure among previous decoder and pilot steps 256 and 512, using all 532480 d3 validation shots',
    'history':history,'initial_validation_subset':'First 512 validation rows/condition; then both trained checkpoints evaluated on full validation',
    'features':'40 detection bits within five frames and 57 static error/geometry features; detector indices come from the ideal geometry/DEM; sample IDs are not features',
    'derivative_check':'Relative error 1.16e-7 versus automatic differentiation on a small d3 example'}
provenance['previous_package_validation']=provenance.pop('package_validation')
(pkg/'training_provenance.json').write_text(json.dumps(provenance,indent=2)+'\n')
(pkg/'README.md').write_text('# Contextual structured logical decoder\n\nRun `bash infer.sh INPUT_ROOT OUTPUT_ROOT`. Selected d3 groups use a small network trained from random initialization to set context-dependent error weights, followed by exact contraction. Other d3 groups retain fixed exact contraction and learned matching ensembles. Distance 5 uses soft conditioning between CSS checks and exact contractions. All supplied geometries, bases and durations are supported, with arbitrary shot order/count/subsets. IDs are copied only. Training and full-validation selection history is recorded in training_provenance.json.\n')
shutil.copytree(root,pkg/'contextual_training_source',ignore=shutil.ignore_patterns('*.npz','*.log','*.json','pilot','validation256','validation512','selected-predictions','package','continuation1','__pycache__'),dirs_exist_ok=True)
sha=lambda p:hashlib.sha256(p.read_bytes()).hexdigest()
files=[p for d in ['weights','dems','plans','conditional_plans','contextual_plans'] for p in sorted((pkg/d).glob('*'))]
manifest={'schema':'surface-code-decoding-model/v1','checkpoints':[{'path':str(p.relative_to(pkg)),'sha256':sha(p),'format':'npz' if p.suffix=='.npz' else 'stim-dem'} for p in files],
    'model_config':'model_config.json','training_provenance':'training_provenance.json'}
(pkg/'model_manifest.json').write_text(json.dumps(manifest,indent=2)+'\n')
new_d3=float(np.mean([h['candidates'][h['selected']] for h in history]));d5=previous['failure_by_distance']['d5']
print(json.dumps({'expected_P':1-(new_d3+d5)/2,'d3_failure':new_d3,'d5_failure':d5}),flush=True)