File size: 3,591 Bytes
b75888f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
"""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()