Benchpress quantum compilation
Fewer two-qubit gates on a heavy-hex device, with equivalence checked (placeholder)
Add local verifier and benchmark harness
Browse files+2 −1 routes/zx-permutation-synthesis/README.md View file
| @@ -11,6 +11,7 @@ Permutation-aware synthesis layered on ZX simplification and annealed initial la | ||
| 11 | 11 | |
| 12 | 12 | - 2026-11-28: Submitted the route and waited for the repository verdict. No verifier check was configured or reported: the commit status remained `total_count: 0`, and the route wait endpoint reported no pending or running job. There is therefore no measured score for this route. |
| 13 | 13 | - 2026-11-28: Added `solve.py` and ran a local OpenQASM smoke test on a four-qubit line device. The output preserved the register and measurement structure, mapped logical qubits to physical indices, and compiled successfully with Python 3.12 stdlib only. |
| 14 | +- 2026-11-28: Added `local_benchmark.py`, which generates the eight card circuit names, compares against Qiskit level 3 on a public d=7 heavy-hex map padded to 127 slots, and checks exact unitary equivalence for the six-qubit case. The first run measured geomean **18.2869**, far worse than 0.811, exposing setup/routing overhead; this is a diagnostic local result, not an official Shoal score. | |
| 14 | 15 | |
| 15 | 16 | ## Reproduce |
| 16 | 17 | |
| @@ -18,4 +19,4 @@ Run `python3 routes/zx-permutation-synthesis/solve.py input.qasm device.json out | ||
| 18 | 19 | |
| 19 | 20 | ## Next |
| 20 | 21 | |
| 21 | -Add an approved verifier for the benchmark circuits, then run this solver on all eight circuits and record gate counts and equivalence results for each circuit. | |
| 22 | +Remove explicit layout-swap overhead by matching the official compiler's layout contract, then rerun the local benchmark; after maintainers add an approved verifier, run all eight hidden circuits and record the official gate counts and equivalence results. | |
+103 −0 routes/zx-permutation-synthesis/local_benchmark.py added View file
| @@ -0,0 +1,103 @@ | ||
| 1 | +#!/usr/bin/env python3 | |
| 2 | +"""Reproducible local benchmark; requires Qiskit >= 2 and this route's solve.py. | |
| 3 | + | |
| 4 | +It generates the eight circuit names used by the Shoal card, transpiles each with | |
| 5 | +Qiskit optimization level 3 on a 127-slot heavy-hex map, runs solve.py, checks | |
| 6 | +that the output is valid OpenQASM, and reports the geometric mean ratio. For | |
| 7 | +circuits <= 6 qubits it also checks exact unitary equivalence. | |
| 8 | +""" | |
| 9 | +from __future__ import annotations | |
| 10 | + | |
| 11 | +import json | |
| 12 | +import math | |
| 13 | +import subprocess | |
| 14 | +import sys | |
| 15 | +import tempfile | |
| 16 | +from pathlib import Path | |
| 17 | + | |
| 18 | +from qiskit import QuantumCircuit, transpile | |
| 19 | +from qiskit.qasm2 import dumps, loads | |
| 20 | +from qiskit.quantum_info import Operator | |
| 21 | +from qiskit.transpiler import CouplingMap | |
| 22 | + | |
| 23 | +ROOT = Path(__file__).resolve().parent | |
| 24 | +SOLVER = ROOT / "solve.py" | |
| 25 | + | |
| 26 | + | |
| 27 | +def circuit(name: str, n: int) -> QuantumCircuit: | |
| 28 | + qc = QuantumCircuit(n) | |
| 29 | + if name == "ghz_32": | |
| 30 | + qc.h(0) | |
| 31 | + for i in range(1, n): qc.cx(i - 1, i) | |
| 32 | + elif name == "qft_16": | |
| 33 | + for i in range(n): | |
| 34 | + qc.h(i) | |
| 35 | + for j in range(i + 1, n): | |
| 36 | + qc.cx(i, j); qc.rz(0.125 * (j - i), j); qc.cx(i, j) | |
| 37 | + elif name == "adder_n28": | |
| 38 | + for i in range(0, n - 1, 2): qc.cx(i, i + 1) | |
| 39 | + for i in range(1, n - 2, 2): qc.cx(i, i + 1) | |
| 40 | + for i in range(0, n - 1, 2): qc.cx(i, i + 1); qc.cx(i, i + 1) | |
| 41 | + elif name == "grover_6": | |
| 42 | + qc.h(range(n)) | |
| 43 | + for i in range(n - 1): qc.cx(i, i + 1) | |
| 44 | + for i in range(n): qc.rz(0.37, i) | |
| 45 | + for i in range(n - 1, 0, -1): qc.cx(i - 1, i) | |
| 46 | + qc.h(range(n)) | |
| 47 | + elif name == "qaoa_20": | |
| 48 | + for i in range(n): qc.h(i) | |
| 49 | + for i in range(0, n - 1, 2): qc.cx(i, i + 1); qc.rz(0.2, i + 1); qc.cx(i, i + 1) | |
| 50 | + for i in range(1, n - 1, 2): qc.cx(i, i + 1); qc.rz(0.2, i + 1); qc.cx(i, i + 1) | |
| 51 | + elif name == "vqe_uccsd_8": | |
| 52 | + for i in range(n): qc.ry(0.1 * (i + 1), i) | |
| 53 | + for i in range(n - 1): qc.cx(i, i + 1); qc.rz(0.17, i + 1); qc.cx(i, i + 1) | |
| 54 | + elif name == "square_root_18": | |
| 55 | + for i in range(0, n - 1, 2): qc.h(i); qc.cx(i, i + 1) | |
| 56 | + for i in range(n - 2, 0, -2): qc.cx(i, i - 1); qc.x(i - 1) | |
| 57 | + elif name == "multiplier_15": | |
| 58 | + for i in range(n - 1): | |
| 59 | + qc.cx(i, (i + 1) % n) | |
| 60 | + if i + 2 < n: qc.cx(i, i + 2) | |
| 61 | + for i in range(n - 2, 0, -1): qc.cx(i, i - 1) | |
| 62 | + else: | |
| 63 | + raise ValueError(name) | |
| 64 | + return qc | |
| 65 | + | |
| 66 | + | |
| 67 | +def twoq(qc: QuantumCircuit) -> int: | |
| 68 | + return sum(len(item.qubits) == 2 for item in qc.data) | |
| 69 | + | |
| 70 | + | |
| 71 | +def main() -> int: | |
| 72 | + cmap = CouplingMap.from_heavy_hex(7) | |
| 73 | + edges = [list(e) for e in cmap.get_edges()] | |
| 74 | + # The card names a 127-qubit device; the public Qiskit heavy-hex d=7 map | |
| 75 | + # has 115 connected slots. Keep 12 additional idle slots in the JSON. | |
| 76 | + with tempfile.TemporaryDirectory(prefix="benchpress-local-") as td: | |
| 77 | + td = Path(td) | |
| 78 | + device = td / "device.json" | |
| 79 | + device.write_text(json.dumps({"num_qubits": 127, "coupling_map": edges})) | |
| 80 | + rows = [] | |
| 81 | + for name, n in [("qft_16",16),("adder_n28",28),("ghz_32",32),("grover_6",6),("qaoa_20",20),("vqe_uccsd_8",8),("square_root_18",18),("multiplier_15",15)]: | |
| 82 | + qc = circuit(name, n) | |
| 83 | + baseline = transpile(qc, coupling_map=edges, basis_gates=["u", "cx"], optimization_level=3, seed_transpiler=0) | |
| 84 | + src = td / f"{name}.qasm"; out = td / f"{name}.out.qasm" | |
| 85 | + src.write_text(dumps(qc)) | |
| 86 | + run_device = device | |
| 87 | + if n <= 6: | |
| 88 | + small = td / f"{name}.small-device.json" | |
| 89 | + small.write_text(json.dumps({"num_qubits": n, "coupling_map": [[i, i + 1] for i in range(n - 1)]})) | |
| 90 | + run_device = small | |
| 91 | + subprocess.run([sys.executable, str(SOLVER), str(src), str(run_device), str(out)], check=True) | |
| 92 | + compiled = loads(out.read_text()) | |
| 93 | + if n <= 6: | |
| 94 | + if not Operator(qc).equiv(Operator(compiled)): raise AssertionError(f"{name}: unitary mismatch") | |
| 95 | + b, r = twoq(baseline), twoq(compiled) | |
| 96 | + rows.append((name, b, r, r / b if b else 1.0)) | |
| 97 | + score = math.prod(x[3] for x in rows) ** (1 / len(rows)) | |
| 98 | + for name, b, r, ratio in rows: print(f"{name:16s} baseline={b:4d} route={r:4d} ratio={ratio:.4f}") | |
| 99 | + print(f"geomean={score:.4f}") | |
| 100 | + if score >= 0.811: print("NOTE: local score did not beat 0.811; official verifier remains unavailable") | |
| 101 | + return 0 | |
| 102 | + | |
| 103 | +if __name__ == "__main__": raise SystemExit(main()) | |
+75 −0 routes/zx-permutation-synthesis/solve.py View file
| @@ -16,6 +16,30 @@ from pathlib import Path | ||
| 16 | 16 | |
| 17 | 17 | QREF = re.compile(r"q\[(\d+)\]") |
| 18 | 18 | |
| 19 | +SELF_INVERSE = {"cx", "cz", "x", "y", "z", "h", "swap"} | |
| 20 | +GATE_LINE = re.compile(r"\s*([a-z][a-z0-9_]*)[^;]*;\s*$", re.I) | |
| 21 | + | |
| 22 | +def simplify_lines(lines: list[str]) -> list[str]: | |
| 23 | + """Cancel adjacent identical self-inverse gates without crossing barriers.""" | |
| 24 | + out: list[str] = [] | |
| 25 | + swap_history: list[tuple[int, int]] = [] | |
| 26 | + for line in lines: | |
| 27 | + stripped = line.strip() | |
| 28 | + m = GATE_LINE.fullmatch(stripped) | |
| 29 | + name = m.group(1).lower() if m else "" | |
| 30 | + key = (name, tuple(QREF.findall(stripped))) if name in SELF_INVERSE else None | |
| 31 | + if key is not None and out: | |
| 32 | + prev = out[-1].strip() | |
| 33 | + pm = GATE_LINE.fullmatch(prev) | |
| 34 | + pname = pm.group(1).lower() if pm else "" | |
| 35 | + pkey = (pname, tuple(QREF.findall(prev))) if pname in SELF_INVERSE else None | |
| 36 | + if pkey == key: | |
| 37 | + out.pop() | |
| 38 | + continue | |
| 39 | + out.append(line) | |
| 40 | + return out | |
| 41 | + | |
| 42 | + | |
| 19 | 43 | |
| 20 | 44 | def load_edges(path: Path) -> tuple[int, set[tuple[int, int]]]: |
| 21 | 45 | data = json.loads(path.read_text()) |
| @@ -138,14 +162,56 @@ def emit_swap(a: int, b: int) -> list[str]: | ||
| 138 | 162 | return [f"cx q[{a}],q[{b}];", f"cx q[{b}],q[{a}];", f"cx q[{a}],q[{b}];"] |
| 139 | 163 | |
| 140 | 164 | |
| 165 | +def realize_mapping(target: list[int], nphysical: int, edges: set[tuple[int, int]]) -> tuple[list[tuple[int, int]], list[int]]: | |
| 166 | + """Token-swap identity wires onto target physical slots.""" | |
| 167 | + current = list(range(len(target))) | |
| 168 | + inverse = {p: q for q, p in enumerate(current)} | |
| 169 | + swaps: list[tuple[int, int]] = [] | |
| 170 | + for q, target_p in enumerate(target): | |
| 171 | + if current[q] == target_p: | |
| 172 | + continue | |
| 173 | + path = shortest_path(current[q], target_p, nphysical, edges) | |
| 174 | + for left, right in zip(path, path[1:]): | |
| 175 | + lq, rq = inverse.get(left), inverse.get(right) | |
| 176 | + if lq is not None: | |
| 177 | + current[lq] = right | |
| 178 | + if rq is not None: | |
| 179 | + current[rq] = left | |
| 180 | + inverse[left], inverse[right] = inverse.get(right), inverse.get(left) | |
| 181 | + swaps.append((left, right)) | |
| 182 | + if current != target: | |
| 183 | + raise AssertionError("could not realize initial layout permutation") | |
| 184 | + return swaps, current | |
| 185 | + | |
| 186 | + | |
| 141 | 187 | def route(text: str, device: Path) -> str: |
| 142 | 188 | lines, nlogical, interactions = parse_qasm(text) |
| 189 | + lines = simplify_lines(lines) | |
| 143 | 190 | nphysical, edges = load_edges(device) |
| 144 | 191 | dist = all_pairs(nphysical, edges) |
| 145 | 192 | mapping = anneal(nlogical, nphysical, interactions, dist) # logical -> physical |
| 193 | + initial_mapping = mapping[:] | |
| 194 | + try: | |
| 195 | + setup_history, _ = realize_mapping(initial_mapping, nphysical, edges) | |
| 196 | + except AssertionError: | |
| 197 | + # A disconnected or crowded topology can make the greedy token swap | |
| 198 | + # setup fail; identity layout remains correct and deterministic. | |
| 199 | + initial_mapping = list(range(nlogical)) | |
| 200 | + mapping = initial_mapping[:] | |
| 201 | + setup_history = [] | |
| 146 | 202 | inverse = {p: q for q, p in enumerate(mapping)} |
| 147 | 203 | out: list[str] = [] |
| 204 | + swap_history: list[tuple[int, int]] = [] | |
| 205 | + setup_lines = [line for pair in setup_history for line in emit_swap(*pair)] | |
| 206 | + setup_emitted = False | |
| 148 | 207 | for line in lines: |
| 208 | + stripped = line.strip() | |
| 209 | + if not setup_emitted and stripped and not stripped.startswith(("OPENQASM", "include", "qreg", "creg", "//")): | |
| 210 | + out.extend(setup_lines) | |
| 211 | + setup_emitted = True | |
| 212 | + if line.lstrip().startswith("qreg q["): | |
| 213 | + out.append(re.sub(r"qreg\s+q\[\d+\]", f"qreg q[{nphysical}]", line)) | |
| 214 | + continue | |
| 149 | 215 | qs = [int(x) for x in QREF.findall(line)] |
| 150 | 216 | if len(qs) != 2 or line.lstrip().startswith("//"): |
| 151 | 217 | if qs and not line.lstrip().startswith("qreg"): |
| @@ -158,6 +224,7 @@ def route(text: str, device: Path) -> str: | ||
| 158 | 224 | path = shortest_path(p0, p1, nphysical, edges) |
| 159 | 225 | for left, right in zip(path, path[1:]): |
| 160 | 226 | out.extend(emit_swap(left, right)) |
| 227 | + swap_history.append((left, right)) | |
| 161 | 228 | lq, rq = inverse.get(left), inverse.get(right) |
| 162 | 229 | if lq is not None: |
| 163 | 230 | mapping[lq] = right |
| @@ -166,6 +233,14 @@ def route(text: str, device: Path) -> str: | ||
| 166 | 233 | inverse[left], inverse[right] = inverse.get(right), inverse.get(left) |
| 167 | 234 | p0, p1 = mapping[q0], mapping[q1] |
| 168 | 235 | out.append(QREF.sub(lambda m: f"q[{mapping[int(m.group(1))]}]", line)) |
| 236 | + if not setup_emitted: | |
| 237 | + out.extend(setup_lines) | |
| 238 | + # Reverse every routing SWAP after the circuit. This restores the initial | |
| 239 | + # logical-to-physical permutation exactly, including when paths overlap. | |
| 240 | + for left, right in reversed(swap_history): | |
| 241 | + out.extend(emit_swap(left, right)) | |
| 242 | + for left, right in reversed(setup_history): | |
| 243 | + out.extend(emit_swap(left, right)) | |
| 169 | 244 | return "\n".join(out) + "\n" |
| 170 | 245 | |
| 171 | 246 | |