Skip to content

Commit 2a74388

Browse files
committed
Fix 11 ruff errors: unused vars, missing Optional import, f-string, variable name typo
1 parent bd8291d commit 2a74388

12 files changed

Lines changed: 209 additions & 118 deletions

python/qector_decoder_v3/__init__.py

Lines changed: 15 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@ def _load_native_module():
4040
try:
4141
run_mcp_server = _native_module.run_mcp_server
4242
except AttributeError:
43+
4344
def run_mcp_server(*args, **kwargs):
4445
raise RuntimeError("run_mcp_server requires the 'grpc' feature (maturin develop --features full)")
4546

@@ -863,6 +864,7 @@ def __init__(self, node_feat_dim=None, edge_feat_dim=None, hidden_size=16, n_lay
863864
# Load PyTorch implementation if torch is installed.
864865
try:
865866
from .torch_predecoder import TorchGNNPredecoder
867+
866868
self._torch_model = TorchGNNPredecoder(nfd, efd, hidden_size, n_layers)
867869
self._torch_model.double() # Cast to float64 to match Rust f64.
868870
self.use_torch = True
@@ -873,6 +875,7 @@ def _sync_to_rust(self):
873875
if self.use_torch:
874876
import tempfile
875877
import os
878+
876879
with tempfile.NamedTemporaryFile(suffix=".safetensors", delete=False) as tmp:
877880
tmp_path = tmp.name
878881
try:
@@ -886,6 +889,7 @@ def _sync_to_torch(self):
886889
if self.use_torch:
887890
import tempfile
888891
import os
892+
889893
with tempfile.NamedTemporaryFile(suffix=".safetensors", delete=False) as tmp:
890894
tmp_path = tmp.name
891895
try:
@@ -936,6 +940,7 @@ def forward(self, graph):
936940
"""Predict adjusted edge weights for a DetectorGraph."""
937941
if self.use_torch:
938942
import torch
943+
939944
self._torch_model.eval()
940945
with torch.no_grad():
941946
node_feats = torch.tensor(graph.node_features, dtype=torch.float64)
@@ -954,17 +959,18 @@ def train(self, graphs, targets, n_epochs):
954959
raise ImportError("PyTorch is required to train GNNPredecoder")
955960
import torch
956961
import torch.optim as optim
962+
957963
optimizer = optim.SGD(self._torch_model.parameters(), lr=self.learning_rate, weight_decay=self.l2_lambda)
958964
self._torch_model.train()
959-
965+
960966
for epoch in range(n_epochs):
961967
for graph, target in zip(graphs, targets):
962968
node_feats = torch.tensor(graph.node_features, dtype=torch.float64)
963969
edge_feats = torch.tensor(graph.edge_features, dtype=torch.float64)
964970
edge_src = torch.tensor(graph.edge_src, dtype=torch.long)
965971
edge_dst = torch.tensor(graph.edge_dst, dtype=torch.long)
966972
target_t = torch.tensor(target, dtype=torch.float64)
967-
973+
968974
optimizer.zero_grad()
969975
preds = self._torch_model(node_feats, edge_feats, edge_src, edge_dst)
970976
loss = F.mse_loss(preds, target_t)
@@ -979,35 +985,35 @@ def predict_with_node_probs(self, graph):
979985
"""Predict edge weights and node error probabilities."""
980986
if self.use_torch:
981987
import torch
988+
982989
self._torch_model.eval()
983990
with torch.no_grad():
984991
node_feats = torch.tensor(graph.node_features, dtype=torch.float64)
985992
edge_feats = torch.tensor(graph.edge_features, dtype=torch.float64)
986993
edge_src = torch.tensor(graph.edge_src, dtype=torch.long)
987994
edge_dst = torch.tensor(graph.edge_dst, dtype=torch.long)
988-
995+
989996
weights = self._torch_model(node_feats, edge_feats, edge_src, edge_dst)
990-
997+
991998
N = node_feats.size(0)
992999
node_probs = torch.zeros(N, dtype=torch.float64)
9931000
node_counts = torch.zeros(N, dtype=torch.float64)
994-
1001+
9951002
node_probs.scatter_add_(0, edge_src, weights)
9961003
node_probs.scatter_add_(0, edge_dst, weights)
997-
1004+
9981005
node_counts.scatter_add_(0, edge_src, torch.ones_like(edge_src, dtype=torch.float64))
9991006
node_counts.scatter_add_(0, edge_dst, torch.ones_like(edge_dst, dtype=torch.float64))
1000-
1007+
10011008
mask = node_counts > 0
10021009
node_probs[mask] /= node_counts[mask]
10031010
node_probs = 1.0 / (1.0 + (-node_probs + 1.0).exp())
1004-
1011+
10051012
return weights.cpu().numpy().tolist(), node_probs.cpu().numpy().tolist()
10061013
else:
10071014
return self._inner.predict_with_node_probs(graph._inner if isinstance(graph, DetectorGraph) else graph)
10081015

10091016

1010-
10111017
class DetectorGraph:
10121018
"""Detector graph used by the GNN and hybrid decoder paths."""
10131019

python/qector_decoder_v3/belief_matching.py

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -211,8 +211,6 @@ def from_numpy_h(cls, H, error_rate: float = 0.05, max_iter: int = 20) -> "Belie
211211
hyper_ids = {}
212212
edge_ids = {}
213213
hyper_to_edges = {}
214-
hyper_obs_dict = {}
215-
edge_obs_dict = {}
216214
priors = {}
217215

218216
for q in range(nQ):

python/qector_decoder_v3/bposd.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@
2222

2323
from __future__ import annotations
2424

25-
from typing import Any, List, Tuple, cast
25+
from typing import Any, List, Optional, Tuple, cast
2626

2727
import numpy as np
2828

@@ -82,6 +82,7 @@ def decode(self, syndrome) -> np.ndarray:
8282

8383
if self.max_latency_ms is not None:
8484
import time as _time
85+
8586
t_start = _time.perf_counter()
8687
max_seconds = self.max_latency_ms / 1000.0
8788

@@ -110,6 +111,7 @@ def decode(self, syndrome) -> np.ndarray:
110111

111112
if self.max_latency_ms is not None and (_time.perf_counter() - t_start) > max_seconds:
112113
from . import UnionFindDecoder
114+
113115
checks = [sorted(int(c) for c in np.nonzero(self.H[r])[0]) for r in range(self.n_checks)]
114116
uf = UnionFindDecoder(checks, self.n_qubits)
115117
return np.asarray(uf.decode(s), dtype=np.uint8).reshape(-1)
@@ -226,9 +228,7 @@ def _osd(self, s: np.ndarray, posterior: np.ndarray) -> np.ndarray:
226228
# ---------------------------------------------------------------------------
227229
# GF(2) ordered-statistics solve
228230
# ---------------------------------------------------------------------------
229-
def _gf2_osd_solve(
230-
H: np.ndarray, s: np.ndarray, order: np.ndarray, hard: np.ndarray
231-
) -> Tuple[np.ndarray, np.ndarray]:
231+
def _gf2_osd_solve(H: np.ndarray, s: np.ndarray, order: np.ndarray, hard: np.ndarray) -> Tuple[np.ndarray, np.ndarray]:
232232
"""OSD-0 solve. ``order`` lists columns least-reliable first; the first
233233
rank(H) independent of them form the basis, the rest (free) take their BP hard
234234
decision, and the basis is solved so ``H x == s (mod 2)``.

python/qector_decoder_v3/decode_mmap.py

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -12,12 +12,10 @@
1212
>>> checks, nq = generate_repetition_code_checks(distance=5)
1313
>>> n_shots = 10000
1414
>>> # Create a memory-mapped syndrome file
15-
>>> syn = np.memmap("syndromes.bin", dtype=np.uint8, mode="w+",
16-
... shape=(n_shots, len(checks)))
15+
>>> syn = np.memmap("syndromes.bin", dtype=np.uint8, mode="w+", shape=(n_shots, len(checks)))
1716
>>> syn[:] = (np.random.random((n_shots, len(checks))) < 0.1).astype(np.uint8)
1817
>>> syn.flush()
19-
>>> decode_mmap("syndromes.bin", "corrections.bin",
20-
... checks, nq, batch_size=1024, n_shots=n_shots)
18+
>>> decode_mmap("syndromes.bin", "corrections.bin", checks, nq, batch_size=1024, n_shots=n_shots)
2119
"""
2220

2321
from __future__ import annotations
@@ -66,14 +64,14 @@ def decode_mmap(
6664
n_shots = file_size // bytes_per_shot
6765
if file_size < n_shots * bytes_per_shot:
6866
raise ValueError(
69-
f"syndrome file too small: {file_size} bytes, "
70-
f"need {n_shots * bytes_per_shot} for {n_shots} shots"
67+
f"syndrome file too small: {file_size} bytes, need {n_shots * bytes_per_shot} for {n_shots} shots"
7168
)
7269

7370
syndromes = _np.memmap(syndrome_path, dtype=dtype, mode="r", shape=(n_shots, n_checks))
7471
output = _np.memmap(output_path, dtype=_np.uint8, mode="w+", shape=(n_shots, n_qubits))
7572

7673
from . import CPUBatchDecoder, UnionFindDecoder
74+
7775
if decoder_type == "cpu_batch":
7876
decoder = CPUBatchDecoder(c2q, n_qubits)
7977
batch_fn = decoder.batch_decode

python/qector_decoder_v3/decoder_cache.py

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@
1919
import hashlib as _hashlib
2020
import json as _json
2121
import os as _os
22-
from typing import Any, Dict, Optional, Tuple
22+
from typing import Optional, Tuple
2323

2424
import numpy as _np
2525

@@ -29,19 +29,24 @@
2929
def _normalize_decoder_name(name: str) -> str:
3030
"""Normalize decoder name aliases to canonical form."""
3131
mapping = {
32-
'uf': 'union_find', 'unionfind': 'union_find',
33-
'fast_uf': 'fast_union_find', 'fastuf': 'fast_union_find', 'fastunionfind': 'fast_union_find',
34-
'sparse': 'sparse_blossom',
35-
'batch': 'cpu_batch', 'cpu': 'cpu_batch',
32+
"uf": "union_find",
33+
"unionfind": "union_find",
34+
"fast_uf": "fast_union_find",
35+
"fastuf": "fast_union_find",
36+
"fastunionfind": "fast_union_find",
37+
"sparse": "sparse_blossom",
38+
"batch": "cpu_batch",
39+
"cpu": "cpu_batch",
3640
}
37-
return mapping.get(name.lower().replace('-', '_').replace(' ', '_'), name)
41+
return mapping.get(name.lower().replace("-", "_").replace(" ", "_"), name)
3842

3943

4044
@_functools.lru_cache(maxsize=256)
4145
def _build_decoder(checks_tuple: Tuple[Tuple[int, ...]], n_qubits: int, decoder_type: str):
4246
"""Internal LRU-cached decoder factory."""
4347
checks = [list(c) for c in checks_tuple]
4448
from . import BlossomDecoder, CPUBatchDecoder, FastUnionFindDecoder, SparseBlossomDecoder, UnionFindDecoder
49+
4550
builders = {
4651
"union_find": lambda: UnionFindDecoder(checks, n_qubits),
4752
"fast_union_find": lambda: FastUnionFindDecoder(checks, n_qubits),
@@ -91,6 +96,7 @@ def get_decoder_pool(
9196
A :class:`DecoderPool` instance.
9297
"""
9398
from .decoder_pool import DecoderPool
99+
94100
return DecoderPool(
95101
[list(c) for c in checks_tuple],
96102
n_qubits=n_qubits,

python/qector_decoder_v3/decoder_pool.py

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@
2929
import multiprocessing as _mp
3030
import os
3131
import platform as _platform
32-
from typing import Any, List, Optional
32+
from typing import Optional
3333

3434
import numpy as np
3535

@@ -45,6 +45,7 @@ def _worker_init(checks_tuple, n_qubits, decoder_type):
4545
global _WORKER_DECODER
4646
checks = [list(c) for c in checks_tuple]
4747
from . import BlossomDecoder, CPUBatchDecoder, FastUnionFindDecoder, SparseBlossomDecoder, UnionFindDecoder
48+
4849
builders = {
4950
"union_find": lambda: UnionFindDecoder(checks, n_qubits),
5051
"fast_union_find": lambda: FastUnionFindDecoder(checks, n_qubits),
@@ -74,10 +75,16 @@ def _worker_decode(chunk_and_idx):
7475

7576

7677
_DECODER_BUILDERS = {
77-
"union_find": lambda c2q, nq: __import__("qector_decoder_v3", fromlist=["UnionFindDecoder"]).UnionFindDecoder(c2q, nq),
78-
"fast_union_find": lambda c2q, nq: __import__("qector_decoder_v3", fromlist=["FastUnionFindDecoder"]).FastUnionFindDecoder(c2q, nq),
78+
"union_find": lambda c2q, nq: __import__("qector_decoder_v3", fromlist=["UnionFindDecoder"]).UnionFindDecoder(
79+
c2q, nq
80+
),
81+
"fast_union_find": lambda c2q, nq: __import__(
82+
"qector_decoder_v3", fromlist=["FastUnionFindDecoder"]
83+
).FastUnionFindDecoder(c2q, nq),
7984
"blossom": lambda c2q, nq: __import__("qector_decoder_v3", fromlist=["BlossomDecoder"]).BlossomDecoder(c2q, nq),
80-
"sparse_blossom": lambda c2q, nq: __import__("qector_decoder_v3", fromlist=["SparseBlossomDecoder"]).SparseBlossomDecoder(c2q, nq),
85+
"sparse_blossom": lambda c2q, nq: __import__(
86+
"qector_decoder_v3", fromlist=["SparseBlossomDecoder"]
87+
).SparseBlossomDecoder(c2q, nq),
8188
"cpu_batch": lambda c2q, nq: __import__("qector_decoder_v3", fromlist=["CPUBatchDecoder"]).CPUBatchDecoder(c2q, nq),
8289
}
8390

@@ -150,7 +157,7 @@ def decode(self, syndromes) -> np.ndarray:
150157

151158
nw = min(self._n_workers, n)
152159
chunk_size = (n + nw - 1) // nw
153-
chunks = [(arr[i:i + chunk_size], i // chunk_size) for i in range(0, n, chunk_size)]
160+
chunks = [(arr[i : i + chunk_size], i // chunk_size) for i in range(0, n, chunk_size)]
154161

155162
results = [None] * len(chunks)
156163
for idx, result in self._pool.imap_unordered(_worker_decode, chunks):

python/qector_decoder_v3/predecoder.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -81,7 +81,7 @@ def __init__(self, check_to_qubits, n_qubits=None, backend: str = "blossom"):
8181
if backend in _backend_map:
8282
backend = _backend_map[backend]
8383
if backend not in _valid_backends:
84-
raise ValueError(f"backend must be one of ['blossom', 'union_find', 'sparse_blossom']")
84+
raise ValueError("backend must be one of ['blossom', 'union_find', 'sparse_blossom']")
8585
self.backend = backend
8686
residual: Union[BlossomDecoder, UnionFindDecoder, SparseBlossomDecoder]
8787
if backend == "blossom":

0 commit comments

Comments
 (0)