sci-run / tasks /surface-code-decoding /surface-code-decoding-astra-xhigh-1h100-48h-20261020b /finalization /submission /conditional.py
Download tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/finalization/submission/conditional.py from s42chen/sci-run: direct link, hf CLI and curl.
- Browser
- Download file 5.47 kB
-
https://huggingface.co/datasets/s42chen/sci-run/resolve/main/tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/finalization/submission/conditional.py
- Command line
-
hf download hf://datasets/s42chen/sci-run/tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/finalization/submission/conditional.py
-
curl -L -o conditional.py https://huggingface.co/datasets/s42chen/sci-run/resolve/main/tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/finalization/submission/conditional.py
5.47 kB
| """Exact CSS marginals, with soft conditioning on the complementary syndrome.""" | |
| import os | |
| os.environ['XLA_PYTHON_CLIENT_PREALLOCATE']='false' | |
| os.environ['OPENBLAS_NUM_THREADS']='1' | |
| from pathlib import Path | |
| import collections,time | |
| import numpy as np | |
| import stim | |
| import jax | |
| import jax.numpy as jnp | |
| from exact import parse_errors,make_plan,make_decoder,make_marginals_fb | |
| def save_state(path,state): | |
| flat={k:v for k,v in state.items() if k not in ['on','off']} | |
| for which in ['on','off']: | |
| flat.update({which+'__'+k:v for k,v in state[which].items()}) | |
| np.savez(path,**flat) | |
| def load_state(path): | |
| flat=dict(np.load(path,allow_pickle=False));state={'on':{},'off':{}} | |
| for k,v in flat.items(): | |
| if '__' in k: | |
| which,key=k.split('__',1);state[which][key]=v | |
| else:state[k]=v | |
| return state | |
| def build(dem): | |
| coords=dem.get_detector_coordinates() | |
| first={tuple(c[:2]) for c in coords.values() if c[-1]==0} | |
| on=[d for d,c in coords.items() if tuple(c[:2]) in first] | |
| off=[d for d,c in coords.items() if tuple(c[:2]) not in first] | |
| maps=[{d:i for i,d in enumerate(ds)} for ds in [on,off]] | |
| errors=parse_errors(dem) | |
| groups=[{},{}] | |
| orig_p=[];orig_group=[[],[]] | |
| for ds,l,p in errors: | |
| orig_p.append(p) | |
| for k,idx in enumerate(maps): | |
| key=tuple(sorted(idx[d] for d in ds if d in idx)),l if k==0 else 0 | |
| if not key[0] and not key[1]: | |
| orig_group[k].append(-1) | |
| continue | |
| if key not in groups[k]:groups[k][key]=[len(groups[k]),1.] | |
| groups[k][key][1]*=1-2*p | |
| orig_group[k].append(groups[k][key][0]) | |
| plans=[] | |
| for k,g in enumerate(groups): | |
| sub=stim.DetectorErrorModel() | |
| for (ds,l),(_,bias) in g.items(): | |
| sub.append('error',[(1-bias)/2],[stim.target_relative_detector_id(d) for d in ds]+([stim.target_logical_observable_id(0)] if l else [])) | |
| for d,i in maps[k].items():sub.append('detector',coords[d],[stim.target_relative_detector_id(i)]) | |
| plan=make_plan(sub) | |
| if k==1: | |
| # No logical observable is tracked in the complementary partition. | |
| assert np.all((plan['masks'] & 1)==0) | |
| plan['masks'] >>= 1 | |
| plan['width'] -= 1 | |
| plans.append(plan) | |
| # Relate each original error to its complementary parity's likelihood gradient. | |
| step_from_source={int(v):i for i,v in enumerate(plans[1]['source_indices']) if v>=0} | |
| offstep=np.array([step_from_source.get(g,0) for g in orig_group[1]],np.int32) | |
| p=np.array(orig_p,np.float32) | |
| offp=plans[1]['probabilities'][offstep] | |
| coeff=p*(1-p)*(1-2*offp)/(1-2*p) | |
| coeff[np.array(orig_group[1])<0]=0 | |
| members=[[] for _ in groups[0]] | |
| for i,g in enumerate(orig_group[0]): | |
| if g>=0:members[g].append(i) | |
| size=max(map(len,members)) | |
| member_array=np.array([m+[len(p)]*(size-len(m)) for m in members],np.int32) | |
| return {'on':plans[0],'off':plans[1],'on_indices':np.array(on,np.int32),'off_indices':np.array(off,np.int32), | |
| 'p':p,'coeff':coeff,'offstep':offstep,'members':member_array} | |
| class ConditionalDecoder: | |
| def __init__(self, state, batch=128): | |
| self.state=state;self.batch=batch | |
| self.marginals=make_marginals_fb(int(state['off']['width'])) | |
| self.decode=make_decoder(int(state['on']['width'])) | |
| self.args=[jax.device_put(state['off'][k]) for k in ['probabilities','masks','measured']] | |
| self.onargs=[jax.device_put(state['on'][k]) for k in ['masks','measured']] | |
| p,coeff,offstep,members=[jnp.asarray(state[k]) for k in ['p','coeff','offstep','members']] | |
| src=jnp.asarray(state['on']['source_indices']) | |
| def probabilities(grad,strength): | |
| q=jnp.clip(p[None,:]+strength*coeff[None,:]*grad[:,offstep],1e-7,1-1e-7) | |
| q=jnp.pad(q,((0,0),(0,1))) | |
| bias=jnp.prod(1-2*q[:,members],axis=-1) | |
| v=(1-bias)/2 | |
| return jnp.where(src[:,None]>=0,v[:,jnp.maximum(src,0)].T,0) | |
| self.probabilities=probabilities | |
| def predict(self,dets,strengths=(0.,0.5,1.)): | |
| outputs=[[] for s in strengths] | |
| for start in range(0,len(dets),self.batch): | |
| n=min(self.batch,len(dets)-start) | |
| ds=np.pad(dets[start:start+n],((0,self.batch-n),(0,0))) | |
| logz,grad=self.marginals(ds[:,self.state['off_indices']],*self.args) | |
| for i,strength in enumerate(strengths): | |
| probabilities=self.probabilities(grad,strength) | |
| result=self.decode(ds[:,self.state['on_indices']],probabilities,*self.onargs) | |
| outputs[i].append(np.asarray(result)[:n]) | |
| return np.stack([np.concatenate(v) for v in outputs],axis=1) | |
| if __name__=='__main__': | |
| import sys | |
| path=Path(sys.argv[1]);n=int(sys.argv[2]) if len(sys.argv)>2 else 512 | |
| t=time.time();dem=stim.DetectorErrorModel.from_file(path/'pij_from_even_for_odd.dem');state=build(dem) | |
| print('plan',time.time()-t,'widths',state['on']['width'],state['off']['width'],flush=True) | |
| arrays=np.load(path/'arrays.npz');dets=np.unpackbits(arrays['detectors'][:n],axis=1,count=dem.num_detectors,bitorder='little') | |
| decoder=ConditionalDecoder(state,batch=128) | |
| for trial in range(2): | |
| t=time.time();p=decoder.predict(dets);print('trial',trial,'seconds',time.time()-t,'failure',np.mean((p>=.5)!=arrays['labels'][:n,None],axis=0),'range',p.min(),p.max(),flush=True) | |