Publish 11 evaluated Astra histories with reproducible checkpoint artifacts (part 56)
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/S044/runtime_sources/persistent_attention1/plan.json +31 -0
- tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S044/selection_history.json +0 -0
- tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S044/short_syndrome_model.py +8 -0
- tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S044/temporal_base_contextual.py +32 -0
- tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S044/temporal_contextual.py +42 -0
- tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S044/temporal_model.py +44 -0
- tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S044/training_code.py +108 -0
- tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S044/training_sources/axial_residual1/data.py +51 -0
- tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S044/training_sources/axial_residual1/model.py +89 -0
- tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S044/training_sources/axial_residual1/state.py +34 -0
- tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S044/training_sources/axial_residual1/train.py +87 -0
- tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S044/training_sources/beam_calibration1/FIT_SOURCE_LOCK.json +15 -0
- tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S044/training_sources/beam_calibration1/PACKAGE_SOURCE_LOCK.json +19 -0
- tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S044/training_sources/beam_calibration1/QUEUE_AMENDMENT.json +10 -0
- tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S044/training_sources/beam_calibration1/after_resource.py +32 -0
- tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S044/training_sources/beam_calibration1/beam_cpu.py +45 -0
- tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S044/training_sources/beam_calibration1/beam_lookahead.py +76 -0
- tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S044/training_sources/beam_calibration1/control_cpu.py +20 -0
- tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S044/training_sources/beam_calibration1/core.py +36 -0
- tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S044/training_sources/beam_calibration1/export.py +11 -0
- tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S044/training_sources/beam_calibration1/fit.py +104 -0
- tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S044/training_sources/beam_calibration1/generate_beam_training.py +34 -0
- tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S044/training_sources/beam_calibration1/generate_parent_training.py +21 -0
- tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S044/training_sources/beam_calibration1/package.py +55 -0
- tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S044/training_sources/beam_calibration1/plan.json +91 -0
- tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S044/training_sources/beam_calibration1/runtime.py +37 -0
- tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S044/training_sources/beam_calibration1/runtime_control.py +42 -0
- tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S044/training_sources/beam_calibration1/verify_during_recovery.py +21 -0
- tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S044/training_sources/condition_same1/exact_d3__exact.py +213 -0
- tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S044/training_sources/condition_same1/learned_exact__data.py +73 -0
- tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S044/training_sources/condition_same1/learned_exact__gradient.py +43 -0
- tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S044/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/S044/training_sources/condition_same1/learned_exact__temporal_model.py +44 -0
- tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S044/training_sources/conditional_edge_projection1/PROPOSAL.json +17 -0
- tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S044/training_sources/conditional_edge_projection1/REPLAY_BACKEND_RECOVERY_PLAN.json +16 -0
- tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S044/training_sources/conditional_edge_projection1/RUNTIME_PRECISION_RECOVERY_PLAN.json +96 -0
- tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S044/training_sources/conditional_edge_projection1/TRAINING_PLAN.json +28 -0
- tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S044/training_sources/conditional_edge_projection1/after_d3_head.py +27 -0
- tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S044/training_sources/conditional_edge_projection1/audit_run.py +34 -0
- tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S044/training_sources/conditional_edge_projection1/aux_encoder.py +39 -0
- tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S044/training_sources/conditional_edge_projection1/axial_base.py +89 -0
- tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S044/training_sources/conditional_edge_projection1/backend_control.py +32 -0
- tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S044/training_sources/conditional_edge_projection1/checkpoint_gradient.py +73 -0
- tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S044/training_sources/conditional_edge_projection1/compiled.py +19 -0
- tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S044/training_sources/conditional_edge_projection1/conditional_tokens.py +16 -0
- tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S044/training_sources/conditional_edge_projection1/confidence_joint.py +38 -0
- tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S044/training_sources/conditional_edge_projection1/contextual.py +40 -0
- tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S044/training_sources/conditional_edge_projection1/control_cpu.py +45 -0
- tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S044/training_sources/conditional_edge_projection1/core.py +30 -0
- tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S044/training_sources/conditional_edge_projection1/data.py +38 -0
tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S044/runtime_sources/persistent_attention1/plan.json
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"name": "persistent_attention1",
|
| 3 |
+
"created_utc": "2026-10-21T21:43:42.641693+00:00",
|
| 4 |
+
"status": "CPU controls passed; queued after pretrained_axial1",
|
| 5 |
+
"hypothesis": "Global per-condition jax.clear_caches in hybrid3 forces repeated compilation of fixed-shape attention. Retain bounded compiled callable across clears to reduce startup overhead. CPU controls confirmed retention and exact predictions; GPU runtime benefit unmeasured.",
|
| 6 |
+
"changes": "Only two recognized axial dispatchers use PersistentCompiled instead of jax.jit; shapes/dtypes/weaktypes form cache key, at most2 executables per wrapper. No weights, modelconfig, loss, training, validation choice or mathematical inference changes.",
|
| 7 |
+
"current_reference": {
|
| 8 |
+
"package": "/run-state/workspace/research/context_upgrades/axial_residual1/package",
|
| 9 |
+
"predictions": "/run-state/workspace/research/context_upgrades/axial_residual1/predictions",
|
| 10 |
+
"score": "/run-state/workspace/research/context_upgrades/axial_residual1/score.json",
|
| 11 |
+
"P": 0.7674663837139424
|
| 12 |
+
},
|
| 13 |
+
"queue_after": "pretrained_axial/pretrained_axial1_finished.json",
|
| 14 |
+
"mandatory_before_publication": "ActualnativeGPU B256repeatedfreshJIT/clear/order/shapecontrols and<75GiBpeak; full26d5actualreplay+trusted130score;0decisionchangesandmaxprobdelta<1e-5;readonlyrelocationchecks; actualreplayfasterthanthen-currentrecordedreplay;runtimeprojection<3600. No publicationifnoactiveattentionroute ornotfaster. Timingsareseparateruns.",
|
| 15 |
+
"test_data_used": false,
|
| 16 |
+
"frozen_source_sha256": {
|
| 17 |
+
"persistent_attention/control_cpu.py": "6a065ed03d1ddb27a46a15479987b8a836d0328c965975dc9c0ce02969326691",
|
| 18 |
+
"persistent_attention/after_pretrained.py": "732d28a009eec864f0b056b3ba78202a1aa21202ae7b70d38dc92b1909158476",
|
| 19 |
+
"persistent_attention/export_control_cpu.py": "eddf82b51a3cdff62b514c69e0cd9fa611f7e9302a8fbfd9b00738284820ceb3",
|
| 20 |
+
"persistent_attention/compiled.py": "c54ce7837bc6ad683ed2b5bf5353eb161dc12156ae5564618e1c4f08489386dd",
|
| 21 |
+
"persistent_attention/control_gpu.py": "6243506814a7b31b7123a77136d976c496a0f4dc4850b8dbe44977138fb13e82",
|
| 22 |
+
"persistent_attention/export.py": "59c5c3e0a9e94374626f58dd7a6cd6bcc34ec32c5f73ba819ef34d38213b8301",
|
| 23 |
+
"persistent_attention/control_cpu.json": "36496b247c1f6c43220fa9a72eab20e2e665b79e6f6cf67dc113dabf097034de",
|
| 24 |
+
"persistent_attention/export_control_cpu.json": "3f90b6f33ee84f1c12f6d16bb9be5948cdde39ea8d5e7ce148a272f7ed4c0936",
|
| 25 |
+
"axial_residual/model.py": "a62d91d239325f45d9f1a6af6e91095b8d6028a52959dcb7b98ba109df097537",
|
| 26 |
+
"axial_residual/data.py": "3fb7f50cac3adf37b53db5873965a8e62e6eac09ccc54d89198ec569450271d3",
|
| 27 |
+
"axial_residual/contextual.py": "6865098931f4c9a84c791235fb3e0a0e0e5a8b4d10150b924528f078793f589c",
|
| 28 |
+
"pretrained_axial/contextual.py": "3b70b79285379b3424bb422daaf99dcebfa152e8695e858b58ecfa7376a359d0",
|
| 29 |
+
"axial_residual/axial1/weights-2048.npz": "c26b6b6faf8ac559161f1ba5370bd2ac7302e77852849ba1742a7a14eae3a9a3"
|
| 30 |
+
}
|
| 31 |
+
}
|
tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S044/selection_history.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/S044/short_syndrome_model.py
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Categorical logical decoder indexed only by an8-bit detection syndrome."""
|
| 2 |
+
import numpy as np
|
| 3 |
+
from scipy.special import expit
|
| 4 |
+
|
| 5 |
+
def predict(packed,state):
|
| 6 |
+
assert packed.dtype==np.uint8 and packed.ndim==2 and packed.shape[1]==1
|
| 7 |
+
key=packed[:,0]
|
| 8 |
+
return expit(state['physical_logits'][key]+state['residual_logits'][key]).astype(np.float32)
|
tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S044/temporal_base_contextual.py
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Portable temporal contextual exact decoder with shot-local features."""
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
import numpy as np
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class TemporalContextualDecoder:
|
| 7 |
+
def __init__(self):
|
| 8 |
+
import jax
|
| 9 |
+
from temporal_model import probabilities
|
| 10 |
+
from exact import make_decoder
|
| 11 |
+
exact=make_decoder(10)
|
| 12 |
+
@jax.jit
|
| 13 |
+
def infer(weights,ds,context,static,base_logits,valid,masks,measured,grid,measurement_indices,counts):
|
| 14 |
+
p=probabilities(weights,ds,context,static,base_logits,valid,grid,measurement_indices,counts)
|
| 15 |
+
return exact(ds,p,masks,measured)
|
| 16 |
+
self.infer=infer;self.weights={}
|
| 17 |
+
|
| 18 |
+
def predict(self,root,record,group_record,packed,num_detectors,batch=1024):
|
| 19 |
+
import jax.numpy as jnp
|
| 20 |
+
path=group_record['weights']
|
| 21 |
+
if path not in self.weights:
|
| 22 |
+
self.weights[path]={k:jnp.asarray(v) for k,v in dict(np.load(root/path,allow_pickle=False)).items()}
|
| 23 |
+
plan=dict(np.load(root/record['rich_plan'],allow_pickle=False))
|
| 24 |
+
ds=np.unpackbits(packed,axis=1,count=num_detectors,bitorder='little')
|
| 25 |
+
ds=np.pad(ds,((0,0),(0,201-num_detectors)))
|
| 26 |
+
args=[plan[k] for k in ['context','static','base_logits','valid','masks','measured','grid','measurement_indices','counts']]
|
| 27 |
+
outputs=[]
|
| 28 |
+
for begin in range(0,len(ds),batch):
|
| 29 |
+
selected=ds[begin:begin+batch];n=len(selected)
|
| 30 |
+
selected=np.pad(selected,((0,batch-n),(0,0)))
|
| 31 |
+
outputs.append(np.asarray(self.infer(self.weights[path],selected,*args))[:n])
|
| 32 |
+
return np.concatenate(outputs).astype(np.float32)
|
tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S044/temporal_contextual.py
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Portable one-quality-chain route; original surrounding routes remain callable."""
|
| 2 |
+
import numpy as np
|
| 3 |
+
from d3_pre_latent_temporal import TemporalContextualDecoder as ParentDecoder
|
| 4 |
+
from d3_lr_compiled import PersistentCompiled
|
| 5 |
+
from d3_lr_core import make_kernels
|
| 6 |
+
|
| 7 |
+
class TemporalContextualDecoder(ParentDecoder):
|
| 8 |
+
def __init__(self):
|
| 9 |
+
import jax
|
| 10 |
+
super().__init__();self.latent_weights={};self.latent_groups={};self.latent_plans={}
|
| 11 |
+
self.latent_infer=PersistentCompiled(make_kernels(interpret=jax.default_backend()=='cpu')[0],max_executables=32)
|
| 12 |
+
def predict(self,root,record,group_record,packed,num_detectors,batch=None):
|
| 13 |
+
settings=record.get('d3_latent_readout')
|
| 14 |
+
if settings is None:
|
| 15 |
+
if batch is None:return super().predict(root,record,group_record,packed,num_detectors)
|
| 16 |
+
return super().predict(root,record,group_record,packed,num_detectors,batch)
|
| 17 |
+
if batch is None:batch=256
|
| 18 |
+
import jax.numpy as jnp
|
| 19 |
+
key=(settings['weights'],settings['group'])
|
| 20 |
+
if key not in self.latent_weights:
|
| 21 |
+
with np.load(root/settings['weights'],allow_pickle=False) as f:self.latent_weights[key]=jnp.asarray(f[settings['group']])
|
| 22 |
+
group=settings['group']
|
| 23 |
+
if group not in self.latent_groups:
|
| 24 |
+
weights=[];coefficients=[]
|
| 25 |
+
for member in group_record.get('members',[group_record]):
|
| 26 |
+
with np.load(root/member['weights'],allow_pickle=False) as f:weights.append({k:jnp.asarray(f[k]) for k in f.files})
|
| 27 |
+
coefficients.append(member.get('coefficient',1.))
|
| 28 |
+
coefficients=np.asarray(coefficients,np.float32);coefficients/=coefficients.sum()
|
| 29 |
+
self.latent_groups[group]=({k:jnp.stack([w[k] for w in weights]) for k in weights[0]},coefficients)
|
| 30 |
+
gp=settings['geometry']
|
| 31 |
+
if gp not in self.latent_plans:
|
| 32 |
+
with np.load(root/record['rich_plan'],allow_pickle=False) as f:plan={k:f[k] for k in f.files}
|
| 33 |
+
with np.load(root/gp,allow_pickle=False) as f:geometry={k:f[k] for k in f.files}
|
| 34 |
+
self.latent_plans[gp]=(plan,geometry)
|
| 35 |
+
plan,geometry=self.latent_plans[gp];frozen,coefficients=self.latent_groups[group]
|
| 36 |
+
ds=np.pad(np.unpackbits(packed,axis=1,count=num_detectors,bitorder='little'),((0,0),(0,201-num_detectors)));values=[]
|
| 37 |
+
for pos in range(0,len(ds),batch):
|
| 38 |
+
n=min(batch,len(ds)-pos);dets=np.pad(ds[pos:pos+batch],((0,batch-n),(0,0)))
|
| 39 |
+
q=self.latent_infer(self.latent_weights[key],frozen,dets,coefficients,np.ones(batch,np.float32),np.zeros(batch,np.float32),
|
| 40 |
+
*[plan[k] for k in ['context','static','base_logits','valid','masks','measured','grid','measurement_indices','counts']],geometry['quality_times'],geometry['transition_gaps'])
|
| 41 |
+
values.append(np.asarray(q)[:n])
|
| 42 |
+
return np.concatenate(values).astype(np.float32)
|
tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S044/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/S044/training_code.py
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Fit matching ensemble from random coefficients using the hardware training split."""
|
| 2 |
+
import os
|
| 3 |
+
os.environ['OPENBLAS_NUM_THREADS'] = '1'
|
| 4 |
+
os.environ['OMP_NUM_THREADS'] = '1'
|
| 5 |
+
from concurrent.futures import ProcessPoolExecutor, as_completed
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
import json, time, hashlib, shutil, importlib.metadata
|
| 8 |
+
import numpy as np
|
| 9 |
+
import stim
|
| 10 |
+
from scipy.optimize import minimize
|
| 11 |
+
from scipy.special import expit
|
| 12 |
+
from decoder import match_features, predict_features
|
| 13 |
+
|
| 14 |
+
ROOT = Path(__file__).resolve().parent
|
| 15 |
+
DATA = Path('/workspace/data')
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def features(row):
|
| 19 |
+
path = ROOT/'cache'/f"{row['name']}.npz"
|
| 20 |
+
if path.exists():
|
| 21 |
+
return row['name']
|
| 22 |
+
dem = stim.DetectorErrorModel.from_file(DATA/'train'/row['noise'])
|
| 23 |
+
content = {}
|
| 24 |
+
for split in ('train', 'validation'):
|
| 25 |
+
with np.load(DATA/split/row['arrays'], allow_pickle=False) as a:
|
| 26 |
+
content[split+'_x'] = match_features(dem, a['detectors'], row['rounds'])
|
| 27 |
+
content[split+'_y'] = a['labels']
|
| 28 |
+
np.savez(path, **content)
|
| 29 |
+
return row['name']
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def main():
|
| 33 |
+
start = time.time()
|
| 34 |
+
rows = json.loads((DATA/'train/manifest.json').read_text())['conditions']
|
| 35 |
+
(ROOT/'cache').mkdir(exist_ok=True)
|
| 36 |
+
with ProcessPoolExecutor(max_workers=16) as pool:
|
| 37 |
+
futures = [pool.submit(features, row) for row in rows]
|
| 38 |
+
for i, future in enumerate(as_completed(futures)):
|
| 39 |
+
print(json.dumps({'features_done': i+1, 'condition': future.result(), 'seconds': time.time()-start}), flush=True)
|
| 40 |
+
pkg = ROOT/'package'
|
| 41 |
+
pkg.mkdir(exist_ok=True)
|
| 42 |
+
(pkg/'weights').mkdir(exist_ok=True)
|
| 43 |
+
(pkg/'dems').mkdir(exist_ok=True)
|
| 44 |
+
config = {'architecture': 'per-group logistic ensemble of MWPM, correlated MWPM, and two constrained logical cosets',
|
| 45 |
+
'feature_version': 1, 'groups': {}, 'conditions': {}}
|
| 46 |
+
history = []
|
| 47 |
+
for group in sorted({r['group'] for r in rows}):
|
| 48 |
+
members = [r for r in rows if r['group'] == group]
|
| 49 |
+
cache = [np.load(ROOT/'cache'/f"{r['name']}.npz") for r in members]
|
| 50 |
+
x = np.concatenate([a['train_x'] for a in cache]).astype(np.float64)
|
| 51 |
+
y = np.concatenate([a['train_y'] for a in cache]).astype(np.float64)
|
| 52 |
+
vx = np.concatenate([a['validation_x'] for a in cache]).astype(np.float64)
|
| 53 |
+
vy = np.concatenate([a['validation_y'] for a in cache])
|
| 54 |
+
scale = np.maximum(np.sqrt(np.mean(x*x, axis=0)), 0.01)
|
| 55 |
+
x /= scale
|
| 56 |
+
rng = np.random.default_rng(20261021)
|
| 57 |
+
initial = rng.normal(0, 0.01, x.shape[1])
|
| 58 |
+
def objective(w):
|
| 59 |
+
z = x @ w
|
| 60 |
+
loss = np.mean(np.logaddexp(0, z)-y*z) + 1e-5*np.sum(w*w)
|
| 61 |
+
grad = x.T @ (expit(z)-y)/len(y) + 2e-5*w
|
| 62 |
+
return loss, grad
|
| 63 |
+
fit = minimize(objective, initial, jac=True, method='L-BFGS-B', options={'maxiter': 300, 'ftol': 1e-12})
|
| 64 |
+
state = {'coef': fit.x.astype(np.float32), 'scale': scale.astype(np.float32)}
|
| 65 |
+
p = predict_features(vx, state)
|
| 66 |
+
metrics = {'group': group, 'train_loss': float(fit.fun), 'iterations': int(fit.nit),
|
| 67 |
+
'failure': float(np.mean((p>=.5)!=vy)),
|
| 68 |
+
'plain_failure': float(np.mean((vx[:,2]>0)!=vy)),
|
| 69 |
+
'correlated_failure': float(np.mean((vx[:,3]>0)!=vy)),
|
| 70 |
+
'coset_failure': float(np.mean((vx[:,1]>0)!=vy)),
|
| 71 |
+
'optimizer_success': bool(fit.success)}
|
| 72 |
+
history.append(metrics)
|
| 73 |
+
print(json.dumps(metrics), flush=True)
|
| 74 |
+
np.savez(pkg/'weights'/f'{group}.npz', **state)
|
| 75 |
+
config['groups'][group] = f'weights/{group}.npz'
|
| 76 |
+
for row in rows:
|
| 77 |
+
target = f"dems/{row['name']}.dem"
|
| 78 |
+
shutil.copyfile(DATA/'train'/row['noise'], pkg/target)
|
| 79 |
+
config['conditions'][row['name']] = {'dem': target, 'circuit_sha256': row['circuit_sha256']}
|
| 80 |
+
shutil.copyfile(ROOT/'decoder.py', pkg/'decoder.py')
|
| 81 |
+
shutil.copyfile(ROOT/'train.py', pkg/'training_code.py')
|
| 82 |
+
(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')
|
| 83 |
+
(pkg/'infer.sh').chmod(0o755)
|
| 84 |
+
(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')
|
| 85 |
+
deps = ['numpy', 'scipy', 'stim', 'pymatching']
|
| 86 |
+
(pkg/'requirements.lock').write_text('\n'.join(f'{d}=={importlib.metadata.version(d)}' for d in deps)+'\n')
|
| 87 |
+
sha = lambda p: hashlib.sha256(p.read_bytes()).hexdigest()
|
| 88 |
+
provenance = {'initialization': {'distribution': 'Normal(0,0.01)', 'seed': 20261021, 'pretrained_weights': False},
|
| 89 |
+
'training_data': 'all 19880 supplied training shots per condition; all 130 conditions',
|
| 90 |
+
'train_manifest_sha256': sha(DATA/'train/manifest.json'),
|
| 91 |
+
'validation_manifest_sha256': sha(DATA/'validation/manifest.json'),
|
| 92 |
+
'calibration_exception': 'Supplied even-fitted DEMs include validation syndromes but no logical labels or test data.',
|
| 93 |
+
'optimizer': 'L-BFGS-B binary cross entropy plus 1e-5 L2, maximum 300 iterations',
|
| 94 |
+
'selection': 'First trained candidate; validation reported without parameter fitting or hyperparameter selection',
|
| 95 |
+
'test_data_used': False, 'released_per_shot_predictions_used': False,
|
| 96 |
+
'history': history, 'elapsed_seconds': time.time()-start}
|
| 97 |
+
for name, obj in [('model_config.json', config), ('training_provenance.json', provenance)]:
|
| 98 |
+
(pkg/name).write_text(json.dumps(obj, indent=2)+'\n')
|
| 99 |
+
checkpoints = [{'path': str(p.relative_to(pkg)), 'sha256': sha(p), 'format': 'npz' if p.suffix=='.npz' else 'stim-dem'}
|
| 100 |
+
for p in sorted((pkg/'weights').glob('*'))+sorted((pkg/'dems').glob('*'))]
|
| 101 |
+
(pkg/'model_manifest.json').write_text(json.dumps({'schema': 'surface-code-decoding-model/v1', 'checkpoints': checkpoints,
|
| 102 |
+
'model_config': 'model_config.json', 'training_provenance': 'training_provenance.json'}, indent=2)+'\n')
|
| 103 |
+
p = 1-np.mean([np.mean([h['failure'] for h in history if h['group'].startswith(d)]) for d in ['d3', 'd5']])
|
| 104 |
+
print(json.dumps({'P': p, 'package': str(pkg), 'seconds': time.time()-start}), flush=True)
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
if __name__ == '__main__':
|
| 108 |
+
main()
|
tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S044/training_sources/axial_residual1/data.py
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Authorized data and frozen, session-trained parent probabilities."""
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
import hashlib,json
|
| 4 |
+
import numpy as np
|
| 5 |
+
|
| 6 |
+
ROOT=Path(__file__).resolve().parent
|
| 7 |
+
RESEARCH=ROOT.parent
|
| 8 |
+
|
| 9 |
+
def digest(path):
|
| 10 |
+
return hashlib.sha256(Path(path).read_bytes()).hexdigest()
|
| 11 |
+
|
| 12 |
+
def reference():
|
| 13 |
+
info=json.loads((ROOT/'reference.json').read_text());package=Path(info['package'])
|
| 14 |
+
for name,sha in info['sha256'].items():assert digest(package/name)==sha,name
|
| 15 |
+
return info,package,json.loads((package/'model_config.json').read_text())
|
| 16 |
+
|
| 17 |
+
def aligned(path,ids):
|
| 18 |
+
with np.load(path,allow_pickle=False) as saved:
|
| 19 |
+
assert set(saved.files)=={'sample_ids','probabilities'}
|
| 20 |
+
source_ids=saved['sample_ids'];q=saved['probabilities']
|
| 21 |
+
assert source_ids.dtype==np.uint64 and len(np.unique(source_ids))==len(source_ids)
|
| 22 |
+
order=np.argsort(source_ids);locations=np.searchsorted(source_ids[order],ids)
|
| 23 |
+
assert np.all(locations<len(order))
|
| 24 |
+
indices=order[locations];assert np.array_equal(source_ids[indices],ids)
|
| 25 |
+
q=q[indices];assert q.dtype==np.float32 and np.isfinite(q).all() and ((q>=0)&(q<=1)).all()
|
| 26 |
+
return q
|
| 27 |
+
|
| 28 |
+
def load_all(splits=('train','validation'),cache=None):
|
| 29 |
+
cache=ROOT/'cache1' if cache is None else Path(cache)
|
| 30 |
+
info,package,config=reference();items=[]
|
| 31 |
+
manifests={s:json.loads((Path('/workspace/data')/s/'manifest.json').read_text()) for s in splits}
|
| 32 |
+
rows=sorted([r for r in json.loads(Path('/workspace/data/train/manifest.json').read_text())['conditions'] if r['distance']==5],key=lambda r:r['name'])
|
| 33 |
+
for row in rows:
|
| 34 |
+
path=package/config['conditions'][row['name']]['neural_d5_plan']
|
| 35 |
+
with np.load(path,allow_pickle=False) as plan:grid=plan['grid'].copy()
|
| 36 |
+
assert grid.shape==(26,24) and np.array_equal(np.sort(grid[grid!=600]),np.arange(row['num_detectors']))
|
| 37 |
+
item={'row':row,'grid':grid,'feature_plan_sha256':digest(path)}
|
| 38 |
+
for split in splits:
|
| 39 |
+
record=next(r for r in manifests[split]['conditions'] if r['name']==row['name'])
|
| 40 |
+
with np.load(Path('/workspace/data')/split/record['arrays'],allow_pickle=False) as saved:
|
| 41 |
+
ids=saved['sample_ids'];labels=saved['labels'];packed=saved['detectors']
|
| 42 |
+
source=(cache if split=='train' else Path(info['predictions']))/(row['name']+'.npz')
|
| 43 |
+
q=aligned(source,ids)
|
| 44 |
+
detectors=np.unpackbits(packed,axis=1,count=row['num_detectors'],bitorder='little')
|
| 45 |
+
item[split+'_dets']=np.pad(detectors,((0,0),(0,601-row['num_detectors'])))
|
| 46 |
+
item[split+'_parent']=q;item[split+'_labels']=labels;item[split+'_sample_ids']=ids
|
| 47 |
+
item[split+'_reference']={'file':str(source),'file_sha256':digest(source),'input_arrays_sha256':record['arrays_sha256'],
|
| 48 |
+
'sample_ids_sha256':hashlib.sha256(ids.tobytes()).hexdigest(),'alignment':'Opaque sample ID equality join, with uniqueness and membership assertions'}
|
| 49 |
+
items.append(item)
|
| 50 |
+
assert len(items)==26
|
| 51 |
+
return items
|
tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S044/training_sources/axial_residual1/model.py
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Untrained axial-attention residual over a frozen session-trained decoder."""
|
| 2 |
+
import jax
|
| 3 |
+
import jax.numpy as jnp
|
| 4 |
+
|
| 5 |
+
DEFAULT={'width':64,'heads':4,'depth':3,'expansion':2,'dropout':.1,'correction_bound':4.}
|
| 6 |
+
|
| 7 |
+
def initialize(seed,config=None):
|
| 8 |
+
c=DEFAULT if config is None else config;d=c['width'];params={};key=jax.random.key(seed)
|
| 9 |
+
def random(shape,scale):
|
| 10 |
+
nonlocal key
|
| 11 |
+
key,sub=jax.random.split(key);return jax.random.normal(sub,shape)*scale
|
| 12 |
+
params['input_w']=random((8,d),jnp.sqrt(1/8));params['input_b']=jnp.zeros(d)
|
| 13 |
+
params['space_embedding']=random((24,d),.02);params['time_embedding']=random((26,d),.02)
|
| 14 |
+
for i in range(c['depth']):
|
| 15 |
+
for axis in ['time','space']:
|
| 16 |
+
prefix=f'b{i}_{axis}'
|
| 17 |
+
params[prefix+'_scale']=jnp.ones(d);params[prefix+'_bias']=jnp.zeros(d)
|
| 18 |
+
params[prefix+'_qkv']=random((d,3*d),jnp.sqrt(1/d));params[prefix+'_qkv_b']=jnp.zeros(3*d)
|
| 19 |
+
params[prefix+'_out']=random((d,d),jnp.sqrt(1/d));params[prefix+'_out_b']=jnp.zeros(d)
|
| 20 |
+
prefix=f'b{i}_ff';hidden=d*c['expansion']
|
| 21 |
+
params[prefix+'_scale']=jnp.ones(d);params[prefix+'_bias']=jnp.zeros(d)
|
| 22 |
+
params[prefix+'_w1']=random((d,hidden),jnp.sqrt(1/d));params[prefix+'_b1']=jnp.zeros(hidden)
|
| 23 |
+
params[prefix+'_w2']=random((hidden,d),jnp.sqrt(1/hidden));params[prefix+'_b2']=jnp.zeros(d)
|
| 24 |
+
params['readout_scale']=jnp.ones(d);params['readout_bias']=jnp.zeros(d)
|
| 25 |
+
params['readout_w1']=random((d+2,d),jnp.sqrt(1/(d+2)));params['readout_b1']=jnp.zeros(d)
|
| 26 |
+
params['readout_w2']=jnp.zeros((d,1));params['readout_b2']=jnp.zeros(1)
|
| 27 |
+
return params
|
| 28 |
+
|
| 29 |
+
def parent_logit(probability):
|
| 30 |
+
p=jnp.clip(probability,1e-7,1-1e-7)
|
| 31 |
+
return jnp.log(p)-jnp.log1p(-p)
|
| 32 |
+
|
| 33 |
+
def token_features(dets,grid,basis,rounds,parent):
|
| 34 |
+
valid=grid!=600;events=dets[:,grid].astype(jnp.float32)*valid[None]
|
| 35 |
+
measured=(jnp.cumsum(events.astype(jnp.int32),axis=1)&1).astype(jnp.float32)
|
| 36 |
+
shape=events.shape
|
| 37 |
+
broadcast=lambda v:jnp.broadcast_to(v,shape)
|
| 38 |
+
z=jnp.clip(parent_logit(parent),-8.,8.)/8
|
| 39 |
+
return jnp.stack([events,measured,broadcast(valid[None]),broadcast(jnp.arange(26)[None,:,None]/25),
|
| 40 |
+
broadcast(jnp.asarray(basis,jnp.float32)),broadcast(jnp.asarray(rounds,jnp.float32)/25),
|
| 41 |
+
broadcast(z[:,None,None]),broadcast(jnp.abs(z)[:,None,None])],axis=-1),valid
|
| 42 |
+
|
| 43 |
+
def layer_norm(x,scale,bias):
|
| 44 |
+
mean=x.mean(axis=-1,keepdims=True);variance=jnp.mean((x-mean)**2,axis=-1,keepdims=True)
|
| 45 |
+
return (x-mean)*jax.lax.rsqrt(variance+1e-5)*scale+bias
|
| 46 |
+
|
| 47 |
+
def dropout(x,key,rate,training):
|
| 48 |
+
if not training or rate==0:return x
|
| 49 |
+
keep=1-rate;return jnp.where(jax.random.bernoulli(key,keep,x.shape),x/keep,0.)
|
| 50 |
+
|
| 51 |
+
def attention(parameters,prefix,x,valid,axis,heads):
|
| 52 |
+
# Reshape each temporal/spatial line into its own attention group.
|
| 53 |
+
if axis=='time':x=jnp.swapaxes(x,1,2);valid=valid.T
|
| 54 |
+
batch,groups,length,width=x.shape;head_width=width//heads
|
| 55 |
+
qkv=x@parameters[prefix+'_qkv']+parameters[prefix+'_qkv_b']
|
| 56 |
+
q,k,v=[part.reshape(batch,groups,length,heads,head_width) for part in jnp.split(qkv,3,axis=-1)]
|
| 57 |
+
score=jnp.einsum('bgihd,bgjhd->bghij',q,k)/jnp.sqrt(jnp.float32(head_width))
|
| 58 |
+
score=jnp.where(valid[None,:,None,None,:],score,-1e9)
|
| 59 |
+
weights=jax.nn.softmax(score,axis=-1)
|
| 60 |
+
value=jnp.einsum('bghij,bgjhd->bgihd',weights,v).reshape(batch,groups,length,width)
|
| 61 |
+
value=(value@parameters[prefix+'_out']+parameters[prefix+'_out_b'])*valid[None,:,:,None]
|
| 62 |
+
return jnp.swapaxes(value,1,2) if axis=='time' else value
|
| 63 |
+
|
| 64 |
+
def logits(parameters,dets,grid,basis,rounds,parent,*,training=False,key=None,config=None):
|
| 65 |
+
c=DEFAULT if config is None else config
|
| 66 |
+
features,valid=token_features(dets,grid,basis,rounds,parent);mask=valid[None,:,:,None]
|
| 67 |
+
x=(features@parameters['input_w']+parameters['input_b']+parameters['space_embedding'][None,None]+parameters['time_embedding'][None,:,None])*mask
|
| 68 |
+
if key is None:key=jax.random.key(0)
|
| 69 |
+
keys=jax.random.split(key,3*c['depth'])
|
| 70 |
+
for i in range(c['depth']):
|
| 71 |
+
for rank,axis in enumerate(['time','space']):
|
| 72 |
+
prefix=f'b{i}_{axis}';normalized=layer_norm(x,parameters[prefix+'_scale'],parameters[prefix+'_bias'])
|
| 73 |
+
update=attention(parameters,prefix,normalized,valid,axis,c['heads'])
|
| 74 |
+
x=(x+dropout(update,keys[3*i+rank],c['dropout'],training))*mask
|
| 75 |
+
prefix=f'b{i}_ff';normalized=layer_norm(x,parameters[prefix+'_scale'],parameters[prefix+'_bias'])
|
| 76 |
+
update=jax.nn.gelu(normalized@parameters[prefix+'_w1']+parameters[prefix+'_b1'])@parameters[prefix+'_w2']+parameters[prefix+'_b2']
|
| 77 |
+
x=(x+dropout(update,keys[3*i+2],c['dropout'],training))*mask
|
| 78 |
+
x=layer_norm(x,parameters['readout_scale'],parameters['readout_bias'])*mask
|
| 79 |
+
pooled=x.sum(axis=(1,2))/jnp.maximum(valid.sum(),1)
|
| 80 |
+
base=parent_logit(parent);z=jnp.clip(base,-8,8)/8
|
| 81 |
+
hidden=jax.nn.silu(jnp.concatenate([pooled,z[:,None],jnp.abs(z)[:,None]],axis=1)@parameters['readout_w1']+parameters['readout_b1'])
|
| 82 |
+
correction=c['correction_bound']*jnp.tanh((hidden@parameters['readout_w2']+parameters['readout_b2'])[:,0])
|
| 83 |
+
return base+correction
|
| 84 |
+
|
| 85 |
+
def predict(parameters,dets,grid,basis,rounds,parent,config=None):
|
| 86 |
+
return jax.nn.sigmoid(logits(parameters,dets,grid,basis,rounds,parent,config=config))
|
| 87 |
+
|
| 88 |
+
def binary_loss(logit,labels):
|
| 89 |
+
return jnp.mean(jax.nn.softplus(logit)-labels*logit)
|
tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S044/training_sources/axial_residual1/state.py
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Numeric-only checkpoint state for a newly initialized residual model."""
|
| 2 |
+
import numpy as np
|
| 3 |
+
import jax
|
| 4 |
+
import jax.numpy as jnp
|
| 5 |
+
import optax
|
| 6 |
+
|
| 7 |
+
def save_state(path,state):
|
| 8 |
+
np.savez(path,**{f'arr_{i}':np.asarray(v) for i,v in enumerate(jax.tree_util.tree_leaves(state))})
|
| 9 |
+
|
| 10 |
+
def load_state(path,template):
|
| 11 |
+
leaves,tree=jax.tree_util.tree_flatten(template);values=[]
|
| 12 |
+
with np.load(path,allow_pickle=False) as saved:
|
| 13 |
+
assert set(saved.files)=={f'arr_{i}' for i in range(len(leaves))}
|
| 14 |
+
for i,v in enumerate(leaves):
|
| 15 |
+
a=saved[f'arr_{i}'];assert a.shape==v.shape and a.dtype==v.dtype
|
| 16 |
+
values.append(jnp.asarray(a))
|
| 17 |
+
return jax.tree_util.tree_unflatten(tree,values)
|
| 18 |
+
|
| 19 |
+
def optimizer(learning_rate,total_steps=4096):
|
| 20 |
+
schedule=optax.warmup_cosine_decay_schedule(learning_rate/128,learning_rate,128,total_steps,end_value=learning_rate*.1)
|
| 21 |
+
return optax.chain(optax.clip_by_global_norm(1.),optax.adamw(schedule,weight_decay=1e-4))
|
| 22 |
+
|
| 23 |
+
def make_step(architecture,optim,dropout_seed):
|
| 24 |
+
from model import logits,binary_loss
|
| 25 |
+
def objective(p,dets,grid,basis,rounds,parent,y,step):
|
| 26 |
+
key=jax.random.fold_in(jax.random.key(dropout_seed),step)
|
| 27 |
+
z=logits(p,dets,grid,basis,rounds,parent,training=True,key=key,config=architecture)
|
| 28 |
+
return binary_loss(z,y),jnp.mean((z>=0)!=y)
|
| 29 |
+
@jax.jit
|
| 30 |
+
def update(p,state,dets,grid,basis,rounds,parent,y,step):
|
| 31 |
+
(loss,error),gradient=jax.value_and_grad(objective,has_aux=True)(p,dets,grid,basis,rounds,parent,y,step)
|
| 32 |
+
updates,state=optim.update(gradient,state,p)
|
| 33 |
+
return optax.apply_updates(p,updates),state,loss,error,optax.global_norm(gradient)
|
| 34 |
+
return update
|
tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S044/training_sources/axial_residual1/train.py
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Fresh axial attention over a frozen session-trained parent; all d5 conditions."""
|
| 2 |
+
import os
|
| 3 |
+
os.environ['OPENBLAS_NUM_THREADS']='1';os.environ['OMP_NUM_THREADS']='1';os.environ['XLA_PYTHON_CLIENT_PREALLOCATE']='false'
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
import argparse,hashlib,json,shutil,time
|
| 6 |
+
import numpy as np
|
| 7 |
+
import jax
|
| 8 |
+
import jax.numpy as jnp
|
| 9 |
+
from data import load_all,reference,digest
|
| 10 |
+
from model import initialize,predict,DEFAULT
|
| 11 |
+
from state import save_state,load_state,optimizer,make_step
|
| 12 |
+
|
| 13 |
+
def main():
|
| 14 |
+
parser=argparse.ArgumentParser();parser.add_argument('--output',type=Path,required=True);parser.add_argument('--cache',type=Path)
|
| 15 |
+
parser.add_argument('--resume',type=Path);parser.add_argument('--steps',type=int,default=4096);parser.add_argument('--batch',type=int,default=256)
|
| 16 |
+
parser.add_argument('--learning-rate',type=float,default=.0002);parser.add_argument('--schedule-steps',type=int,default=4096)
|
| 17 |
+
parser.add_argument('--initial-seed',type=int,default=20261800);parser.add_argument('--seed',type=int,default=20261801);parser.add_argument('--dropout-seed',type=int,default=20261802)
|
| 18 |
+
parser.add_argument('--eval-every',type=int,default=512);parser.add_argument('--validation-shots',type=int,default=1024);parser.add_argument('--validation-batch',type=int,default=256)
|
| 19 |
+
args=parser.parse_args();args.output.mkdir(exist_ok=False);root=Path(__file__).resolve().parent
|
| 20 |
+
config={k:str(v) if isinstance(v,Path) else v for k,v in vars(args).items()};config['architecture']=DEFAULT
|
| 21 |
+
source=args.output/'training_source';source.mkdir();hashes={}
|
| 22 |
+
for name in ['model.py','data.py','state.py','train.py']:
|
| 23 |
+
shutil.copyfile(root/name,source/name);hashes[name]=digest(root/name)
|
| 24 |
+
parameters=initialize(args.initial_seed);optim=optimizer(args.learning_rate,args.schedule_steps);state=optim.init(parameters)
|
| 25 |
+
rng=np.random.default_rng(args.seed);start_step=0;dataset=load_all(cache=args.cache);seen=[np.zeros(len(x['train_labels']),bool) for x in dataset]
|
| 26 |
+
if args.resume:
|
| 27 |
+
previous=json.loads((args.resume.parent/'run_config.json').read_text())
|
| 28 |
+
for name in ['batch','learning_rate','schedule_steps','initial_seed','seed','dropout_seed','architecture']:assert config[name]==previous[name],name
|
| 29 |
+
start_step=int(args.resume.stem.split('-')[-1]);assert start_step<args.steps
|
| 30 |
+
with np.load(args.resume,allow_pickle=False) as saved:
|
| 31 |
+
assert set(saved.files)==set(parameters)
|
| 32 |
+
for k,v in parameters.items():assert saved[k].shape==v.shape and saved[k].dtype==v.dtype
|
| 33 |
+
parameters={k:jnp.asarray(saved[k]) for k in parameters}
|
| 34 |
+
state=load_state(args.resume.with_name(f'optimizer-{start_step}.npz'),state)
|
| 35 |
+
rng.bit_generator.state=json.loads(args.resume.with_name(f'rng-{start_step}.json').read_text())
|
| 36 |
+
with np.load(args.resume.with_name(f'seen-{start_step}.npz'),allow_pickle=False) as saved:
|
| 37 |
+
seen=[saved[item['row']['name']] for item in dataset]
|
| 38 |
+
assert int(state[1][0].count)==start_step
|
| 39 |
+
config.update(training_source_sha256=hashes,parameter_count=sum(v.size for v in parameters.values()),initial_adam_count=start_step,
|
| 40 |
+
initialization='Session random initialization, zero output; frozen parent trained in the same session. Resume restores exact weights, Adam, RNG and seen masks.',
|
| 41 |
+
dropout_keys='fold_in(JAX key(dropout_seed), absolute update number)',runtime_versions={'jax':jax.__version__,'numpy':np.__version__})
|
| 42 |
+
(args.output/'run_config.json').write_text(json.dumps(config,indent=2)+'\n')
|
| 43 |
+
update=make_step(DEFAULT,optim,args.dropout_seed);infer=jax.jit(predict);started=time.time();records=[]
|
| 44 |
+
print(json.dumps({'conditions':len(dataset),'training_rows':sum(len(x['train_labels']) for x in dataset),'start_step':start_step}),flush=True)
|
| 45 |
+
def evaluate(step):
|
| 46 |
+
rows=[];beginning=time.time()
|
| 47 |
+
for item in dataset:
|
| 48 |
+
row=item['row'];n=min(args.validation_shots,len(item['validation_labels']))
|
| 49 |
+
ix=np.random.default_rng(20261102).choice(len(item['validation_labels']),n,replace=False);values=[]
|
| 50 |
+
for start in range(0,n,args.validation_batch):
|
| 51 |
+
selected=ix[start:start+args.validation_batch];size=len(selected)
|
| 52 |
+
ds=np.pad(item['validation_dets'][selected],((0,args.validation_batch-size),(0,0)))
|
| 53 |
+
parent=np.pad(item['validation_parent'][selected],(0,args.validation_batch-size),constant_values=.5)
|
| 54 |
+
values.append(np.asarray(infer(parameters,ds,item['grid'],row['basis']=='X',row['rounds'],parent))[:size])
|
| 55 |
+
q=np.concatenate(values);y=item['validation_labels'][ix].astype(np.float64);qq=np.clip(q.astype(np.float64),1e-7,1-1e-7)
|
| 56 |
+
assert np.isfinite(q).all() and ((q>=0)&(q<=1)).all()
|
| 57 |
+
rows.append({'condition':row['name'],'failure':float(np.mean((q>=.5)!=y)),
|
| 58 |
+
'negative_log_likelihood':float(np.mean(-y*np.log(qq)-(1-y)*np.log1p(-qq)))})
|
| 59 |
+
report={'step':step,'validation_failure':float(np.mean([x['failure'] for x in rows])),
|
| 60 |
+
'negative_log_likelihood':float(np.mean([x['negative_log_likelihood'] for x in rows])),'conditions':rows,'seconds':time.time()-beginning}
|
| 61 |
+
np.savez(args.output/f'weights-{step}.npz',**{k:np.asarray(v) for k,v in parameters.items()});save_state(args.output/f'optimizer-{step}.npz',state)
|
| 62 |
+
np.savez(args.output/f'seen-{step}.npz',**{item['row']['name']:mask for item,mask in zip(dataset,seen)})
|
| 63 |
+
(args.output/f'rng-{step}.json').write_text(json.dumps(rng.bit_generator.state)+'\n')
|
| 64 |
+
checkpoint={'step':step,'training_draws':step*args.batch,'distinct_rows':sum(int(x.sum()) for x in seen),
|
| 65 |
+
'distinct_by_condition':{item['row']['name']:int(mask.sum()) for item,mask in zip(dataset,seen)},
|
| 66 |
+
'adam_count':int(state[1][0].count),'weights_sha256':digest(args.output/f'weights-{step}.npz'),'complete':True}
|
| 67 |
+
assert checkpoint['adam_count']==step
|
| 68 |
+
(args.output/f'checkpoint-{step}.json').write_text(json.dumps(checkpoint,indent=2)+'\n')
|
| 69 |
+
(args.output/f'validation-{step}.json').write_text(json.dumps(report,indent=2)+'\n')
|
| 70 |
+
print(json.dumps({k:v for k,v in report.items() if k!='conditions'}),flush=True)
|
| 71 |
+
evaluate(start_step)
|
| 72 |
+
for step in range(start_step+1,args.steps+1):
|
| 73 |
+
ci=int(rng.integers(len(dataset)));item=dataset[ci];row=item['row'];ix=rng.integers(len(item['train_labels']),size=args.batch);seen[ci][ix]=True
|
| 74 |
+
parameters,state,loss,error,norm=update(parameters,state,item['train_dets'][ix],item['grid'],row['basis']=='X',row['rounds'],item['train_parent'][ix],item['train_labels'][ix],step)
|
| 75 |
+
if step==start_step+1 or step%32==0:
|
| 76 |
+
record={'step':step,'loss':float(loss),'error':float(error),'gradient_norm':float(norm),'elapsed':time.time()-started}
|
| 77 |
+
assert np.isfinite(record['loss']) and np.isfinite(record['gradient_norm']);records.append(record);print(json.dumps(record),flush=True)
|
| 78 |
+
if step%args.eval_every==0 or step==args.steps:evaluate(step)
|
| 79 |
+
provenance={'run_config':config,'frozen_parent':reference()[0],'training_rows':sum(len(x['train_labels']) for x in dataset),
|
| 80 |
+
'data_references':{x['row']['name']:{'feature_plan_sha256':x['feature_plan_sha256'],'train':x['train_reference'],'validation':x['validation_reference']} for x in dataset},
|
| 81 |
+
'training':'Uniform condition/row sampling over all516880supplied d5training rows; binary logical BCE and dropout. Parent parameters frozen.',
|
| 82 |
+
'loss':'Logical observable BCE on parent logit plus bounded4tanh learned correction',
|
| 83 |
+
'validation':'Seed20261102 per-condition screens; full supplied validation required for checkpoint selection',
|
| 84 |
+
'test_data_used':False,'records':records,'seconds':time.time()-started}
|
| 85 |
+
(args.output/'provenance.json').write_text(json.dumps(provenance,indent=2)+'\n')
|
| 86 |
+
|
| 87 |
+
if __name__=='__main__':main()
|
tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S044/training_sources/beam_calibration1/FIT_SOURCE_LOCK.json
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"created_utc": "2026-10-21T20:25:33.650374+00:00",
|
| 3 |
+
"source_sha256": {
|
| 4 |
+
"beam_calibration/core.py": "6cc89f9e5a3143564c57f8a79c7ea6e1d1cd5b2612dacfd5a52b58b6bcde41c7",
|
| 5 |
+
"beam_calibration/fit.py": "bb494e78078963e81f287dcd0925ce4c071276e791b1902202a17d7a028a2f41",
|
| 6 |
+
"beam_calibration/control_cpu.py": "8e7dcb714f5e5ca8a1d86188fc24d569bd0456d65a42a86f8e7a1bd56a6a0f8f",
|
| 7 |
+
"beam_calibration/plan.json": "6a16f161a24d54c05afe10004f0d6f119aa3879394195d63f9d1ce65830b52c1",
|
| 8 |
+
"beam_calibration/generate_beam_training.py": "b7d8aabc20b10577500518002df566b789b65fa5da398584e8d35185892ce41f",
|
| 9 |
+
"beam_calibration/generate_parent_training.py": "c8c11132e5eb98cae6e71936cdeba4a90211fe1cdc03dd63e5b7982f49d87073",
|
| 10 |
+
"full_frontier/beam_lookahead.py": "557ea3eef701c480b90896cda3e8f69e263bc852fcce805f054a90e43d7cffe5",
|
| 11 |
+
"beam_r3/reference.json": "9f0bbe90c63da1d9a13a27b9ecb61b07d689c64cc41055ba2c812e5b013c2701"
|
| 12 |
+
},
|
| 13 |
+
"scope": "Frozen before any beam_calibration hardware-label fitting. Evidence generation is in progress; fits await and audit both complete caches.",
|
| 14 |
+
"test_data_used": false
|
| 15 |
+
}
|
tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S044/training_sources/beam_calibration1/PACKAGE_SOURCE_LOCK.json
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"created_utc": "2026-10-21T20:27:57.623048+00:00",
|
| 3 |
+
"queue_after": "full_frontier/resource_finished.json",
|
| 4 |
+
"source_sha256": {
|
| 5 |
+
"beam_calibration/runtime.py": "a3e6f859e6d4a350858c47ab362f5716155f3434e25661bb70e8e2896ab228c5",
|
| 6 |
+
"beam_calibration/export.py": "ad0c3d9cdf2897b350e4b9abb44a044bff5a84d81003775d5e7d682571fd2cd4",
|
| 7 |
+
"beam_calibration/runtime_control.py": "f93fe417f7b43a4f95314b84c6102f7a3eba6a4255600409f57555553bb1abc4",
|
| 8 |
+
"beam_calibration/core.py": "6cc89f9e5a3143564c57f8a79c7ea6e1d1cd5b2612dacfd5a52b58b6bcde41c7",
|
| 9 |
+
"beam_calibration/package.py": "7ce80033a384a5943a3e3d877dd7bde023322800871c7aab5aca551871e4c036",
|
| 10 |
+
"beam_calibration/after_resource.py": "cc2fdb0c0d24d46ad7e793913be53100f4969b67af72f3418802fcf1574b89fb",
|
| 11 |
+
"beam_calibration/plan.json": "6a16f161a24d54c05afe10004f0d6f119aa3879394195d63f9d1ce65830b52c1",
|
| 12 |
+
"beam_calibration/FIT_SOURCE_LOCK.json": "05595c096ef729d9981461316c883d106c2e95722b0f0ba1067cea86ff17fad9",
|
| 13 |
+
"full_frontier/beam_jax.py": "45ce979892fad6eaa88325477fb063e6513e635f89370d8a6a9c930f56f09cb1",
|
| 14 |
+
"beam_r3/plans/surface_code_bX_d5_r03_center_5_5.npz": "cc763f0638add95aa03f2b76b5acf8dcceb470de00182d6804366e3bfa0e3f0d",
|
| 15 |
+
"beam_r3/plans/surface_code_bZ_d5_r03_center_5_5.npz": "3a6746481fe2953c4b5b7615b365fccfcee538ff1b8fadc910420fb0f9ba681d"
|
| 16 |
+
},
|
| 17 |
+
"scope": "Portable and packaging code frozen after actual CPU runtime controls, before fitted validation outcomes. GPU work only if a global candidate improves, serialized after the frontier resource study; no original queue reordered.",
|
| 18 |
+
"test_data_used": false
|
| 19 |
+
}
|
tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S044/training_sources/beam_calibration1/QUEUE_AMENDMENT.json
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"created_utc": "2026-10-21T20:43:17.769949+00:00",
|
| 3 |
+
"previous_waiter_pid": 80427,
|
| 4 |
+
"previous_waiter_session": 95715,
|
| 5 |
+
"previous_queue_after": "full_frontier/resource_finished.json",
|
| 6 |
+
"new_queue": "GPUidle gap after completed block_physical resource study and failed/pretraining trajectorycontrol; finish calibrationverificationbeforetrajectoryrestart",
|
| 7 |
+
"reason": "Completed prespecifiedfitselectedparent-onlycalibration (no beam needed); verify strongestcandidate promptly whiletrajectorycontrolrecoveryprepared. Only operational scheduling changes, no training/selection/model changes.",
|
| 8 |
+
"original_source_lock_sha256": "a73ad807bf27cb8c65ed3b06fa287d2ce1fd1206b7a74f867221e35261b4edfa",
|
| 9 |
+
"test_data_used": false
|
| 10 |
+
}
|
tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S044/training_sources/beam_calibration1/after_resource.py
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Publish only after serialized resource work, fitted assessment and actual replay."""
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
import hashlib,json,subprocess,time
|
| 4 |
+
root=Path(__file__).resolve().parent;r=root.parent;started=time.monotonic();report_path=root/'fit1/report.json';marker=r/'full_frontier/resource_finished.json'
|
| 5 |
+
while not report_path.exists():
|
| 6 |
+
if time.monotonic()-started>86400:raise TimeoutError('Calibration did not finish')
|
| 7 |
+
time.sleep(2)
|
| 8 |
+
report=json.loads(report_path.read_text());assert report['status']=='complete';selected=report['selected']
|
| 9 |
+
if selected is None:
|
| 10 |
+
(root/'beam_calibration1_finished.json').write_text(json.dumps({'complete':True,'published':False,'reason':'All six global validation choices failed to improve frozen reference','test_data_used':False})+'\n')
|
| 11 |
+
else:
|
| 12 |
+
while not marker.exists():
|
| 13 |
+
if (r/'full_frontier/resource_failure.json').exists():raise RuntimeError('Prior GPU resource study failed; inspect and recover before advancing queue')
|
| 14 |
+
if time.monotonic()-started>86400:raise TimeoutError('Prior resource study did not complete')
|
| 15 |
+
time.sleep(2)
|
| 16 |
+
assert json.loads(marker.read_text())['complete']
|
| 17 |
+
assert not subprocess.check_output(['nvidia-smi','--query-compute-apps=pid','--format=csv,noheader'],text=True).strip()
|
| 18 |
+
for path,digest in json.loads((root/'PACKAGE_SOURCE_LOCK.json').read_text())['source_sha256'].items():assert hashlib.sha256((r/path).read_bytes()).hexdigest()==digest,path
|
| 19 |
+
for filename in ['control_cpu.json','runtime_control_cpu.json']:
|
| 20 |
+
control=json.loads((root/filename).read_text());assert control['status']=='passed'
|
| 21 |
+
for path,digest in control['source_sha256'].items():
|
| 22 |
+
source=r/path if '/' in path else root/path
|
| 23 |
+
assert hashlib.sha256(source.read_bytes()).hexdigest()==digest,path
|
| 24 |
+
current=json.loads((r/'CURRENT.json').read_text());score=json.loads(Path(current['score']).read_text());gain=sum((score['per_condition'][z['condition']]['errors']/score['per_condition'][z['condition']]['total']-z['failure'])/52 for z in selected['conditions'])
|
| 25 |
+
if gain<=1e-12:
|
| 26 |
+
(root/'beam_calibration1_finished.json').write_text(json.dumps({'complete':True,'published':False,'reason':'Selected global choice no longer improves then-current incumbent','test_data_used':False})+'\n')
|
| 27 |
+
else:
|
| 28 |
+
subprocess.run(['python',str(r/'run_limited.py'),str(root/'runtime_control.py'),'--device','gpu'],check=True)
|
| 29 |
+
subprocess.run(['python',str(root/'package.py')],check=True);out=r/'context_upgrades/beam_calibration1'
|
| 30 |
+
subprocess.run(['python',str(r/'verify_d5_candidate.py'),str(out)],check=True)
|
| 31 |
+
subprocess.run(['python',str(r/'audit_completed_candidate.py'),'--candidate',str(out),'--previous',current['predictions']],check=True)
|
| 32 |
+
done=json.loads((out/'finished.json').read_text());(root/'beam_calibration1_finished.json').write_text(json.dumps({'complete':True,'published':done['published'],'test_data_used':False})+'\n')
|
tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S044/training_sources/beam_calibration1/beam_cpu.py
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Untrained NumPy sparse frontier prototype, capped separately by logical sector."""
|
| 2 |
+
import numpy as np
|
| 3 |
+
|
| 4 |
+
def decode(plan,dets,per_sector=128):
|
| 5 |
+
keys=np.array([0],np.uint32);mass=np.ones(1,np.float64)
|
| 6 |
+
pruned_steps=0;maximum_states=1;discarded_fractions=[]
|
| 7 |
+
for probability,mask,detector in zip(plan['probabilities'],plan['masks'],plan['measured']):
|
| 8 |
+
probability=float(probability);mask=np.uint32(mask)
|
| 9 |
+
if detector<0:
|
| 10 |
+
expanded=np.concatenate([keys,keys^mask]);values=np.concatenate([(1-probability)*mass,probability*mass])
|
| 11 |
+
order=np.argsort(expanded,kind='stable');expanded=expanded[order];values=values[order]
|
| 12 |
+
starts=np.r_[0,np.flatnonzero(expanded[1:]!=expanded[:-1])+1]
|
| 13 |
+
keys=expanded[starts];mass=np.add.reduceat(values,starts)
|
| 14 |
+
positive=mass>0;keys,mass=keys[positive],mass[positive]
|
| 15 |
+
selected=[]
|
| 16 |
+
for sector in [0,1]:
|
| 17 |
+
indices=np.flatnonzero((keys&1)==sector)
|
| 18 |
+
if len(indices)>per_sector:
|
| 19 |
+
# Deterministic key tie break; never use sample IDs or other shots.
|
| 20 |
+
indices=indices[np.lexsort((keys[indices],-mass[indices]))[:per_sector]]
|
| 21 |
+
selected.extend(indices.tolist())
|
| 22 |
+
if len(selected)<len(keys):
|
| 23 |
+
total=mass.sum();discarded_fractions.append(float(1-mass[selected].sum()/total));pruned_steps+=1
|
| 24 |
+
keys,mass=keys[selected],mass[selected]
|
| 25 |
+
else:
|
| 26 |
+
keep=(keys&mask)==np.uint32(int(dets[int(detector)]))*mask
|
| 27 |
+
keys,mass=keys[keep]&~mask,mass[keep]
|
| 28 |
+
norm=mass.sum()
|
| 29 |
+
if norm==0:return np.float64(.5),{'status':'empty_beam','detector':int(detector),'pruned_steps':pruned_steps,'maximum_states':maximum_states}
|
| 30 |
+
mass/=norm
|
| 31 |
+
maximum_states=max(maximum_states,len(keys))
|
| 32 |
+
probability=mass[(keys&1)!=0].sum()/mass.sum()
|
| 33 |
+
return probability,{'status':'ok','pruned_steps':pruned_steps,'maximum_states':maximum_states,
|
| 34 |
+
'maximum_discarded_fraction':max(discarded_fractions,default=0.),'sum_discarded_fractions':sum(discarded_fractions)}
|
| 35 |
+
|
| 36 |
+
def dense_reference(plan,dets):
|
| 37 |
+
width=int(plan['width']);assert width<=14,'CPU reference limited to small controlled frontiers'
|
| 38 |
+
indices=np.arange(1<<width);mass=np.zeros(1<<width,np.float64);mass[0]=1
|
| 39 |
+
for p,mask,detector in zip(plan['probabilities'],plan['masks'],plan['measured']):
|
| 40 |
+
p=float(p);mask=int(mask)
|
| 41 |
+
if detector<0:mass=(1-p)*mass+p*mass[indices^mask]
|
| 42 |
+
else:
|
| 43 |
+
mass=mass[((indices&~mask)|(int(dets[int(detector)])*mask))]*((indices&mask)==0)
|
| 44 |
+
mass/=mass.sum()
|
| 45 |
+
return mass[1::2].sum()/mass.sum()
|
tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S044/training_sources/beam_calibration1/beam_lookahead.py
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Sparse frontier with independent remaining-syndrome marginals used only for ranking."""
|
| 2 |
+
import numpy as np
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
def prepare_lookahead(plan):
|
| 6 |
+
width=int(plan['width']);bits=np.left_shift(np.uint32(1),np.arange(1,width,dtype=np.uint32))
|
| 7 |
+
active_masks=[];active=np.uint32(1)
|
| 8 |
+
for mask,d in zip(plan['masks'],plan['measured']):
|
| 9 |
+
active|=np.uint32(mask);active_masks.append(active)
|
| 10 |
+
if d>=0:active&=~np.uint32(mask)
|
| 11 |
+
detectors=np.full((len(active_masks),width-1),-1,np.int32)
|
| 12 |
+
future=np.zeros((len(active_masks),width-1),np.float64)
|
| 13 |
+
active=np.asarray(active_masks,np.uint32)[:,None]&bits[None,:]!=0
|
| 14 |
+
assigned=np.full(width-1,-1,np.int32);log_parity=np.zeros(width-1,np.float64)
|
| 15 |
+
for i in range(len(active_masks)-1,-1,-1):
|
| 16 |
+
p=float(plan['probabilities'][i]);mask=np.uint32(plan['masks'][i]);d=int(plan['measured'][i]);touched=(mask&bits)!=0
|
| 17 |
+
if d>=0:
|
| 18 |
+
assert touched.sum()==1
|
| 19 |
+
assigned[touched]=d;log_parity[touched]=0.
|
| 20 |
+
else:
|
| 21 |
+
assert 0<=p<.5
|
| 22 |
+
detectors[i]=assigned;future[i]=-.5*np.expm1(log_parity)
|
| 23 |
+
assert (assigned[active[i]]>=0).all()
|
| 24 |
+
log_parity[touched]+=np.log1p(-2*p)
|
| 25 |
+
return {'detectors':detectors,'future':future,'active':active,'bits':bits}
|
| 26 |
+
|
| 27 |
+
def decode(plan,dets,per_sector=128,lookahead=None):
|
| 28 |
+
lookahead=prepare_lookahead(plan) if lookahead is None else lookahead
|
| 29 |
+
keys=np.array([0],np.uint32);mass=np.ones(1,np.float64)
|
| 30 |
+
pruned_steps=0;maximum_states=1;discarded_fractions=[]
|
| 31 |
+
for operation,(probability,mask,detector) in enumerate(zip(plan['probabilities'],plan['masks'],plan['measured'])):
|
| 32 |
+
probability=float(probability);mask=np.uint32(mask)
|
| 33 |
+
if detector<0:
|
| 34 |
+
expanded=np.concatenate([keys,keys^mask]);values=np.concatenate([(1-probability)*mass,probability*mass])
|
| 35 |
+
order=np.argsort(expanded,kind='stable');expanded=expanded[order];values=values[order]
|
| 36 |
+
starts=np.r_[0,np.flatnonzero(expanded[1:]!=expanded[:-1])+1]
|
| 37 |
+
keys=expanded[starts];mass=np.add.reduceat(values,starts)
|
| 38 |
+
positive=mass>0;keys,mass=keys[positive],mass[positive]
|
| 39 |
+
selected=[];scores=None
|
| 40 |
+
for sector in [0,1]:
|
| 41 |
+
indices=np.flatnonzero((keys&1)==sector)
|
| 42 |
+
if len(indices)>per_sector:
|
| 43 |
+
# Deterministic key tie break; never use sample IDs or other shots.
|
| 44 |
+
if scores is None:
|
| 45 |
+
active=lookahead['active'][operation];bits=lookahead['bits'][active]
|
| 46 |
+
ds=lookahead['detectors'][operation,active];q=lookahead['future'][operation,active]
|
| 47 |
+
mismatch=((keys[:,None]&bits[None,:])!=0)!=dets[ds][None,:]
|
| 48 |
+
with np.errstate(divide='ignore'):
|
| 49 |
+
future_log=np.where(mismatch,np.log(q)[None,:],np.log1p(-q)[None,:]).sum(axis=1)
|
| 50 |
+
scores=np.log(mass)+future_log
|
| 51 |
+
indices=indices[np.lexsort((keys[indices],-scores[indices]))[:per_sector]]
|
| 52 |
+
selected.extend(indices.tolist())
|
| 53 |
+
if len(selected)<len(keys):
|
| 54 |
+
total=mass.sum();discarded_fractions.append(float(1-mass[selected].sum()/total));pruned_steps+=1
|
| 55 |
+
keys,mass=keys[selected],mass[selected]
|
| 56 |
+
else:
|
| 57 |
+
keep=(keys&mask)==np.uint32(int(dets[int(detector)]))*mask
|
| 58 |
+
keys,mass=keys[keep]&~mask,mass[keep]
|
| 59 |
+
norm=mass.sum()
|
| 60 |
+
if norm==0:return np.float64(.5),{'status':'empty_beam','detector':int(detector),'pruned_steps':pruned_steps,'maximum_states':maximum_states}
|
| 61 |
+
mass/=norm
|
| 62 |
+
maximum_states=max(maximum_states,len(keys))
|
| 63 |
+
probability=mass[(keys&1)!=0].sum()/mass.sum()
|
| 64 |
+
return probability,{'status':'ok','pruned_steps':pruned_steps,'maximum_states':maximum_states,
|
| 65 |
+
'maximum_discarded_fraction':max(discarded_fractions,default=0.),'sum_discarded_fractions':sum(discarded_fractions)}
|
| 66 |
+
|
| 67 |
+
def dense_reference(plan,dets):
|
| 68 |
+
width=int(plan['width']);assert width<=14,'CPU reference limited to small controlled frontiers'
|
| 69 |
+
indices=np.arange(1<<width);mass=np.zeros(1<<width,np.float64);mass[0]=1
|
| 70 |
+
for p,mask,detector in zip(plan['probabilities'],plan['masks'],plan['measured']):
|
| 71 |
+
p=float(p);mask=int(mask)
|
| 72 |
+
if detector<0:mass=(1-p)*mass+p*mass[indices^mask]
|
| 73 |
+
else:
|
| 74 |
+
mass=mass[((indices&~mask)|(int(dets[int(detector)])*mask))]*((indices&mask)==0)
|
| 75 |
+
mass/=mass.sum()
|
| 76 |
+
return mass[1::2].sum()/mass.sum()
|
tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S044/training_sources/beam_calibration1/control_cpu.py
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Independent gradient, unsigned-label, and row/subset controls."""
|
| 2 |
+
import os
|
| 3 |
+
os.environ['OPENBLAS_NUM_THREADS']='1';os.sched_setaffinity(0,sorted(os.sched_getaffinity(0))[:4])
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
import hashlib,json
|
| 6 |
+
import numpy as np
|
| 7 |
+
from scipy.special import expit
|
| 8 |
+
from core import raw_features,normalize,objective_gradient,predict
|
| 9 |
+
root=Path(__file__).resolve().parent;rng=np.random.default_rng(20262110);parent=np.r_[0.,1.,.5,rng.uniform(.001,.999,29)].astype(np.float32);beam=np.r_[1.,0.,.5,rng.uniform(.001,.999,29)].astype(np.float32);labels=rng.integers(2,size=len(parent),dtype=np.uint8);checks=[]
|
| 10 |
+
for mode in ['parent_only','parent_plus_beam']:
|
| 11 |
+
b=None if mode=='parent_only' else beam;base,raw=raw_features(parent,b);state={'center':raw.mean(axis=0),'scale':np.maximum(raw.std(axis=0),.05),'weights':rng.normal(0,.2,raw.shape[1]+1)};x=normalize(raw,state['center'],state['scale']);value,gradient=objective_gradient(state['weights'],x,base,labels,.001);finite=[]
|
| 12 |
+
for i in range(len(gradient)):
|
| 13 |
+
offset=np.zeros(len(gradient));offset[i]=1e-5
|
| 14 |
+
a=objective_gradient(state['weights']+offset,x,base,labels,.001)[0];c=objective_gradient(state['weights']-offset,x,base,labels,.001)[0];finite.append((a-c)/2e-5)
|
| 15 |
+
delta=float(abs(gradient-finite).max());assert delta<1e-9
|
| 16 |
+
actual=predict(parent,b,state);expected=expit(base+x@state['weights']).astype(np.float32);assert np.array_equal(actual,expected)
|
| 17 |
+
reverse=predict(parent[::-1].copy(),None if b is None else b[::-1].copy(),state);single=predict(parent[7:8],None if b is None else b[7:8],state);assert np.array_equal(reverse,actual[::-1]) and np.array_equal(single,actual[7:8]);assert np.isfinite(actual).all() and ((actual>=0)&(actual<=1)).all()
|
| 18 |
+
neutral={**state,'weights':np.zeros_like(state['weights'])};neutral_p=predict(parent,b,neutral);assert ((neutral_p>=.5)==(parent>=.5)).all();checks.append({'mode':mode,'gradient_max_abs_difference':delta,'independent_scipy_probability_exact':True,'order_subset_exact':True,'neutral_decisions_exact':True,'neutral_probability_max_abs':float(abs(neutral_p-parent).max())})
|
| 19 |
+
y=np.array([1,0],np.uint8);base=np.log(np.array([.8,.2])/np.array([.2,.8]));value,_=objective_gradient(np.zeros(2),np.array([[1.,0.],[1.,0.]]),base,y,0.);assert abs(value+np.log(.8))<1e-14
|
| 20 |
+
report={'status':'passed','checks':checks,'unsigned_label_reference_loss':value,'hardware_labels_accessed':False,'optimizer_updates':0,'test_data_used':False,'source_sha256':{p.name:hashlib.sha256(p.read_bytes()).hexdigest() for p in [root/'core.py',Path(__file__).resolve()]}};(root/'control_cpu.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/S044/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/S044/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/S044/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/S044/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/S044/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/S044/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/S044/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/S044/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/S044/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/S044/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/S044/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/S044/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/S044/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/S044/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/S044/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/S044/training_sources/conditional_edge_projection1/PROPOSAL.json
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"name": "conditional_edge_projection_cpu_prototype",
|
| 3 |
+
"created_utc": "2026-10-22T00:19:02.702150+00:00",
|
| 4 |
+
"status": "CPU attachment prototype only; notGPUqueued, no main training protocol or validation selection yet.",
|
| 5 |
+
"hypothesis": "The original reconstruction loss supervises masked positions, but the first frozen edge-projection study uses unmasked representations. Instead give each fault endpoint its representation from a deterministic pass where its own bit is hidden. Original raw syndrome features remain in the frozen edge networks.",
|
| 6 |
+
"frozen_encoder": "masked_pretraining/auxiliary1/weights-8192.npz",
|
| 7 |
+
"frozen_encoder_sha256": "c2002e838abdc41fa166248396eaf63501905f000befab6f1b2bffefe00794f8",
|
| 8 |
+
"frozen_parent": "Own r3 parent: X confidence_joint1024 with two frozen experts and frozen confidence gate; Z fresh2full1536 with physical prior5. All originate from random initialization in this session.",
|
| 9 |
+
"new_parameters": "One zero-initialized64x64 first-hidden-layer input projection per frozen expert: Xexpert0,Xexpert1,Zsingle. No updates to original MLPs, gate or encoder.",
|
| 10 |
+
"partition_seed": 20263501,
|
| 11 |
+
"partition_count": 8,
|
| 12 |
+
"partition": "Same fixed26x24 colors as masked_conditional_features. Eightpasses, each token taken from its own maskedpass; masked events removed before cumulative parity. Colors depend only on ideal slot positions, not IDs/rows/batch data.",
|
| 13 |
+
"training_only_evidence": "masked_conditional_features/probe_report.json: conditional reconstruction NLL.344819 vspositionfreq.408062 on64originalreservedtrainingrows percondition,26d5conditions. No logical accuracy claim. CPU target-bit invariance/order/composition controls passed.",
|
| 14 |
+
"prototype": "Reuse unchanged exact frozen-parent edge equations; compare projected-head gradients to whole-contraction autodiff, neutral behavior, frozen-state and resume/order on real training X3/Z3N2. Only six discarded control updates includingreplay.",
|
| 15 |
+
"future_if_pursued": "Main should match original projection2048B512 data/draws/optimizer/checkpointchoices, with only token feature construction changed. ActualGPU resources and runtime feasibility must pass first. Decision to pursue main follows completed original fullvalidation. No current queue.",
|
| 16 |
+
"test_data_used": false
|
| 17 |
+
}
|
tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S044/training_sources/conditional_edge_projection1/REPLAY_BACKEND_RECOVERY_PLAN.json
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"created_utc": "2026-10-22T01:28:37.966406+00:00",
|
| 3 |
+
"failure": "GPU control and training workers explicitly set cuda, but their CPU preparation supervisor passed JAX_PLATFORMS=cpu to the shared full-package replay helper. GPU telemetry showed zero GPU compute and 4MiB device memory while replay consumed CPU and Xr1 took83s versus prior14s. The queue source demonstrates inheritedCPU; /proc environment read was denied and is not claimed as evidence.",
|
| 4 |
+
"stopped_processes": [
|
| 5 |
+
166742,
|
| 6 |
+
167145,
|
| 7 |
+
174418,
|
| 8 |
+
174419
|
| 9 |
+
],
|
| 10 |
+
"preservation": "Original helper, partial predictions, complete cached predictions, original candidate metadata and logs preserved in cpu_replay_failure. Original cached validation predictions copied back; original helper will create a fresh cache before replay. No rows or probabilities modified.",
|
| 11 |
+
"repair": "Shared verify_d5_candidate.py now supplies JAX_PLATFORMS=cuda explicitly to full inference and relocated subset inference. Trusted scoring unchanged. This also repairs subsequent queued experiments using that helper.",
|
| 12 |
+
"scientific_effect": "None: all673 frozen study source/state pins remain unchanged. No new updates, checkpoints, choices or threshold changes. Timed replay restarts on the oneH100. No candidate publication occurred.",
|
| 13 |
+
"original_helper_sha256": "4f3725d3292df8a0e04a64d52ef365d19ba64be92ed1b92bb369848c36c48cf1",
|
| 14 |
+
"corrected_helper_sha256": "1d9d817f6df96abb654c141e4b2cc31c1bfa54b190e1a9d188d8a7f9f510fece",
|
| 15 |
+
"test_data_used": false
|
| 16 |
+
}
|
tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S044/training_sources/conditional_edge_projection1/RUNTIME_PRECISION_RECOVERY_PLAN.json
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"created_utc": "2026-10-22T01:49:36.006244+00:00",
|
| 3 |
+
"status": "Fresh-process numerical controls passed; only runtime encoder precision repaired; full replay pending",
|
| 4 |
+
"cause_evidence": "Native fresh-process warmups Z1/X1 change conditional encoder tokens by0.00159/0.00149 and logical outputs by~5.53e-5; live priors are bitwise identical. Within-process permutation/subset checks are exact. This isolates the observed discrepancy to encoder compilation context, without claiming a particular backend kernel implementation.",
|
| 5 |
+
"repair": "Only conditional_edge_features.token_embeddings enters jax.default_matmul_precision(highest) during encoder tracing. Physical head, prior calculation, selected weights, geometry, masks, batch size, input features and equations unchanged. No weight fitting or new checkpoint choice.",
|
| 6 |
+
"fixed_selection": "Original Z1024 and incumbentX from three declared cached choices. No precision variant selected using validation score.",
|
| 7 |
+
"criteria": "Fresh-process encoder tokens/pooling<2e-5, priorlogits<1e-6, logicalprobabilities<2e-6 and zero decision changes for cold/Z1/X1 contexts. Full original readonly subset criterion remains<2e-6; all26 actual replay and trusted130score required.",
|
| 8 |
+
"controls": {
|
| 9 |
+
"status": "passed",
|
| 10 |
+
"scope": "Fixed trained weights and training detectors; Only encoder matmuls use highestfloat32; originalphysicalhead/priorprecision unchanged. Earlier condition warmup differs. Freshprocesses, no fitting, labels, IDs or score selection.",
|
| 11 |
+
"records": [
|
| 12 |
+
{
|
| 13 |
+
"warm": "none",
|
| 14 |
+
"max_abs_versus_cold": {
|
| 15 |
+
"tokens": 0.0,
|
| 16 |
+
"pooled": 0.0,
|
| 17 |
+
"base": 0.0,
|
| 18 |
+
"logical": 0.0
|
| 19 |
+
},
|
| 20 |
+
"decision_differences": 0
|
| 21 |
+
},
|
| 22 |
+
{
|
| 23 |
+
"warm": "Z1",
|
| 24 |
+
"max_abs_versus_cold": {
|
| 25 |
+
"tokens": 0.0,
|
| 26 |
+
"pooled": 0.0,
|
| 27 |
+
"base": 0.0,
|
| 28 |
+
"logical": 0.0
|
| 29 |
+
},
|
| 30 |
+
"decision_differences": 0
|
| 31 |
+
},
|
| 32 |
+
{
|
| 33 |
+
"warm": "X1",
|
| 34 |
+
"max_abs_versus_cold": {
|
| 35 |
+
"tokens": 0.0,
|
| 36 |
+
"pooled": 0.0,
|
| 37 |
+
"base": 0.0,
|
| 38 |
+
"logical": 0.0
|
| 39 |
+
},
|
| 40 |
+
"decision_differences": 0
|
| 41 |
+
}
|
| 42 |
+
],
|
| 43 |
+
"source_sha256": {
|
| 44 |
+
"control_conditional_precise_stages.py": "4b3169ac1f4d342b734f9508d4a3e2a6643c934a35777bc78f32b0f71b8049ad",
|
| 45 |
+
"capture_conditional_precise_stages.py": "45a47113f8f0cc54d72cdca595902ffd0e50dba14b6876026f51fe28cd096bf4"
|
| 46 |
+
},
|
| 47 |
+
"test_data_used": false
|
| 48 |
+
},
|
| 49 |
+
"diagnosis": {
|
| 50 |
+
"status": "complete",
|
| 51 |
+
"scope": "Fixed trained weights and training detectors; only earlier condition warmup differs. Freshprocesses, no fitting, labels, IDs or score selection.",
|
| 52 |
+
"records": [
|
| 53 |
+
{
|
| 54 |
+
"warm": "none",
|
| 55 |
+
"max_abs_versus_cold": {
|
| 56 |
+
"tokens": 0.0,
|
| 57 |
+
"pooled": 0.0,
|
| 58 |
+
"base": 0.0,
|
| 59 |
+
"logical": 0.0
|
| 60 |
+
},
|
| 61 |
+
"decision_differences": 0
|
| 62 |
+
},
|
| 63 |
+
{
|
| 64 |
+
"warm": "Z1",
|
| 65 |
+
"max_abs_versus_cold": {
|
| 66 |
+
"tokens": 0.0015914440155029297,
|
| 67 |
+
"pooled": 0.0015914440155029297,
|
| 68 |
+
"base": 0.0,
|
| 69 |
+
"logical": 5.53131103515625e-05
|
| 70 |
+
},
|
| 71 |
+
"decision_differences": 0
|
| 72 |
+
},
|
| 73 |
+
{
|
| 74 |
+
"warm": "X1",
|
| 75 |
+
"max_abs_versus_cold": {
|
| 76 |
+
"tokens": 0.0014914870262145996,
|
| 77 |
+
"pooled": 0.0014914870262145996,
|
| 78 |
+
"base": 0.0,
|
| 79 |
+
"logical": 5.525350570678711e-05
|
| 80 |
+
},
|
| 81 |
+
"decision_differences": 0
|
| 82 |
+
}
|
| 83 |
+
],
|
| 84 |
+
"source_sha256": {
|
| 85 |
+
"diagnose_conditional_fresh_stages.py": "6e4ed8fbc2f535a7c985647d3577b4806d5f30c35f21c9488937ba9e938771c2",
|
| 86 |
+
"capture_conditional_fresh_stages.py": "3d884292adffc9734564eaeb0a3e25a5049c64b87b99ecef86c06d72e1202f69"
|
| 87 |
+
},
|
| 88 |
+
"test_data_used": false
|
| 89 |
+
},
|
| 90 |
+
"source_file": "conditional_edge_features.py",
|
| 91 |
+
"source_before_sha256": "0dd05676027b5bbe71dc168f89a004f746b670e5533de27b6ec809843afabd25",
|
| 92 |
+
"source_after_sha256": "a54e0a0f50583372509f2fbbfd507099d2331fa721217e1e016e67c8852fc22c",
|
| 93 |
+
"frozen_scientific_pins_unchanged": 673,
|
| 94 |
+
"preserved_failure": "production_portability_failure contains native full/cached predictions, score, logs, failed contract and complete pre-repair package snapshot under contract/relocated. CPU backend failure remains separately preserved.",
|
| 95 |
+
"test_data_used": false
|
| 96 |
+
}
|
tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S044/training_sources/conditional_edge_projection1/TRAINING_PLAN.json
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"name": "conditional_edge_projection1",
|
| 3 |
+
"created_utc": "2026-10-22T00:35:23.164582+00:00",
|
| 4 |
+
"status": "Declared after completed unmasked projection results and before actual trainer controls or main fitting",
|
| 5 |
+
"prototype_control": "control_cpu.json",
|
| 6 |
+
"steps": 2048,
|
| 7 |
+
"batch": 512,
|
| 8 |
+
"learning_rate": 0.0005,
|
| 9 |
+
"sampling_seed": 20263201,
|
| 10 |
+
"optimizer": "Fresh separate X and Z AdamW states; beta defaults, constant learning rate. Clip norm1 across active basis projections only; decay1e-4 on projections only. All frozen parents, confidence gate and auxiliary encoder excluded from optimizer and weight decay.",
|
| 11 |
+
"initial_projection": "Allzero64x64 per Xexpert0/Xexpert1/Zsingle; no new random learned weights. All frozen weights descend own-session random initialization.",
|
| 12 |
+
"data": "All516880d5 supplied training labels, uniform condition then uniform row with replacement, conditions sorted by canonical name. Same frozen r3 parent and physical prior3X/prior5Z as declared prototype.",
|
| 13 |
+
"feature_computation": "Frozen auxiliary encoder8192. Eight deterministic ideal-slot masking partitions, seed20263501; each token embedding is taken only from the pass hiding its own detector event. Masked bits are zeroed before cumulative parity. Endpoint pooling unchanged; no dropout or logical probability inputs. Features evaluated live.",
|
| 14 |
+
"validation_screens": "Fixed1024 rows percondition fromseed20261102 at0 and every512updates, including1536; diagnostic only. Full selection remains512/1024/2048.",
|
| 15 |
+
"selection_steps": [
|
| 16 |
+
512,
|
| 17 |
+
1024,
|
| 18 |
+
2048
|
| 19 |
+
],
|
| 20 |
+
"selection": "Full26d5 validation, all13 durations perbasis; three raw checkpoints plus retain then-current. No blends or step0 selection.",
|
| 21 |
+
"mandatory_controls": "All26geometry support audits; actual CPU trainer full2 versus1+resume1, all-source/hash/ID/seen/RNG/active-basis Adam audit; CUDA CPU-reference gradients and native production B512 X25/Z25 discarded memory pilots; actual exported live/cached order/subset/globalclear controls; full0 frozen-parent cache agreement before main.",
|
| 22 |
+
"publication": "Full assembled d5 replay, trusted all130 scoring, readonly relocation/subset/ID checks and <3600second runtime projection before atomic publication. If numerical or resource controls fail, preserve evidence and resolve before any main fitting.",
|
| 23 |
+
"queue": "After d3_masked_head completes, subject to all CPU and actual GPU numerical/resource/runtime controls.",
|
| 24 |
+
"test_data_used": false,
|
| 25 |
+
"pre_main_clarification": "The implemented eval-every512 trainer also emits a1536 diagnostic screen, as its earlier sibling trainers do. This monitoring-only clarification is recorded before main execution/source freeze; no checkpoint selection or training math changes. Existing discarded CPU fixtures used the previous wording.",
|
| 26 |
+
"matched_control": "Completed masked_edge_projection/projection1: identical initial zero projections, frozen parents/encoder, all train/cache rows, sampler seed and every draw, optimizer schedule, separate basis clocks and three full checkpoint choices. Only token feature construction changes. Every draw/state descriptor and initial weights are compared explicitly; fitted weights and optimizer moments are expected to differ.",
|
| 27 |
+
"validation_cache": "Reuse original projection recovered exact-runtime validation priors with explicit ID equality joins; no historical prior cache. Full zero audit still required."
|
| 28 |
+
}
|
tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S044/training_sources/conditional_edge_projection1/after_d3_head.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Serialize projection controls, initial cache audit, fitting and publication on one H100."""
|
| 2 |
+
import os
|
| 3 |
+
os.environ['OPENBLAS_NUM_THREADS']='1';os.sched_setaffinity(0,sorted(os.sched_getaffinity(0))[:22])
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
import json,datetime,subprocess,time
|
| 6 |
+
from fixtures import digest,frozen_states
|
| 7 |
+
from audit_run import audit
|
| 8 |
+
from matched_draw_audit import audit as matched_audit
|
| 9 |
+
root=Path(__file__).resolve().parent;r=root.parent;marker=r/'d3_masked_head/d3_masked_head1_finished.json';started=time.monotonic()
|
| 10 |
+
while not marker.exists():
|
| 11 |
+
if time.monotonic()-started>86400:raise TimeoutError('Prior d3 masked-head study incomplete')
|
| 12 |
+
time.sleep(2)
|
| 13 |
+
assert json.loads(marker.read_text())['complete'];assert not subprocess.check_output(['nvidia-smi','--query-compute-apps=pid','--format=csv,noheader'],text=True).strip();plan=json.loads((root/'plan.json').read_text())
|
| 14 |
+
for path,sha in plan['frozen_source_sha256'].items():assert digest(r/path)==sha,path
|
| 15 |
+
for name in ['control_cpu.json','pipeline_control_cpu.json','dual_basis_control_cpu.json','geometry_control_cpu.json','backend_control_cpu.json','runtime_control_cpu.json']:
|
| 16 |
+
a=json.loads((root/name).read_text());assert a['status']=='passed'
|
| 17 |
+
for path,sha in a['source_sha256'].items():assert digest(root/path)==sha,(name,path)
|
| 18 |
+
for name in ['zero_parent_audit','projection1','validation-512','validation-1024','validation-2048']:assert not (root/name).exists(),name
|
| 19 |
+
def call(script,*args,gpu=False,log=None):
|
| 20 |
+
cmd=['python']+([str(r/'run_limited.py')] if gpu else [])+[str(root/script),*map(str,args)];env=os.environ.copy();env['JAX_PLATFORMS']='cuda' if gpu else 'cpu'
|
| 21 |
+
if log:
|
| 22 |
+
with (root/log).open('w') as stream:subprocess.run(cmd,stdout=stream,stderr=subprocess.STDOUT,check=True,env=env)
|
| 23 |
+
else:subprocess.run(cmd,check=True,env=env)
|
| 24 |
+
call('backend_control.py','--device','gpu',gpu=True);call('runtime_control.py','--device','gpu',gpu=True);call('evaluate.py','--zero','--output',root/'zero_parent_audit',gpu=True,log='zero_parent_audit.log');a=json.loads((root/'zero_parent_audit/report.json').read_text());assert a['status']=='passed' and a['zero_parent_audit'] and a['shots']==133120 and all(x['frozen_parent_decision_changes']==0 for x in a['conditions']);plan.update(status='All GPU production controls and full zero-projection parent/cache agreement passed; main fitting launched',launch_utc=datetime.datetime.now(datetime.timezone.utc).isoformat());(root/'plan.json').write_text(json.dumps(plan,indent=2)+'\n')
|
| 25 |
+
call('train.py','--output',root/'projection1',gpu=True,log='projection1.log');evidence=audit(root/'projection1');assert evidence['training_draws']==1048576 and evidence['eligible_rows']==516880;provenance=json.loads((root/'projection1/provenance.json').read_text());matched=matched_audit(root/'projection1');provenance.update(declared_plan=plan,sampling_audit=evidence,zero_parent_audit=a,matched_draw_audit=matched);(root/'projection1/provenance.json').write_text(json.dumps(provenance,indent=2)+'\n')
|
| 26 |
+
for step in plan['selection_steps']:call('evaluate.py','--weights',root/f'projection1/weights-{step}.npz','--output',root/f'validation-{step}',gpu=True,log=f'validation-{step}.log')
|
| 27 |
+
previous=json.loads((r/'CURRENT.json').read_text())['predictions'];call('package.py');out=r/'context_upgrades/conditional_edge_projection1';subprocess.run(['python',str(r/'verify_d5_candidate.py'),str(out)],check=True);subprocess.run(['python',str(r/'audit_completed_candidate.py'),'--candidate',str(out),'--previous',previous],check=True);(root/'conditional_edge_projection1_finished.json').write_text(json.dumps({'complete':True,'test_data_used':False})+'\n')
|
tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S044/training_sources/conditional_edge_projection1/audit_run.py
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Replay every condition/row draw and the separate projection Adam clocks."""
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
import argparse,json,hashlib
|
| 4 |
+
import numpy as np
|
| 5 |
+
|
| 6 |
+
def digest(p):return hashlib.sha256(Path(p).read_bytes()).hexdigest()
|
| 7 |
+
def audit(run):
|
| 8 |
+
run=Path(run);config=json.loads((run/'run_config.json').read_text());assert config['start_step']==0 and not config['resume'];plan=config['training_plan'];rows=sorted([x for x in json.loads(Path('/workspace/data/train/manifest.json').read_text())['conditions'] if x['distance']==5],key=lambda x:x['name']);assert len(rows)==26 and len(config['data'])==26
|
| 9 |
+
for name,sha in config['source_sha256'].items():assert digest(run/'training_source'/name)==sha
|
| 10 |
+
for record,row in zip(config['data'],rows):
|
| 11 |
+
assert record['condition']==row['name']
|
| 12 |
+
for split,source in record['sources'].items():
|
| 13 |
+
assert digest(source['cache'])==source['cache_sha256'];path=Path('/workspace/data')/split/row['arrays'];assert digest(path)==source['arrays_sha256']
|
| 14 |
+
with np.load(path,allow_pickle=False) as f:ids=f['sample_ids']
|
| 15 |
+
assert hashlib.sha256(ids.tobytes()).hexdigest()==source['ID_sha256']
|
| 16 |
+
rng=np.random.default_rng(plan['sampling_seed']);seen=[np.zeros(x['shots'],bool) for x in rows];counts={'X':0,'Z':0};draw_hash=hashlib.sha256();steps=[]
|
| 17 |
+
for step in range(config['steps']+1):
|
| 18 |
+
if step:
|
| 19 |
+
ci=int(rng.integers(26));ix=rng.integers(rows[ci]['shots'],size=config['batch']);seen[ci][ix]=True;counts[rows[ci]['basis']]+=1;draw_hash.update(np.asarray([ci,*ix],dtype='<i8').tobytes())
|
| 20 |
+
path=run/f'checkpoint-{step}.json'
|
| 21 |
+
if not path.exists():continue
|
| 22 |
+
a=json.loads(path.read_text());assert a['complete'] and a['frozen_encoder_parents_and_gate_exact'] and a['step']==step and a['training_draws']==step*config['batch'] and a['basis_update_counts']==counts and a['weights_sha256']==digest(run/f'weights-{step}.npz') and a['draw_descriptor_sha256']==draw_hash.hexdigest() and a['unique_rows']==sum(int(x.sum()) for x in seen)
|
| 23 |
+
assert json.loads((run/f'rng-{step}.json').read_text())==rng.bit_generator.state
|
| 24 |
+
with np.load(run/f'seen-{step}.npz',allow_pickle=False) as f:assert set(f.files)=={x['name'] for x in rows} and all(np.array_equal(f[x['name']],v) for x,v in zip(rows,seen))
|
| 25 |
+
with np.load(run/f'optimizer-{step}.npz',allow_pickle=False) as f:
|
| 26 |
+
actual=[int(f[k]) for k in f.files if f[k].shape==() and np.issubdtype(f[k].dtype,np.integer)];assert actual==[counts['X'],counts['Z']],actual
|
| 27 |
+
with np.load(run/f'weights-{step}.npz',allow_pickle=False) as f:
|
| 28 |
+
assert set(f.files)=={'X_expert0','X_expert1','Z'} and all(f[k].shape==(64,64) and f[k].dtype==np.float32 and np.isfinite(f[k]).all() for k in f.files)
|
| 29 |
+
if step==0:assert all(not f[k].any() for k in f.files)
|
| 30 |
+
steps.append(step)
|
| 31 |
+
assert config['steps'] in steps;provenance=json.loads((run/'provenance.json').read_text());assert provenance['training_draws']==config['steps']*config['batch'] and provenance['basis_update_counts']==counts and provenance['draw_descriptor_sha256']==draw_hash.hexdigest()
|
| 32 |
+
report={'status':'passed','checked_steps':steps,'training_draws':config['steps']*config['batch'],'eligible_rows':516880,'basis_update_counts':counts,'every_draw_seen_RNG_hash_and_separate_Adam_clock_verified':True,'optimizer_contains_projections_only':True,'zero_initial_projections_verified':True,'source_sha256':digest(Path(__file__).resolve()),'test_data_used':False};(run/'audit.json').write_text(json.dumps(report,indent=2)+'\n');return report
|
| 33 |
+
if __name__=='__main__':
|
| 34 |
+
p=argparse.ArgumentParser();p.add_argument('run',type=Path);a=p.parse_args();print(json.dumps(audit(a.run),indent=2))
|
tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S044/training_sources/conditional_edge_projection1/aux_encoder.py
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Dense masked-event objective using the unchanged axial encoder equations."""
|
| 2 |
+
import jax
|
| 3 |
+
import jax.numpy as jnp
|
| 4 |
+
from axial_base import DEFAULT,layer_norm,attention,dropout
|
| 5 |
+
|
| 6 |
+
def features(dets,grid,basis,rounds,mask):
|
| 7 |
+
valid=grid!=600
|
| 8 |
+
target=dets[:,grid].astype(jnp.float32)*valid[None]
|
| 9 |
+
mask=mask&valid[None]
|
| 10 |
+
events=jnp.where(mask,0.,target)
|
| 11 |
+
measured=(jnp.cumsum(events.astype(jnp.int32),axis=1)&1).astype(jnp.float32)
|
| 12 |
+
broadcast=lambda value:jnp.broadcast_to(value,events.shape)
|
| 13 |
+
x=jnp.stack([events,measured,broadcast(valid[None]),broadcast(jnp.arange(26)[None,:,None]/25),broadcast(jnp.asarray(basis,jnp.float32)),broadcast(jnp.asarray(rounds,jnp.float32)/25),mask.astype(jnp.float32),jnp.zeros_like(events)],axis=-1)
|
| 14 |
+
return x,valid,target,mask
|
| 15 |
+
|
| 16 |
+
def encode(parameters,inputs,valid,*,training=False,key=None,config=None):
|
| 17 |
+
c=DEFAULT if config is None else config;mask=valid[None,:,:,None]
|
| 18 |
+
x=(inputs@parameters['input_w']+parameters['input_b']+parameters['space_embedding'][None,None]+parameters['time_embedding'][None,:,None])*mask
|
| 19 |
+
if key is None:key=jax.random.key(0)
|
| 20 |
+
keys=jax.random.split(key,3*c['depth'])
|
| 21 |
+
for i in range(c['depth']):
|
| 22 |
+
for rank,axis in enumerate(['time','space']):
|
| 23 |
+
prefix=f'b{i}_{axis}';normalized=layer_norm(x,parameters[prefix+'_scale'],parameters[prefix+'_bias']);update=attention(parameters,prefix,normalized,valid,axis,c['heads']);x=(x+dropout(update,keys[3*i+rank],c['dropout'],training))*mask
|
| 24 |
+
prefix=f'b{i}_ff';normalized=layer_norm(x,parameters[prefix+'_scale'],parameters[prefix+'_bias']);update=jax.nn.gelu(normalized@parameters[prefix+'_w1']+parameters[prefix+'_b1'])@parameters[prefix+'_w2']+parameters[prefix+'_b2'];x=(x+dropout(update,keys[3*i+2],c['dropout'],training))*mask
|
| 25 |
+
return layer_norm(x,parameters['readout_scale'],parameters['readout_bias'])*mask
|
| 26 |
+
|
| 27 |
+
def token_logits(parameters,dets,grid,basis,rounds,mask,*,training=False,key=None):
|
| 28 |
+
x,valid,target,mask=features(dets,grid,basis,rounds,mask);hidden=encode(parameters,x,valid,training=training,key=key)
|
| 29 |
+
return (hidden@parameters['mask_w'])[:,:, :,0]+parameters['mask_b'][0],target,mask
|
| 30 |
+
|
| 31 |
+
def objective(parameters,dets,grid,basis,rounds,mask,*,training=False,key=None):
|
| 32 |
+
z,y,mask=token_logits(parameters,dets,grid,basis,rounds,mask,training=training,key=key);count=jnp.maximum(mask.sum(),1)
|
| 33 |
+
return jnp.sum(jnp.where(mask,jax.nn.softplus(z)-y*z,0.))/count
|
| 34 |
+
|
| 35 |
+
def attach(trained,initial):
|
| 36 |
+
result={key:value for key,value in trained.items() if not key.startswith('mask_')}
|
| 37 |
+
result['input_w']=result['input_w'].at[6:8].set(initial['input_w'][6:8])
|
| 38 |
+
for key in ['readout_w1','readout_b1','readout_w2','readout_b2']:result[key]=initial[key]
|
| 39 |
+
return result
|
tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S044/training_sources/conditional_edge_projection1/axial_base.py
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Untrained axial-attention residual over a frozen session-trained decoder."""
|
| 2 |
+
import jax
|
| 3 |
+
import jax.numpy as jnp
|
| 4 |
+
|
| 5 |
+
DEFAULT={'width':64,'heads':4,'depth':3,'expansion':2,'dropout':.1,'correction_bound':4.}
|
| 6 |
+
|
| 7 |
+
def initialize(seed,config=None):
|
| 8 |
+
c=DEFAULT if config is None else config;d=c['width'];params={};key=jax.random.key(seed)
|
| 9 |
+
def random(shape,scale):
|
| 10 |
+
nonlocal key
|
| 11 |
+
key,sub=jax.random.split(key);return jax.random.normal(sub,shape)*scale
|
| 12 |
+
params['input_w']=random((8,d),jnp.sqrt(1/8));params['input_b']=jnp.zeros(d)
|
| 13 |
+
params['space_embedding']=random((24,d),.02);params['time_embedding']=random((26,d),.02)
|
| 14 |
+
for i in range(c['depth']):
|
| 15 |
+
for axis in ['time','space']:
|
| 16 |
+
prefix=f'b{i}_{axis}'
|
| 17 |
+
params[prefix+'_scale']=jnp.ones(d);params[prefix+'_bias']=jnp.zeros(d)
|
| 18 |
+
params[prefix+'_qkv']=random((d,3*d),jnp.sqrt(1/d));params[prefix+'_qkv_b']=jnp.zeros(3*d)
|
| 19 |
+
params[prefix+'_out']=random((d,d),jnp.sqrt(1/d));params[prefix+'_out_b']=jnp.zeros(d)
|
| 20 |
+
prefix=f'b{i}_ff';hidden=d*c['expansion']
|
| 21 |
+
params[prefix+'_scale']=jnp.ones(d);params[prefix+'_bias']=jnp.zeros(d)
|
| 22 |
+
params[prefix+'_w1']=random((d,hidden),jnp.sqrt(1/d));params[prefix+'_b1']=jnp.zeros(hidden)
|
| 23 |
+
params[prefix+'_w2']=random((hidden,d),jnp.sqrt(1/hidden));params[prefix+'_b2']=jnp.zeros(d)
|
| 24 |
+
params['readout_scale']=jnp.ones(d);params['readout_bias']=jnp.zeros(d)
|
| 25 |
+
params['readout_w1']=random((d+2,d),jnp.sqrt(1/(d+2)));params['readout_b1']=jnp.zeros(d)
|
| 26 |
+
params['readout_w2']=jnp.zeros((d,1));params['readout_b2']=jnp.zeros(1)
|
| 27 |
+
return params
|
| 28 |
+
|
| 29 |
+
def parent_logit(probability):
|
| 30 |
+
p=jnp.clip(probability,1e-7,1-1e-7)
|
| 31 |
+
return jnp.log(p)-jnp.log1p(-p)
|
| 32 |
+
|
| 33 |
+
def token_features(dets,grid,basis,rounds,parent):
|
| 34 |
+
valid=grid!=600;events=dets[:,grid].astype(jnp.float32)*valid[None]
|
| 35 |
+
measured=(jnp.cumsum(events.astype(jnp.int32),axis=1)&1).astype(jnp.float32)
|
| 36 |
+
shape=events.shape
|
| 37 |
+
broadcast=lambda v:jnp.broadcast_to(v,shape)
|
| 38 |
+
z=jnp.clip(parent_logit(parent),-8.,8.)/8
|
| 39 |
+
return jnp.stack([events,measured,broadcast(valid[None]),broadcast(jnp.arange(26)[None,:,None]/25),
|
| 40 |
+
broadcast(jnp.asarray(basis,jnp.float32)),broadcast(jnp.asarray(rounds,jnp.float32)/25),
|
| 41 |
+
broadcast(z[:,None,None]),broadcast(jnp.abs(z)[:,None,None])],axis=-1),valid
|
| 42 |
+
|
| 43 |
+
def layer_norm(x,scale,bias):
|
| 44 |
+
mean=x.mean(axis=-1,keepdims=True);variance=jnp.mean((x-mean)**2,axis=-1,keepdims=True)
|
| 45 |
+
return (x-mean)*jax.lax.rsqrt(variance+1e-5)*scale+bias
|
| 46 |
+
|
| 47 |
+
def dropout(x,key,rate,training):
|
| 48 |
+
if not training or rate==0:return x
|
| 49 |
+
keep=1-rate;return jnp.where(jax.random.bernoulli(key,keep,x.shape),x/keep,0.)
|
| 50 |
+
|
| 51 |
+
def attention(parameters,prefix,x,valid,axis,heads):
|
| 52 |
+
# Reshape each temporal/spatial line into its own attention group.
|
| 53 |
+
if axis=='time':x=jnp.swapaxes(x,1,2);valid=valid.T
|
| 54 |
+
batch,groups,length,width=x.shape;head_width=width//heads
|
| 55 |
+
qkv=x@parameters[prefix+'_qkv']+parameters[prefix+'_qkv_b']
|
| 56 |
+
q,k,v=[part.reshape(batch,groups,length,heads,head_width) for part in jnp.split(qkv,3,axis=-1)]
|
| 57 |
+
score=jnp.einsum('bgihd,bgjhd->bghij',q,k)/jnp.sqrt(jnp.float32(head_width))
|
| 58 |
+
score=jnp.where(valid[None,:,None,None,:],score,-1e9)
|
| 59 |
+
weights=jax.nn.softmax(score,axis=-1)
|
| 60 |
+
value=jnp.einsum('bghij,bgjhd->bgihd',weights,v).reshape(batch,groups,length,width)
|
| 61 |
+
value=(value@parameters[prefix+'_out']+parameters[prefix+'_out_b'])*valid[None,:,:,None]
|
| 62 |
+
return jnp.swapaxes(value,1,2) if axis=='time' else value
|
| 63 |
+
|
| 64 |
+
def logits(parameters,dets,grid,basis,rounds,parent,*,training=False,key=None,config=None):
|
| 65 |
+
c=DEFAULT if config is None else config
|
| 66 |
+
features,valid=token_features(dets,grid,basis,rounds,parent);mask=valid[None,:,:,None]
|
| 67 |
+
x=(features@parameters['input_w']+parameters['input_b']+parameters['space_embedding'][None,None]+parameters['time_embedding'][None,:,None])*mask
|
| 68 |
+
if key is None:key=jax.random.key(0)
|
| 69 |
+
keys=jax.random.split(key,3*c['depth'])
|
| 70 |
+
for i in range(c['depth']):
|
| 71 |
+
for rank,axis in enumerate(['time','space']):
|
| 72 |
+
prefix=f'b{i}_{axis}';normalized=layer_norm(x,parameters[prefix+'_scale'],parameters[prefix+'_bias'])
|
| 73 |
+
update=attention(parameters,prefix,normalized,valid,axis,c['heads'])
|
| 74 |
+
x=(x+dropout(update,keys[3*i+rank],c['dropout'],training))*mask
|
| 75 |
+
prefix=f'b{i}_ff';normalized=layer_norm(x,parameters[prefix+'_scale'],parameters[prefix+'_bias'])
|
| 76 |
+
update=jax.nn.gelu(normalized@parameters[prefix+'_w1']+parameters[prefix+'_b1'])@parameters[prefix+'_w2']+parameters[prefix+'_b2']
|
| 77 |
+
x=(x+dropout(update,keys[3*i+2],c['dropout'],training))*mask
|
| 78 |
+
x=layer_norm(x,parameters['readout_scale'],parameters['readout_bias'])*mask
|
| 79 |
+
pooled=x.sum(axis=(1,2))/jnp.maximum(valid.sum(),1)
|
| 80 |
+
base=parent_logit(parent);z=jnp.clip(base,-8,8)/8
|
| 81 |
+
hidden=jax.nn.silu(jnp.concatenate([pooled,z[:,None],jnp.abs(z)[:,None]],axis=1)@parameters['readout_w1']+parameters['readout_b1'])
|
| 82 |
+
correction=c['correction_bound']*jnp.tanh((hidden@parameters['readout_w2']+parameters['readout_b2'])[:,0])
|
| 83 |
+
return base+correction
|
| 84 |
+
|
| 85 |
+
def predict(parameters,dets,grid,basis,rounds,parent,config=None):
|
| 86 |
+
return jax.nn.sigmoid(logits(parameters,dets,grid,basis,rounds,parent,config=config))
|
| 87 |
+
|
| 88 |
+
def binary_loss(logit,labels):
|
| 89 |
+
return jnp.mean(jax.nn.softplus(logit)-labels*logit)
|
tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S044/training_sources/conditional_edge_projection1/backend_control.py
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""CPU/CUDA gradient references and actual native B512 physical-gradient pilots."""
|
| 2 |
+
import argparse,os
|
| 3 |
+
parser=argparse.ArgumentParser();parser.add_argument('--device',choices=['cpu','gpu'],required=True);args=parser.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';os.sched_setaffinity(0,sorted(os.sched_getaffinity(0))[:(4 if args.device=='cpu' else 22)])
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
import json,time
|
| 7 |
+
import numpy as np
|
| 8 |
+
import jax,jax.numpy as jnp,optax
|
| 9 |
+
from fixtures import frozen_states,training_probe,digest
|
| 10 |
+
from features import token_embeddings,pool_endpoints,endpoint_plan
|
| 11 |
+
from core import make_kernels
|
| 12 |
+
from state import initialize,optimizer
|
| 13 |
+
from train import make_updates
|
| 14 |
+
root=Path(__file__).resolve().parent;encoder,parents,_,_,hashes=frozen_states();assert jax.default_backend()==args.device;rng=np.random.default_rng(20263210);projection=jax.tree_util.tree_map(lambda a:jnp.asarray(rng.normal(0,.01,a.shape),a.dtype),initialize());sg,_,mg,_=make_kernels();gradients={'X':mg,'Z':sg};encode=jax.jit(token_embeddings);pool=jax.jit(pool_endpoints);reference={};checks=[]
|
| 15 |
+
for basis in ['X','Z']:
|
| 16 |
+
row,dets,y,base,fields,source=training_probe(basis,3,2);indices,weights=endpoint_plan(fields[0],fields[1],fields[2],fields[6])
|
| 17 |
+
with jax.default_matmul_precision('highest'):
|
| 18 |
+
embedding=pool(encode(encoder,dets,fields[5],basis=='X',3),indices,weights);g,loss,error=gradients[basis](projection[basis],parents[basis],dets,y,base,embedding,*fields)
|
| 19 |
+
arrays={'embedding':np.asarray(embedding),'loss':np.asarray(loss),**{f'gradient_{i}':np.asarray(v) for i,v in enumerate(jax.tree_util.tree_leaves(g))}};check={'condition':row['name'],'loss':float(loss),'gradient_norm':float(optax.global_norm(g))}
|
| 20 |
+
if args.device=='cpu':reference.update({basis+'__'+k:v for k,v in arrays.items()})
|
| 21 |
+
else:
|
| 22 |
+
with np.load(root/'backend_reference.npz',allow_pickle=False) as f:
|
| 23 |
+
differences=[a-f[basis+'__'+k] for k,a in arrays.items() if k.startswith('gradient')];maximum=max(float(abs(x).max()) for x in differences);relative=float(np.sqrt(sum(np.sum(x.astype(float)**2) for x in differences)/sum(np.sum(f[basis+'__'+k].astype(float)**2) for k in arrays if k.startswith('gradient'))));emb_error=float(abs(arrays['embedding']-f[basis+'__embedding']).max());loss_error=float(abs(arrays['loss']-f[basis+'__loss']))
|
| 24 |
+
assert emb_error<2e-5 and loss_error<2e-6 and maximum<1e-5 and relative<1e-4,(basis,emb_error,loss_error,maximum,relative);check.update(embedding_max_abs=emb_error,loss_max_abs=loss_error,gradient_max_abs=maximum,gradient_relative_l2=relative)
|
| 25 |
+
checks.append(check);print(json.dumps(check),flush=True)
|
| 26 |
+
if args.device=='cpu':np.savez(root/'backend_reference.npz',**reference)
|
| 27 |
+
pilots=[]
|
| 28 |
+
if args.device=='gpu':
|
| 29 |
+
original=[np.asarray(x).copy() for x in jax.tree_util.tree_leaves((encoder,parents))];zero=initialize();optim=optimizer(.0005);updates=make_updates(optim)
|
| 30 |
+
for basis in ['X','Z']:
|
| 31 |
+
row,dets,y,base,fields,source=training_probe(basis,25,512);indices,weights=endpoint_plan(fields[0],fields[1],fields[2],fields[6]);started=time.monotonic();embedding=pool(encode(encoder,dets,fields[5],basis=='X',25),indices,weights);result=updates[basis](zero[basis],optim.init(zero[basis]),parents[basis],dets,y,base,embedding,*fields);jax.block_until_ready(result);peak=int((jax.devices()[0].memory_stats() or {}).get('peak_bytes_in_use',0));assert 0<peak<75*1024**3 and np.isfinite(float(result[2])) and int(result[1][1][0].count)==1;assert all(np.array_equal(a,b) for a,b in zip(original,jax.tree_util.tree_leaves((encoder,parents))));pilots.append({'condition':row['name'],'batch':512,'seconds':time.monotonic()-started,'peak_gpu_bytes':peak,'loss':float(result[2]),'gradient_norm':float(result[4]),'discarded_updates':1,'frozen_parameters_exact':True});print(json.dumps(pilots[-1]),flush=True)
|
| 32 |
+
report={'status':'passed','device':str(jax.devices()[0]),'comparison_precision':'Highest float32 only for CPU/CUDA comparison; production pilots use native precision','cases':checks,'pilots':pilots,'frozen_weights_sha256':hashes,'source_sha256':{n:digest(root/n) for n in ['backend_control.py','train.py','core.py','features.py','conditional_tokens.py','fixtures.py','model.py','state.py','aux_encoder.py','axial_base.py','confidence_joint.py','joint_mixture.py','checkpoint_gradient.py','exact.py']},'test_data_used':False};(root/f'backend_control_{args.device}.json').write_text(json.dumps(report,indent=2)+'\n')
|
tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S044/training_sources/conditional_edge_projection1/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/S044/training_sources/conditional_edge_projection1/compiled.py
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Retain bounded compiled attention executables across global JAX cache clears."""
|
| 2 |
+
from collections import OrderedDict
|
| 3 |
+
import jax
|
| 4 |
+
|
| 5 |
+
class PersistentCompiled:
|
| 6 |
+
def __init__(self,function,max_executables=2):
|
| 7 |
+
self.function=jax.jit(function);self.executables=OrderedDict();self.max_executables=max_executables;self.compilations=0
|
| 8 |
+
def __call__(self,*args):
|
| 9 |
+
leaves,tree=jax.tree_util.tree_flatten(args)
|
| 10 |
+
signatures=[]
|
| 11 |
+
for value in leaves:
|
| 12 |
+
abstract=jax.core.get_aval(value)
|
| 13 |
+
signatures.append((abstract.shape,str(abstract.dtype),bool(abstract.weak_type)))
|
| 14 |
+
key=(tree,tuple(signatures))
|
| 15 |
+
if key not in self.executables:
|
| 16 |
+
self.executables[key]=self.function.lower(*args).compile();self.compilations+=1
|
| 17 |
+
while len(self.executables)>self.max_executables:self.executables.popitem(last=False)
|
| 18 |
+
self.executables.move_to_end(key)
|
| 19 |
+
return self.executables[key](*args)
|
tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S044/training_sources/conditional_edge_projection1/conditional_tokens.py
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Deterministic conditional token representations from eight masking partitions."""
|
| 2 |
+
import jax
|
| 3 |
+
import jax.numpy as jnp
|
| 4 |
+
from aux_encoder import features,encode
|
| 5 |
+
|
| 6 |
+
def conditional_tokens(parameters,dets,grid,basis,rounds,colors):
|
| 7 |
+
valid=grid!=600
|
| 8 |
+
def body(color,result):
|
| 9 |
+
mask=jnp.broadcast_to((colors==color)&valid,(len(dets),26,24));inputs,active,_,_=features(dets,grid,basis,rounds,mask);tokens=encode(parameters,inputs,active,training=False);return jnp.where(mask[:,:,:,None],tokens,result)
|
| 10 |
+
return jax.lax.fori_loop(0,8,body,jnp.zeros((len(dets),26,24,parameters['input_w'].shape[-1]),jnp.float32))
|
| 11 |
+
|
| 12 |
+
def conditional_logits(parameters,dets,grid,basis,rounds,colors):
|
| 13 |
+
h=conditional_tokens(parameters,dets,grid,basis,rounds,colors);return (h@parameters['mask_w'])[:,:,:,0]+parameters['mask_b'][0]
|
| 14 |
+
|
| 15 |
+
# Fixed ideal-slot partition, generated once by seed20263501.
|
| 16 |
+
COLORS=[[6, 2, 0, 7, 3, 2, 3, 1, 2, 2, 4, 7, 4, 2, 4, 0, 2, 5, 0, 3, 6, 3, 6, 4], [1, 5, 4, 4, 5, 4, 5, 1, 0, 1, 3, 1, 5, 1, 7, 5, 1, 4, 6, 2, 3, 5, 6, 6], [7, 7, 6, 1, 2, 7, 7, 7, 1, 6, 0, 2, 6, 7, 2, 5, 1, 3, 4, 0, 4, 5, 1, 5], [4, 3, 0, 3, 3, 1, 5, 6, 0, 3, 2, 7, 4, 4, 4, 5, 7, 3, 2, 0, 0, 6, 1, 5], [4, 2, 7, 5, 1, 6, 3, 2, 1, 1, 0, 6, 7, 5, 2, 4, 4, 1, 5, 0, 2, 7, 1, 7], [3, 4, 2, 5, 2, 1, 6, 0, 0, 7, 2, 5, 4, 7, 6, 6, 4, 7, 6, 4, 7, 2, 3, 3], [0, 3, 4, 7, 4, 7, 2, 4, 7, 5, 7, 2, 1, 6, 4, 0, 6, 0, 4, 4, 4, 6, 1, 0], [5, 3, 7, 0, 7, 2, 3, 5, 5, 7, 0, 2, 0, 4, 0, 4, 1, 1, 1, 1, 4, 2, 7, 3], [0, 3, 2, 5, 7, 5, 1, 7, 6, 2, 0, 5, 7, 1, 6, 6, 6, 4, 6, 0, 6, 6, 2, 1], [6, 0, 4, 7, 1, 6, 2, 7, 0, 2, 4, 1, 3, 7, 7, 0, 3, 5, 4, 4, 5, 2, 2, 1], [2, 1, 5, 3, 2, 6, 4, 4, 4, 4, 0, 4, 0, 0, 2, 4, 3, 6, 3, 7, 4, 7, 2, 7], [2, 0, 4, 0, 4, 1, 6, 0, 1, 5, 2, 7, 4, 3, 6, 6, 0, 3, 0, 2, 1, 0, 6, 1], [1, 6, 1, 5, 4, 4, 1, 4, 6, 3, 0, 2, 6, 1, 1, 6, 0, 6, 0, 4, 6, 3, 3, 7], [5, 1, 7, 0, 2, 0, 0, 5, 3, 1, 2, 0, 3, 3, 3, 1, 3, 1, 3, 3, 7, 5, 3, 5], [2, 6, 4, 1, 7, 4, 7, 3, 2, 6, 4, 1, 2, 4, 6, 6, 3, 6, 5, 7, 3, 4, 6, 0], [7, 5, 4, 3, 0, 4, 6, 1, 4, 1, 2, 6, 5, 1, 3, 1, 3, 0, 7, 6, 5, 0, 0, 6], [1, 1, 3, 2, 6, 6, 7, 2, 5, 7, 7, 3, 6, 5, 4, 2, 6, 2, 5, 3, 3, 3, 1, 2], [4, 7, 4, 1, 4, 4, 1, 2, 0, 6, 6, 1, 1, 1, 6, 1, 0, 1, 4, 2, 4, 0, 3, 6], [7, 7, 6, 7, 0, 0, 7, 4, 5, 2, 4, 2, 2, 0, 6, 5, 6, 3, 5, 1, 6, 3, 2, 3], [6, 3, 5, 1, 7, 4, 0, 3, 4, 4, 5, 7, 5, 3, 1, 3, 2, 0, 7, 6, 5, 7, 3, 6], [6, 1, 7, 6, 4, 5, 3, 0, 6, 4, 4, 7, 5, 4, 1, 1, 3, 7, 5, 2, 0, 1, 7, 0], [1, 2, 3, 5, 7, 2, 1, 4, 4, 7, 7, 2, 1, 1, 5, 3, 7, 3, 4, 7, 3, 0, 0, 4], [7, 6, 0, 0, 7, 4, 2, 6, 0, 0, 2, 5, 5, 3, 4, 1, 0, 2, 2, 2, 3, 0, 2, 3], [1, 5, 2, 6, 3, 6, 0, 4, 5, 1, 6, 5, 4, 3, 5, 3, 6, 1, 3, 0, 0, 2, 7, 7], [5, 5, 6, 7, 3, 0, 7, 3, 6, 5, 4, 1, 4, 3, 6, 6, 5, 0, 4, 0, 7, 3, 3, 2], [6, 5, 3, 2, 6, 7, 6, 7, 7, 7, 5, 1, 1, 0, 1, 7, 6, 2, 4, 2, 0, 0, 1, 2]]
|
tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S044/training_sources/conditional_edge_projection1/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/S044/training_sources/conditional_edge_projection1/contextual.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Portable structured decoder with frozen endpoint embeddings and learned projections."""
|
| 2 |
+
import numpy as np
|
| 3 |
+
from d5_preconditional_edge_contextual import NeuralD5Decoder as PreviousDecoder
|
| 4 |
+
from conditional_edge_compiled import PersistentCompiled
|
| 5 |
+
from conditional_edge_features import token_embeddings,pool_endpoints,endpoint_plan
|
| 6 |
+
from conditional_edge_core import make_kernels
|
| 7 |
+
|
| 8 |
+
class NeuralD5Decoder(PreviousDecoder):
|
| 9 |
+
def __init__(self):
|
| 10 |
+
super().__init__();_,single,_,mixture=make_kernels();self.edge_infer={'X':PersistentCompiled(mixture),'Z':PersistentCompiled(single)};self.edge_encode=PersistentCompiled(token_embeddings);self.edge_pool=PersistentCompiled(pool_endpoints);self.edge_weights={}
|
| 11 |
+
|
| 12 |
+
def predict(self,root,record,settings,packed,num_detectors,batch=512,initial_priors=None,**kwargs):
|
| 13 |
+
extension=settings.get('conditional_edge_projection')
|
| 14 |
+
if extension is None:return super().predict(root,record,settings,packed,num_detectors,batch,initial_priors=initial_priors,**kwargs)
|
| 15 |
+
import jax.numpy as jnp
|
| 16 |
+
from conditional import load_state
|
| 17 |
+
from turbo import TurboDecoder
|
| 18 |
+
parent_settings=extension['parent_settings'];assert settings['prior_pass']==parent_settings['prior_pass'] and not parent_settings.get('blend_turbo',False)
|
| 19 |
+
plan=dict(np.load(root/record['neural_d5_plan'],allow_pickle=False));basis='X' if bool(np.max(plan['static'][:,127])) else 'Z';rounds=int(round(float(np.max(plan['static'][:,124]))*25));key=(extension['weights'],extension['encoder_weights'],basis)
|
| 20 |
+
if key not in self.edge_weights:
|
| 21 |
+
with np.load(root/extension['weights'],allow_pickle=False) as f:projection={k:jnp.asarray(f['X_'+k]) for k in ['expert0','expert1']} if basis=='X' else jnp.asarray(f['Z'])
|
| 22 |
+
with np.load(root/extension['encoder_weights'],allow_pickle=False) as f:encoder={k:jnp.asarray(f[k]) for k in f.files}
|
| 23 |
+
path=parent_settings['confidence_joint']['weights'] if basis=='X' else parent_settings['weights']
|
| 24 |
+
with np.load(root/path,allow_pickle=False) as f:
|
| 25 |
+
if basis=='X':
|
| 26 |
+
parent={k:{} for k in ['expert0','expert1','gate']}
|
| 27 |
+
for name in f.files:part,field=name.split('__',1);parent[part][field]=jnp.asarray(f[name])
|
| 28 |
+
else:parent={k:jnp.asarray(f[k]) for k in f.files}
|
| 29 |
+
self.edge_weights[key]=(projection,encoder,parent)
|
| 30 |
+
projection,encoder,parent=self.edge_weights[key];dets=np.unpackbits(packed,axis=1,count=num_detectors,bitorder='little');passes=settings['prior_pass'];assert passes==(3 if basis=='X' else 5)
|
| 31 |
+
if initial_priors is not None:priors=np.asarray(initial_priors)
|
| 32 |
+
elif 'turbo_plan' in record:
|
| 33 |
+
decoder=TurboDecoder(load_state(root/record['turbo_plan']),batch=batch);_,captured=decoder.predict(dets,damping=1.,iterations=passes,last_only=True,message_clip=8.,return_priors_at=(passes,),skip_final_logical=True);priors=captured[passes];del decoder
|
| 34 |
+
else:
|
| 35 |
+
fixed=dict(np.load(root/record['plan'],allow_pickle=False))['probabilities'];priors=np.broadcast_to(fixed[None],(len(dets),len(fixed)))
|
| 36 |
+
length=((int(plan['operation_count'])+511)//512)*512;assert priors.shape==(len(dets),int(plan['operation_count']));base=np.log(np.clip(priors,1e-7,1-1e-7)/np.clip(1-priors,1e-7,1-1e-7));base=np.pad(base,((0,0),(0,length-base.shape[1]))).astype(np.float32);dets=np.pad(dets,((0,0),(0,601-num_detectors)))
|
| 37 |
+
fields=[plan[k][:length] for k in ['context','static','valid','masks','measured']]+[plan[k] for k in ['grid','measurement_indices','counts']];indices,weights=endpoint_plan(fields[0],fields[1],fields[2],fields[6]);output=[]
|
| 38 |
+
for pos in range(0,len(dets),batch):
|
| 39 |
+
count=min(batch,len(dets)-pos);ds=np.pad(dets[pos:pos+batch],((0,batch-count),(0,0)));z=np.pad(base[pos:pos+batch],((0,batch-count),(0,0)));tokens=self.edge_encode(encoder,ds,plan['grid'],basis=='X',rounds);embedding=self.edge_pool(tokens,indices,weights);q=self.edge_infer[basis](projection,parent,ds,z,embedding,*fields);output.append(np.asarray(q)[:count])
|
| 40 |
+
return np.concatenate(output).astype(np.float32)
|
tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S044/training_sources/conditional_edge_projection1/control_cpu.py
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Endpoint geometry, neutral attachment, independent gradients and discarded state replay."""
|
| 2 |
+
import os
|
| 3 |
+
os.environ['JAX_PLATFORMS']='cpu';os.environ['OPENBLAS_NUM_THREADS']='1';os.environ['OMP_NUM_THREADS']='1';os.sched_setaffinity(0,sorted(os.sched_getaffinity(0))[:4])
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
import json,tempfile
|
| 6 |
+
import numpy as np
|
| 7 |
+
import jax,jax.numpy as jnp,optax
|
| 8 |
+
from fixtures import frozen_states,training_probe,digest
|
| 9 |
+
from features import endpoint_plan,token_embeddings,pool_endpoints
|
| 10 |
+
from model import probabilities
|
| 11 |
+
from base_edge import probabilities as original_probabilities
|
| 12 |
+
from confidence_joint import gate_features,gate_logit,mix_predictions
|
| 13 |
+
from core import make_kernels
|
| 14 |
+
from exact import make_decoder
|
| 15 |
+
root=Path(__file__).resolve().parent;encoder,parents,_,_,hashes=frozen_states();original=[np.asarray(x).copy() for x in jax.tree_util.tree_leaves((encoder,parents))];sg,si,mg,mi=make_kernels();decode=make_decoder(14);checks=[];rng=np.random.default_rng(20263210);encode=jax.jit(token_embeddings)
|
| 16 |
+
for basis in ['X','Z']:
|
| 17 |
+
row,dets,y,base,fields,source=training_probe(basis,3);context,static,valid,masks,measured,grid,mapping,counts=fields;indices,weight=endpoint_plan(context,static,valid,mapping);tokens=encode(encoder,dets,grid,basis=='X',3);embedding=jax.jit(pool_endpoints)(tokens,indices,weight);reference=np.zeros(embedding.shape,np.float64);flat=np.asarray(tokens).reshape(len(dets),624,64)
|
| 18 |
+
for op in range(len(context)):
|
| 19 |
+
selected=indices[op][weight[op]>0]
|
| 20 |
+
if len(selected):reference[:,op]=flat[:,selected].astype(float).mean(axis=1)
|
| 21 |
+
pool_error=float(abs(np.asarray(embedding)-reference).max());assert pool_error<1e-6;assert not np.asarray(embedding)[:,valid==0].any()
|
| 22 |
+
frozen=parents[basis];is_mixture=basis=='X';projection={k:jnp.zeros((64,64),jnp.float32) for k in ['expert0','expert1']} if is_mixture else jnp.zeros((64,64),jnp.float32);infer=mi if is_mixture else si;gradient=mg if is_mixture else sg
|
| 23 |
+
zero=infer(projection,frozen,dets,base,embedding,*fields)
|
| 24 |
+
if is_mixture:
|
| 25 |
+
q=jnp.stack([decode(dets,original_probabilities(frozen[k],dets,base,context,static,valid,grid,mapping,counts),masks,measured) for k in ['expert0','expert1']],axis=1);expected=mix_predictions(q,gate_logit(frozen['gate'],gate_features(dets,grid,static,q)))
|
| 26 |
+
else:expected=decode(dets,original_probabilities(frozen,dets,base,context,static,valid,grid,mapping,counts),masks,measured)
|
| 27 |
+
neutral=float(abs(zero-expected).max());assert neutral<2e-7
|
| 28 |
+
trial=jax.tree_util.tree_map(lambda v:jnp.asarray(rng.normal(0,.01,v.shape),v.dtype),projection)
|
| 29 |
+
def independent_loss(p):
|
| 30 |
+
q=infer(p,frozen,dets,base,embedding,*fields);return -jnp.mean(jnp.log(jnp.where(y.astype(bool),q,1-q)))
|
| 31 |
+
reference_loss,reference_gradient=jax.jit(jax.value_and_grad(independent_loss))(trial);actual,loss,error=gradient(trial,frozen,dets,y,base,embedding,*fields);leaves=jax.tree_util.tree_leaves(actual);ref=jax.tree_util.tree_leaves(reference_gradient);relative=float(np.sqrt(sum(np.sum((np.asarray(a)-np.asarray(b)).astype(float)**2) for a,b in zip(leaves,ref))/max(sum(np.sum(np.asarray(b,dtype=float)**2) for b in ref),1e-24)));assert relative<1e-4 and abs(float(loss-reference_loss))<1e-6 and float(optax.global_norm(actual))>0,(basis,relative,float(loss-reference_loss))
|
| 32 |
+
optim=optax.chain(optax.clip_by_global_norm(1),optax.adamw(.001,weight_decay=1e-4));state=optim.init(projection)
|
| 33 |
+
@jax.jit
|
| 34 |
+
def update(p,s):
|
| 35 |
+
g,loss,_=gradient(p,frozen,dets,y,base,embedding,*fields);changes,s=optim.update(g,s,p);return optax.apply_updates(p,changes),s,loss
|
| 36 |
+
p1,s1,_=update(projection,state);p2,s2,_=update(p1,s1);leaves,tree=jax.tree_util.tree_flatten((p1,s1))
|
| 37 |
+
with tempfile.TemporaryDirectory(prefix='masked-edge-control-') as temp:
|
| 38 |
+
path=Path(temp)/'state.npz';np.savez(path,**{f'arr_{i}':np.asarray(v) for i,v in enumerate(leaves)})
|
| 39 |
+
with np.load(path,allow_pickle=False) as f:loaded=jax.tree_util.tree_unflatten(tree,[jnp.asarray(f[f'arr_{i}']) for i in range(len(leaves))])
|
| 40 |
+
rp,rs,_=update(*loaded)
|
| 41 |
+
assert all(np.array_equal(a,b) for a,b in zip(jax.tree_util.tree_leaves((p2,s2)),jax.tree_util.tree_leaves((rp,rs))))
|
| 42 |
+
assert int(s2[1][0].count)==2 and float(optax.global_norm(p2))>0
|
| 43 |
+
q=infer(p2,frozen,dets,base,embedding,*fields);reverse=infer(p2,frozen,dets[::-1].copy(),base[::-1].copy(),embedding[::-1],*fields);assert np.array_equal(q,reverse[::-1]);assert all(np.array_equal(a,b) for a,b in zip(original,jax.tree_util.tree_leaves((encoder,parents))))
|
| 44 |
+
checks.append({'condition':row['name'],'endpoint_pool_reference_max_abs':pool_error,'neutral_original_probability_max_abs':neutral,'independent_whole_contraction_gradient_relative_l2':relative,'loss_difference':float(abs(loss-reference_loss)),'trainable_projection_count':sum(v.size for v in jax.tree_util.tree_leaves(projection)),'actual_projection_gradient_norm':float(optax.global_norm(actual)),'frozen_encoder_parent_and_gate_exact':True,'two_updates_plus_serialized_resume_exact':True,'order_exact':True,'source':source});print(json.dumps(checks[-1]),flush=True)
|
| 45 |
+
report={'status':'passed','checks':checks,'discarded_optimizer_updates_including_resume':6,'scope':'CPU prototype only, four primary discarded updates plus two resumed replays. No main optimizer schedule, fitting or validation selection. No GPU queue.','source_sha256':{p.name:digest(p) for p in root.glob('*.py')},'frozen_weights_sha256':hashes,'test_data_used':False};(root/'control_cpu.json').write_text(json.dumps(report,indent=2)+'\n')
|
tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S044/training_sources/conditional_edge_projection1/core.py
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Projection-only exact gradients, including the frozen confidence gate's input path."""
|
| 2 |
+
import jax
|
| 3 |
+
import jax.numpy as jnp
|
| 4 |
+
from model import probabilities
|
| 5 |
+
from checkpoint_gradient import make_loss_and_grad
|
| 6 |
+
from exact import make_decoder
|
| 7 |
+
from confidence_joint import gate_features,gate_logit,mixture_terms,mix_predictions,expert_adjoint_factors
|
| 8 |
+
|
| 9 |
+
def make_kernels(width=14,block_size=32):
|
| 10 |
+
exact=make_loss_and_grad(width,block_size);decode=make_decoder(width)
|
| 11 |
+
@jax.jit
|
| 12 |
+
def single_gradient(projection,frozen,dets,labels,base,embedding,context,static,valid,masks,measured,grid,mapping,counts):
|
| 13 |
+
p,pull=jax.vjp(lambda v:probabilities(v,frozen,dets,base,embedding,context,static,valid,grid,mapping,counts),projection);loss,prediction,adjoint=exact(dets,labels,p,masks,measured)
|
| 14 |
+
return pull(adjoint/len(dets))[0],loss.mean(),jnp.mean((prediction>=.5)!=labels)
|
| 15 |
+
@jax.jit
|
| 16 |
+
def single_infer(projection,frozen,dets,base,embedding,context,static,valid,masks,measured,grid,mapping,counts):
|
| 17 |
+
return decode(dets,probabilities(projection,frozen,dets,base,embedding,context,static,valid,grid,mapping,counts),masks,measured)
|
| 18 |
+
@jax.jit
|
| 19 |
+
def mixture_gradient(projections,frozen,dets,labels,base,embedding,context,static,valid,masks,measured,grid,mapping,counts):
|
| 20 |
+
p0,pull0=jax.vjp(lambda v:probabilities(v,frozen['expert0'],dets,base,embedding,context,static,valid,grid,mapping,counts),projections['expert0']);loss0,pred0,g0=exact(dets,labels,p0,masks,measured)
|
| 21 |
+
p1,pull1=jax.vjp(lambda v:probabilities(v,frozen['expert1'],dets,base,embedding,context,static,valid,grid,mapping,counts),projections['expert1']);loss1,pred1,g1=exact(dets,labels,p1,masks,measured)
|
| 22 |
+
losses=jnp.stack([loss0,loss1],axis=1);prediction=jnp.stack([pred0,pred1],axis=1)
|
| 23 |
+
z,pull_gate=jax.vjp(lambda q:gate_logit(frozen['gate'],gate_features(dets,grid,static,q)),prediction);loss,responsibility,adjoint,coefficients=mixture_terms(losses,z);extra=pull_gate(adjoint)[0];factor=expert_adjoint_factors(losses,labels,responsibility,extra)
|
| 24 |
+
gradient={'expert0':pull0(g0*factor[:,0][None]/len(dets))[0],'expert1':pull1(g1*factor[:,1][None]/len(dets))[0]};q=mix_predictions(prediction,z)
|
| 25 |
+
return gradient,loss.mean(),jnp.mean((q>=.5)!=labels)
|
| 26 |
+
@jax.jit
|
| 27 |
+
def mixture_infer(projections,frozen,dets,base,embedding,context,static,valid,masks,measured,grid,mapping,counts):
|
| 28 |
+
q=jnp.stack([decode(dets,probabilities(projections[k],frozen[k],dets,base,embedding,context,static,valid,grid,mapping,counts),masks,measured) for k in ['expert0','expert1']],axis=1)
|
| 29 |
+
return mix_predictions(q,gate_logit(frozen['gate'],gate_features(dets,grid,static,q)))
|
| 30 |
+
return single_gradient,single_infer,mixture_gradient,mixture_infer
|
tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S044/training_sources/conditional_edge_projection1/data.py
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Full authorized hardware data with the frozen parent's physical-prior cache lineage."""
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
import json,hashlib
|
| 4 |
+
import numpy as np
|
| 5 |
+
from fixtures import frozen_states,digest,ROOT,RESEARCH
|
| 6 |
+
from features import endpoint_plan
|
| 7 |
+
|
| 8 |
+
def align(ids,target):
|
| 9 |
+
assert len(np.unique(ids))==len(ids);order=np.argsort(ids);location=np.searchsorted(ids[order],target);assert np.all(location<len(order));index=order[location];assert np.array_equal(ids[index],target);return index
|
| 10 |
+
|
| 11 |
+
def load_all(splits=('train','validation')):
|
| 12 |
+
_,_,package,config,_=frozen_states();rows=sorted([x for x in json.loads(Path('/workspace/data/train/manifest.json').read_text())['conditions'] if x['distance']==5],key=lambda x:x['name']);items=[];records=[]
|
| 13 |
+
for row in rows:
|
| 14 |
+
path=package/config['conditions'][row['name']]['neural_d5_plan']
|
| 15 |
+
with np.load(path,allow_pickle=False) as f:item={k:f[k] for k in f.files}
|
| 16 |
+
length=((int(item['operation_count'])+511)//512)*512;item['length']=length;item['row']=row
|
| 17 |
+
for key in ['context','static','valid','masks','measured']:item[key]=item[key][:length]
|
| 18 |
+
item['endpoint_indices'],item['endpoint_weights']=endpoint_plan(item['context'],item['static'],item['valid'],item['measurement_indices']);prior_pass=config['neural_d5'][row['group']]['prior_pass'];sources={}
|
| 19 |
+
for split in splits:
|
| 20 |
+
record=next(x for x in json.loads((Path('/workspace/data')/split/'manifest.json').read_text())['conditions'] if x['name']==row['name']);path=Path('/workspace/data')/split/record['arrays'];assert digest(path)==record['arrays_sha256']
|
| 21 |
+
with np.load(path,allow_pickle=False) as f:ids=f['sample_ids'];labels=f['labels'];packed=f['detectors']
|
| 22 |
+
if split=='train':
|
| 23 |
+
cache=RESEARCH/('learned_d5/full_training_priors3' if prior_pass==3 else 'full_prior5/cache1')/(row['name']+'.npz')
|
| 24 |
+
with np.load(cache,allow_pickle=False) as f:ix=align(f['sample_ids'],ids);prior=f[f'priors{prior_pass}'][ix]
|
| 25 |
+
lineage='Own generated full-training priors; opaque-ID equality alignment for every row.'
|
| 26 |
+
else:
|
| 27 |
+
cache=RESEARCH/'masked_edge_projection/runtime_validation_priors'/(row['name']+'.npz')
|
| 28 |
+
with np.load(cache,allow_pickle=False) as f:ix=align(f['sample_ids'],ids);prior=f[f'priors{prior_pass}'][ix]
|
| 29 |
+
lineage='Own exact packaged-runtime validation priors, batch512, pass3X/pass5Z, generated from detection events only. Explicit opaque-ID equality alignment. Rebuilt before main after historical-cache numerical discrepancy; original evidence and unchanged audit tolerance retained in masked_edge_projection/VALIDATION_CACHE_RECOVERY_PLAN.json.'
|
| 30 |
+
assert prior.shape==(len(ids),int(item['operation_count']))
|
| 31 |
+
logits=np.log(np.clip(prior,1e-7,1-1e-7)/np.clip(1-prior,1e-7,1-1e-7)).astype(np.float32);item[split+'_base']=np.pad(logits,((0,0),(0,length-logits.shape[1])));item[split+'_dets']=np.pad(np.unpackbits(packed,axis=1,count=row['num_detectors'],bitorder='little'),((0,0),(0,601-row['num_detectors'])));item[split+'_labels']=labels;item[split+'_ids']=ids
|
| 32 |
+
sources[split]={'arrays_sha256':record['arrays_sha256'],'cache':str(cache),'cache_sha256':digest(cache),'ID_sha256':hashlib.sha256(ids.tobytes()).hexdigest(),'lineage':lineage}
|
| 33 |
+
items.append(item);records.append({'condition':row['name'],'feature_plan_sha256':digest(package/config['conditions'][row['name']]['neural_d5_plan']),'prior_pass':prior_pass,'sources':sources})
|
| 34 |
+
assert len(items)==26
|
| 35 |
+
if 'train' in splits:assert sum(len(x['train_labels']) for x in items)==516880
|
| 36 |
+
return items,records
|
| 37 |
+
|
| 38 |
+
def fields(item):return [item[k] for k in ['context','static','valid','masks','measured','grid','measurement_indices','counts']]
|