Download tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S024/decoder.py from s42chen/sci-run: direct link, hf CLI and curl.
- Browser
- Download file 3.59 kB
-
https://huggingface.co/datasets/s42chen/sci-run/resolve/main/tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S024/decoder.py
- Command line
-
hf download hf://datasets/s42chen/sci-run/tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S024/decoder.py
-
curl -L -o decoder.py https://huggingface.co/datasets/s42chen/sci-run/resolve/main/tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b/submissions/S024/decoder.py
3.59 kB
| """Learned calibrated ensemble of matching and constrained logical-coset matching.""" | |
| from pathlib import Path | |
| import json | |
| import numpy as np | |
| import pymatching | |
| import stim | |
| from scipy.special import expit | |
| def match_features(dem, packed, rounds): | |
| dets = np.unpackbits(packed, axis=1, count=dem.num_detectors, bitorder='little') | |
| m = pymatching.Matching.from_detector_error_model(dem, enable_correlations=True) | |
| plain, wp = m.decode_batch(dets, return_weights=True) | |
| corr, wc = m.decode_batch(dets, return_weights=True, enable_correlations=True) | |
| # In these circuits the logical path is on a boundary. Converting L0 into | |
| # one extra syndrome vertex enforces each logical coset separately. | |
| cd = stim.DetectorErrorModel() | |
| for instruction in dem.flattened(): | |
| if instruction.type != 'error': | |
| continue | |
| targets = [stim.target_relative_detector_id(dem.num_detectors) | |
| if t.is_logical_observable_id() else t | |
| for t in instruction.targets_copy()] | |
| cd.append('error', instruction.args_copy(), targets) | |
| cm = pymatching.Matching.from_detector_error_model(cd) | |
| augmented = np.pad(dets, ((0, 0), (0, 1))) | |
| _, w0 = cm.decode_batch(augmented, return_weights=True) | |
| augmented[:, -1] = 1 | |
| _, w1 = cm.decode_batch(augmented, return_weights=True) | |
| gap = np.clip(w0 - w1, -20, 20) | |
| s0, s1 = plain[:, 0].astype(np.float64)*2-1, corr[:, 0].astype(np.float64)*2-1 | |
| density = dets.mean(axis=1) | |
| r = np.log1p(rounds)/np.log(26) | |
| return np.stack([np.ones(len(dets)), gap, s0, s1, s1*abs(gap), | |
| gap*density, s1*density, gap*r, s1*r, | |
| s0*density, s0*r, s0*s1], axis=1).astype(np.float32) | |
| def predict_features(x, state): | |
| return expit((x/state['scale']) @ state['coef']).astype(np.float32) | |
| def infer_condition(task): | |
| package, inputs, output, row, config = task | |
| package, inputs, output = map(Path, (package, inputs, output)) | |
| # ID values are used only to echo the input alignment. | |
| with np.load(inputs/row['arrays'], allow_pickle=False) as a: | |
| packed, ids = a['detectors'], a['sample_ids'] | |
| record = config['conditions'][row['name']] | |
| dem = stim.DetectorErrorModel.from_file(package/record['dem']) | |
| with np.load(package/config['groups'][row['group']], allow_pickle=False) as a: | |
| state = dict(a) | |
| probabilities = np.empty(len(ids), dtype=np.float32) | |
| for start in range(0, len(ids), 8192): | |
| end = min(start+8192, len(ids)) | |
| x = match_features(dem, packed[start:end], row['rounds']) | |
| probabilities[start:end] = predict_features(x, state) | |
| np.savez(output/f"{row['name']}.npz", sample_ids=ids, probabilities=probabilities) | |
| return row['name'] | |
| def main(): | |
| import sys, os | |
| from concurrent.futures import ProcessPoolExecutor | |
| package = Path(__file__).resolve().parent | |
| inputs, output = map(Path, sys.argv[1:3]) | |
| manifest = json.loads((inputs/'manifest.json').read_text()) | |
| if manifest['schema'] != 'surface-code-decoding-input/v1': | |
| raise ValueError('Unsupported input schema') | |
| config = json.loads((package/'model_config.json').read_text()) | |
| output.mkdir(exist_ok=True, parents=True) | |
| tasks = [(str(package), str(inputs), str(output), row, config) for row in manifest['conditions']] | |
| workers = min(int(os.environ.get('QEC_WORKERS', '16')), len(tasks)) | |
| with ProcessPoolExecutor(max_workers=workers) as pool: | |
| for name in pool.map(infer_condition, tasks): | |
| print(name, flush=True) | |
| if __name__ == '__main__': | |
| main() | |