Skip to content

Commit f7e264e

Browse files
committed
style: ruff format 10 files (whitespace/blank-line only, no logic change)
Fixes CI 'ruff format --check' failure in tests/ruff-and-mypy job. Verified: ruff format --check python/ now passes clean (153/153 files).
1 parent b644094 commit f7e264e

10 files changed

Lines changed: 199 additions & 109 deletions

File tree

python/qector_decoder_v3/__init__.py

Lines changed: 15 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,7 @@ def _load_native_module():
4343
try:
4444
run_mcp_server = _native_module.run_mcp_server
4545
except AttributeError:
46+
4647
def run_mcp_server(*args, **kwargs):
4748
raise RuntimeError("run_mcp_server requires the 'grpc' feature (maturin develop --features full)")
4849

@@ -866,6 +867,7 @@ def __init__(self, node_feat_dim=None, edge_feat_dim=None, hidden_size=16, n_lay
866867
# Load PyTorch implementation if torch is installed.
867868
try:
868869
from .torch_predecoder import TorchGNNPredecoder
870+
869871
self._torch_model = TorchGNNPredecoder(nfd, efd, hidden_size, n_layers)
870872
self._torch_model.double() # Cast to float64 to match Rust f64.
871873
self.use_torch = True
@@ -876,6 +878,7 @@ def _sync_to_rust(self):
876878
if self.use_torch:
877879
import tempfile
878880
import os
881+
879882
with tempfile.NamedTemporaryFile(suffix=".safetensors", delete=False) as tmp:
880883
tmp_path = tmp.name
881884
try:
@@ -889,6 +892,7 @@ def _sync_to_torch(self):
889892
if self.use_torch:
890893
import tempfile
891894
import os
895+
892896
with tempfile.NamedTemporaryFile(suffix=".safetensors", delete=False) as tmp:
893897
tmp_path = tmp.name
894898
try:
@@ -939,6 +943,7 @@ def forward(self, graph):
939943
"""Predict adjusted edge weights for a DetectorGraph."""
940944
if self.use_torch:
941945
import torch
946+
942947
self._torch_model.eval()
943948
with torch.no_grad():
944949
node_feats = torch.tensor(graph.node_features, dtype=torch.float64)
@@ -957,17 +962,18 @@ def train(self, graphs, targets, n_epochs):
957962
raise ImportError("PyTorch is required to train GNNPredecoder")
958963
import torch
959964
import torch.optim as optim
965+
960966
optimizer = optim.SGD(self._torch_model.parameters(), lr=self.learning_rate, weight_decay=self.l2_lambda)
961967
self._torch_model.train()
962-
968+
963969
for epoch in range(n_epochs):
964970
for graph, target in zip(graphs, targets):
965971
node_feats = torch.tensor(graph.node_features, dtype=torch.float64)
966972
edge_feats = torch.tensor(graph.edge_features, dtype=torch.float64)
967973
edge_src = torch.tensor(graph.edge_src, dtype=torch.long)
968974
edge_dst = torch.tensor(graph.edge_dst, dtype=torch.long)
969975
target_t = torch.tensor(target, dtype=torch.float64)
970-
976+
971977
optimizer.zero_grad()
972978
preds = self._torch_model(node_feats, edge_feats, edge_src, edge_dst)
973979
loss = F.mse_loss(preds, target_t)
@@ -982,35 +988,35 @@ def predict_with_node_probs(self, graph):
982988
"""Predict edge weights and node error probabilities."""
983989
if self.use_torch:
984990
import torch
991+
985992
self._torch_model.eval()
986993
with torch.no_grad():
987994
node_feats = torch.tensor(graph.node_features, dtype=torch.float64)
988995
edge_feats = torch.tensor(graph.edge_features, dtype=torch.float64)
989996
edge_src = torch.tensor(graph.edge_src, dtype=torch.long)
990997
edge_dst = torch.tensor(graph.edge_dst, dtype=torch.long)
991-
998+
992999
weights = self._torch_model(node_feats, edge_feats, edge_src, edge_dst)
993-
1000+
9941001
N = node_feats.size(0)
9951002
node_probs = torch.zeros(N, dtype=torch.float64)
9961003
node_counts = torch.zeros(N, dtype=torch.float64)
997-
1004+
9981005
node_probs.scatter_add_(0, edge_src, weights)
9991006
node_probs.scatter_add_(0, edge_dst, weights)
1000-
1007+
10011008
node_counts.scatter_add_(0, edge_src, torch.ones_like(edge_src, dtype=torch.float64))
10021009
node_counts.scatter_add_(0, edge_dst, torch.ones_like(edge_dst, dtype=torch.float64))
1003-
1010+
10041011
mask = node_counts > 0
10051012
node_probs[mask] /= node_counts[mask]
10061013
node_probs = 1.0 / (1.0 + (-node_probs + 1.0).exp())
1007-
1014+
10081015
return weights.cpu().numpy().tolist(), node_probs.cpu().numpy().tolist()
10091016
else:
10101017
return self._inner.predict_with_node_probs(graph._inner if isinstance(graph, DetectorGraph) else graph)
10111018

10121019

1013-
10141020
class DetectorGraph:
10151021
"""Detector graph used by the GNN and hybrid decoder paths."""
10161022

python/qector_decoder_v3/bposd.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -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
decoder: Union[CPUBatchDecoder, UnionFindDecoder]
7876
if decoder_type == "cpu_batch":
7977
decoder = CPUBatchDecoder(c2q, n_qubits)

python/qector_decoder_v3/decoder_cache.py

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -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: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -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: List[Optional[np.ndarray]] = [None] * len(chunks)
156163
for idx, result in self._pool.imap_unordered(_worker_decode, chunks):

0 commit comments

Comments
 (0)