Spaces:
Sleeping
qlib: cleanup pass — docstrings, type hints, constants, logging
Browse filesNon-behavioral changes aimed at making qlib/ less intimidating to new
contributors picking up JQub algorithm code:
- Add module-level logger and replace scattered print() calls with
logger.info / logger.debug so the live service stops dumping to
stdout and precompute runs can be tuned via logging config.
- Hoist hardcoded hyperparameters to named module-level constants:
HISTORY_WINDOW_DAYS, CONFIDENCE_LEVEL, LSTM_* in qbound;
QUCAD_DEFAULT_*, TWO_QUBIT_GATES, COBYLA_MAXITER in qucad;
DEFAULT_THETA_GRID, LAMBDA_PENALTY, DECISION_THRESHOLD in compvqc.
These were previously scattered inside function bodies.
- Add type hints + docstrings to public functions used by
workflow_service (call_QuBound, run_qucad_training_noisy, get_LUT,
admmOptimizedCompVQC, etc.) and to internal helpers.
- Remove commented-out dead code: abandoned transpile variants,
debug prints, old example circuits.
- qiskit_utils: prune unused helpers (display_circuit,
qasmFile_toCircuit, transpile_optim) and unused imports
(qasm2/qasm3, FakeMarrakesh, FakeTorino, qpy, io). Only
simpleFidelityEstimator is actually consumed by the web app.
- compvqc: de-duplicate the second "from qiskit import ..." block
that shadowed the top-of-file imports.
No public API changes: all signatures consumed by workflow_service
are preserved (same positional/keyword params, same return shapes).
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
- backend/qlib/compvqc.py +162 -125
- backend/qlib/qbound.py +226 -166
- backend/qlib/qiskit_utils.py +33 -44
- backend/qlib/qucad.py +173 -93
|
@@ -1,173 +1,217 @@
|
|
| 1 |
"""CompressVQC implementation (refactored from Jovin Antony Maria's original).
|
| 2 |
|
| 3 |
-
|
| 4 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5 |
"""
|
| 6 |
|
| 7 |
-
from
|
| 8 |
-
from qiskit import qpy, qasm3, transpile
|
| 9 |
|
| 10 |
-
|
| 11 |
-
from
|
| 12 |
-
from
|
| 13 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
from qiskit_algorithms import QAOA
|
| 15 |
from qiskit_algorithms.optimizers import COBYLA
|
| 16 |
-
from qiskit.primitives import StatevectorSampler
|
| 17 |
-
|
| 18 |
from qiskit_ibm_runtime.fake_provider import FakeFez
|
|
|
|
|
|
|
|
|
|
| 19 |
|
| 20 |
-
|
| 21 |
-
from types import SimpleNamespace
|
| 22 |
|
| 23 |
|
| 24 |
-
#
|
| 25 |
-
##### Implement LUT (Look-Up Table) using transpiled circuit depth
|
| 26 |
|
|
|
|
|
|
|
|
|
|
| 27 |
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 31 |
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 36 |
|
| 37 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 38 |
return gates_to_map
|
| 39 |
|
| 40 |
|
| 41 |
-
def get_LUT(qc, backend):
|
| 42 |
-
|
| 43 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 44 |
gates_to_map = get_gates_to_map(qc)
|
| 45 |
-
lut = {}
|
| 46 |
|
| 47 |
for gate in gates_to_map:
|
| 48 |
lut[gate] = {}
|
| 49 |
-
|
| 50 |
-
for theta in theta_values:
|
| 51 |
test_qc = QuantumCircuit(2)
|
| 52 |
-
|
| 53 |
-
if gate == 'rx':
|
| 54 |
test_qc.rx(theta, 0)
|
| 55 |
-
elif gate ==
|
| 56 |
test_qc.ry(theta, 0)
|
| 57 |
-
elif gate ==
|
| 58 |
test_qc.rz(theta, 0)
|
| 59 |
-
elif gate ==
|
| 60 |
test_qc.p(theta, 0)
|
| 61 |
-
elif gate == 'cx':
|
| 62 |
-
test_qc.cx(0, 1)
|
| 63 |
|
| 64 |
transpiled_qc = transpile(test_qc, backend=backend, optimization_level=1)
|
|
|
|
| 65 |
|
| 66 |
-
|
| 67 |
-
lut[gate][theta_rounded] = transpiled_qc.depth()
|
| 68 |
-
|
| 69 |
-
print(lut)
|
| 70 |
return lut
|
| 71 |
|
| 72 |
|
| 73 |
-
#
|
| 74 |
-
##### Convert LUT into QuadraticProgram
|
| 75 |
|
| 76 |
|
| 77 |
-
def qaoa_callback(eval_count, parameters, value, metadata):
|
| 78 |
-
|
|
|
|
| 79 |
|
| 80 |
|
| 81 |
-
def quadraticProgram_luttoqp(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 82 |
qp = QuadraticProgram("CompressVQC")
|
| 83 |
-
|
| 84 |
-
obj_dict = {}
|
| 85 |
|
| 86 |
for i, instruction in enumerate(qc.data):
|
| 87 |
gate = instruction.operation
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
|
|
|
|
|
|
|
|
|
| 111 |
|
| 112 |
qp.minimize(linear=obj_dict)
|
| 113 |
return qp
|
| 114 |
|
| 115 |
|
| 116 |
-
#
|
| 117 |
-
##### Solve QP using QAOA (convert to QUBO first)
|
| 118 |
-
|
| 119 |
|
| 120 |
|
| 121 |
-
|
| 122 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 123 |
sampler = StatevectorSampler()
|
| 124 |
-
optimizer = COBYLA(maxiter=
|
| 125 |
|
| 126 |
qaoa = QAOA(
|
| 127 |
sampler=sampler,
|
| 128 |
optimizer=optimizer,
|
| 129 |
-
callback=qaoa_callback
|
| 130 |
)
|
| 131 |
|
| 132 |
conv = QuadraticProgramToQubo()
|
| 133 |
qubo = conv.convert(qp)
|
| 134 |
|
| 135 |
-
|
| 136 |
-
result =
|
| 137 |
-
|
| 138 |
-
# for k, v in result.variables_dict.items():
|
| 139 |
-
# if v > 0.5:
|
| 140 |
-
# print("CHOSEN:", k, v)
|
| 141 |
-
|
| 142 |
|
| 143 |
-
# Convert QUBO solution back into original variable space
|
| 144 |
original_x = conv.interpret(result.x)
|
| 145 |
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
|
| 151 |
-
# Return object that behaves like OptimizationResult
|
| 152 |
-
interpreted_result = SimpleNamespace(variables_dict=variables_dict)
|
| 153 |
|
| 154 |
-
|
| 155 |
|
| 156 |
|
| 157 |
-
|
| 158 |
-
|
|
|
|
|
|
|
|
|
|
| 159 |
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
# start from the same initial qc and then apply the compressed changes
|
| 167 |
compressed_qc = QuantumCircuit(*original_qc.qregs, *original_qc.cregs)
|
| 168 |
|
| 169 |
for i, instr in enumerate(original_qc.data):
|
| 170 |
-
# even gate and their instruction
|
| 171 |
gate = instr.operation
|
| 172 |
qargs = instr.qubits
|
| 173 |
cargs = instr.clbits
|
|
@@ -176,35 +220,31 @@ def resultsCompressVQC(result, original_qc):
|
|
| 176 |
|
| 177 |
if gate.name == "ry":
|
| 178 |
for var_name, var_value in result.variables_dict.items():
|
| 179 |
-
|
| 180 |
-
# only variables> 0.5, will exist after pruning
|
| 181 |
-
if var_value > 0.5 and var_name.startswith(f"gate_{i}_ry_"):
|
| 182 |
theta_id = int(var_name.split("_")[-1])
|
| 183 |
-
new_theta = theta_id /
|
| 184 |
new_gate = RYGate(new_theta)
|
| 185 |
|
| 186 |
-
# recreate the compressed qc from the compressed gates
|
| 187 |
compressed_qc.append(new_gate, qargs, cargs)
|
| 188 |
|
| 189 |
-
#
|
| 190 |
-
#
|
| 191 |
-
#
|
| 192 |
-
#
|
| 193 |
-
#
|
| 194 |
-
|
| 195 |
return compressed_qc
|
| 196 |
|
| 197 |
|
| 198 |
-
#
|
| 199 |
|
| 200 |
|
| 201 |
-
def gen_example_vqc(out_path=None):
|
| 202 |
-
"""Build a tiny 2-qubit example VQC
|
|
|
|
| 203 |
qc = QuantumCircuit(2)
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
theta_1 = Parameter('theta_1')
|
| 207 |
-
|
| 208 |
qc.ry(theta_0, 0)
|
| 209 |
qc.ry(theta_1, 1)
|
| 210 |
qc.cx(0, 1)
|
|
@@ -212,31 +252,28 @@ def gen_example_vqc(out_path=None):
|
|
| 212 |
if out_path is not None:
|
| 213 |
with open(out_path, "w") as f:
|
| 214 |
qasm3.dump(qc, f)
|
| 215 |
-
|
| 216 |
return qc
|
| 217 |
|
| 218 |
|
| 219 |
-
##### Main runner
|
| 220 |
-
|
| 221 |
-
|
| 222 |
if __name__ == "__main__":
|
| 223 |
# Minimal CLI entry for ad-hoc testing outside the web app.
|
| 224 |
# Expects one environment variable:
|
| 225 |
# COMPVQC_QPY_FILE - path to a .qpy file holding the VQC to compress
|
| 226 |
import os
|
| 227 |
|
|
|
|
|
|
|
| 228 |
qpy_path = os.environ["COMPVQC_QPY_FILE"]
|
| 229 |
with open(qpy_path, "rb") as f:
|
| 230 |
qc = qpy.load(f)[0]
|
| 231 |
|
| 232 |
-
|
| 233 |
|
| 234 |
backend = FakeFez()
|
| 235 |
-
|
| 236 |
lut = get_LUT(qc, backend)
|
| 237 |
qp = quadraticProgram_luttoqp(qc, lut)
|
| 238 |
result = admmOptimizedCompVQC(qp)
|
| 239 |
compressed_qc = resultsCompressVQC(result, qc)
|
| 240 |
|
| 241 |
-
|
| 242 |
-
print(compressed_qc)
|
|
|
|
| 1 |
"""CompressVQC implementation (refactored from Jovin Antony Maria's original).
|
| 2 |
|
| 3 |
+
Algorithm overview: replace each parameterised rotation gate with the
|
| 4 |
+
"best" angle from a small discrete grid, chosen by solving a QUBO that
|
| 5 |
+
trades off (a) how far the chosen angle is from the original and
|
| 6 |
+
(b) how much transpiled depth the discrete choice costs on the target
|
| 7 |
+
backend. The QUBO is solved via QAOA + COBYLA.
|
| 8 |
+
|
| 9 |
+
The module exposes four functions consumed by
|
| 10 |
+
``app/services/workflow_service.py``:
|
| 11 |
+
:func:`get_LUT`, :func:`quadraticProgram_luttoqp`,
|
| 12 |
+
:func:`admmOptimizedCompVQC`, :func:`resultsCompressVQC`.
|
| 13 |
"""
|
| 14 |
|
| 15 |
+
from __future__ import annotations
|
|
|
|
| 16 |
|
| 17 |
+
import logging
|
| 18 |
+
from types import SimpleNamespace
|
| 19 |
+
from typing import Any
|
| 20 |
|
| 21 |
+
import numpy as np
|
| 22 |
+
from qiskit import QuantumCircuit, qasm3, qpy, transpile
|
| 23 |
+
from qiskit.circuit import Parameter, ParameterExpression
|
| 24 |
+
from qiskit.circuit.library import RYGate
|
| 25 |
+
from qiskit.primitives import StatevectorSampler
|
| 26 |
from qiskit_algorithms import QAOA
|
| 27 |
from qiskit_algorithms.optimizers import COBYLA
|
|
|
|
|
|
|
| 28 |
from qiskit_ibm_runtime.fake_provider import FakeFez
|
| 29 |
+
from qiskit_optimization.algorithms import MinimumEigenOptimizer
|
| 30 |
+
from qiskit_optimization.converters import QuadraticProgramToQubo
|
| 31 |
+
from qiskit_optimization.problems import QuadraticProgram
|
| 32 |
|
| 33 |
+
logger = logging.getLogger(__name__)
|
|
|
|
| 34 |
|
| 35 |
|
| 36 |
+
# ---- Hyperparameters ---------------------------------------------------
|
|
|
|
| 37 |
|
| 38 |
+
VQC_GATE_TYPES: tuple[str, ...] = ("ry", "rx", "rz", "p")
|
| 39 |
+
"""Parameterised single-qubit rotation gate names considered for
|
| 40 |
+
replacement. CX and other entanglers are left untouched."""
|
| 41 |
|
| 42 |
+
DEFAULT_THETA_GRID: tuple[float, ...] = (
|
| 43 |
+
0.0,
|
| 44 |
+
np.pi / 2,
|
| 45 |
+
np.pi,
|
| 46 |
+
3 * np.pi / 2,
|
| 47 |
+
2 * np.pi,
|
| 48 |
+
)
|
| 49 |
+
"""Discrete angles each parameterised gate can be snapped to. Five
|
| 50 |
+
candidates keeps the QUBO small; denser grids blow up QAOA runtime."""
|
| 51 |
|
| 52 |
+
LAMBDA_PENALTY = 0.1
|
| 53 |
+
"""QP coefficient on transpiled-depth cost (vs. angle-distance cost)."""
|
| 54 |
+
|
| 55 |
+
COBYLA_MAXITER = 4
|
| 56 |
+
"""Inner-loop COBYLA iterations inside QAOA. Intentionally small —
|
| 57 |
+
CompressVQC runs at demo latency budgets, not research-grade accuracy."""
|
| 58 |
+
|
| 59 |
+
THETA_ID_SCALE = 1000
|
| 60 |
+
"""Scale factor used to encode angles as stable integer IDs in QP
|
| 61 |
+
variable names (avoids float formatting round-tripping)."""
|
| 62 |
+
|
| 63 |
+
DECISION_THRESHOLD = 0.5
|
| 64 |
+
"""Binary-variable cutoff when reading the QAOA solution back."""
|
| 65 |
|
| 66 |
+
|
| 67 |
+
# ---- Step 1: per-gate depth LUT ---------------------------------------
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def get_gates_to_map(qc: QuantumCircuit) -> set[str]:
|
| 71 |
+
"""Return the set of parameterised rotation-gate names actually
|
| 72 |
+
present in ``qc`` (a subset of :data:`VQC_GATE_TYPES`)."""
|
| 73 |
+
gates_to_map: set[str] = set()
|
| 74 |
+
for instruction in qc.data:
|
| 75 |
+
if instruction.operation.name in VQC_GATE_TYPES:
|
| 76 |
+
gates_to_map.add(instruction.operation.name)
|
| 77 |
+
logger.info("Targeting gates: %s", sorted(gates_to_map))
|
| 78 |
return gates_to_map
|
| 79 |
|
| 80 |
|
| 81 |
+
def get_LUT(qc: QuantumCircuit, backend: Any) -> dict[str, dict[float, int]]:
|
| 82 |
+
"""Build a ``{gate_name: {theta: transpiled_depth}}`` lookup table.
|
| 83 |
|
| 84 |
+
For each candidate (gate, θ) pair, place the gate on a fresh
|
| 85 |
+
two-qubit scratch circuit, transpile against ``backend``, and
|
| 86 |
+
record the resulting depth. Used later as the QUBO's depth-cost
|
| 87 |
+
term.
|
| 88 |
+
"""
|
| 89 |
gates_to_map = get_gates_to_map(qc)
|
| 90 |
+
lut: dict[str, dict[float, int]] = {}
|
| 91 |
|
| 92 |
for gate in gates_to_map:
|
| 93 |
lut[gate] = {}
|
| 94 |
+
for theta in DEFAULT_THETA_GRID:
|
|
|
|
| 95 |
test_qc = QuantumCircuit(2)
|
| 96 |
+
if gate == "rx":
|
|
|
|
| 97 |
test_qc.rx(theta, 0)
|
| 98 |
+
elif gate == "ry":
|
| 99 |
test_qc.ry(theta, 0)
|
| 100 |
+
elif gate == "rz":
|
| 101 |
test_qc.rz(theta, 0)
|
| 102 |
+
elif gate == "p":
|
| 103 |
test_qc.p(theta, 0)
|
|
|
|
|
|
|
| 104 |
|
| 105 |
transpiled_qc = transpile(test_qc, backend=backend, optimization_level=1)
|
| 106 |
+
lut[gate][round(theta, 3)] = transpiled_qc.depth()
|
| 107 |
|
| 108 |
+
logger.debug("Depth LUT: %s", lut)
|
|
|
|
|
|
|
|
|
|
| 109 |
return lut
|
| 110 |
|
| 111 |
|
| 112 |
+
# ---- Step 2: LUT → QuadraticProgram -----------------------------------
|
|
|
|
| 113 |
|
| 114 |
|
| 115 |
+
def qaoa_callback(eval_count: int, parameters: Any, value: float, metadata: Any) -> None:
|
| 116 |
+
"""Progress callback for the inner QAOA optimisation."""
|
| 117 |
+
logger.info("QAOA eval %d: energy %.6f", eval_count, value)
|
| 118 |
|
| 119 |
|
| 120 |
+
def quadraticProgram_luttoqp(
|
| 121 |
+
qc: QuantumCircuit, lut: dict[str, dict[float, int]]
|
| 122 |
+
) -> QuadraticProgram:
|
| 123 |
+
"""Encode the per-gate angle-selection problem as a linear QP:
|
| 124 |
+
one binary variable per (gate_index, candidate_theta), minimising
|
| 125 |
+
(θ - original)² + λ · depth under "exactly one candidate per gate"
|
| 126 |
+
constraints."""
|
| 127 |
qp = QuadraticProgram("CompressVQC")
|
| 128 |
+
obj_dict: dict[str, float] = {}
|
|
|
|
| 129 |
|
| 130 |
for i, instruction in enumerate(qc.data):
|
| 131 |
gate = instruction.operation
|
| 132 |
+
if gate.name not in lut:
|
| 133 |
+
continue
|
| 134 |
+
|
| 135 |
+
p_val = gate.params[0]
|
| 136 |
+
# Parameterised placeholders have no concrete value yet — fall
|
| 137 |
+
# back to 0.5 so the optimiser can still prefer "middle" angles.
|
| 138 |
+
original_val = (
|
| 139 |
+
float(p_val)
|
| 140 |
+
if not isinstance(p_val, (Parameter, ParameterExpression))
|
| 141 |
+
else 0.5
|
| 142 |
+
)
|
| 143 |
+
|
| 144 |
+
gate_var_names: list[str] = []
|
| 145 |
+
for theta_lut, depth in lut[gate.name].items():
|
| 146 |
+
theta_id = int(round(theta_lut * THETA_ID_SCALE))
|
| 147 |
+
var_name = f"gate_{i}_{gate.name}_{theta_id}"
|
| 148 |
+
qp.binary_var(name=var_name)
|
| 149 |
+
gate_var_names.append(var_name)
|
| 150 |
+
|
| 151 |
+
obj_dict[var_name] = (theta_lut - original_val) ** 2 + (LAMBDA_PENALTY * depth)
|
| 152 |
+
|
| 153 |
+
qp.linear_constraint(
|
| 154 |
+
linear={name: 1 for name in gate_var_names},
|
| 155 |
+
sense="==",
|
| 156 |
+
rhs=1,
|
| 157 |
+
)
|
| 158 |
|
| 159 |
qp.minimize(linear=obj_dict)
|
| 160 |
return qp
|
| 161 |
|
| 162 |
|
| 163 |
+
# ---- Step 3: QAOA-solve the QUBO --------------------------------------
|
|
|
|
|
|
|
| 164 |
|
| 165 |
|
| 166 |
+
def admmOptimizedCompVQC(qp: QuadraticProgram) -> SimpleNamespace:
|
| 167 |
+
"""Solve ``qp`` via QAOA on a state-vector simulator and return a
|
| 168 |
+
duck-typed object exposing ``variables_dict`` (mapping each binary
|
| 169 |
+
variable back to its chosen 0/1 value). Returning
|
| 170 |
+
:class:`SimpleNamespace` rather than the raw
|
| 171 |
+
:class:`qiskit_optimization.algorithms.OptimizationResult` keeps
|
| 172 |
+
the downstream consumer loose-coupled.
|
| 173 |
+
"""
|
| 174 |
sampler = StatevectorSampler()
|
| 175 |
+
optimizer = COBYLA(maxiter=COBYLA_MAXITER)
|
| 176 |
|
| 177 |
qaoa = QAOA(
|
| 178 |
sampler=sampler,
|
| 179 |
optimizer=optimizer,
|
| 180 |
+
callback=qaoa_callback,
|
| 181 |
)
|
| 182 |
|
| 183 |
conv = QuadraticProgramToQubo()
|
| 184 |
qubo = conv.convert(qp)
|
| 185 |
|
| 186 |
+
min_eigen = MinimumEigenOptimizer(qaoa)
|
| 187 |
+
result = min_eigen.solve(qubo)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 188 |
|
| 189 |
+
# Convert QUBO solution back into original variable space.
|
| 190 |
original_x = conv.interpret(result.x)
|
| 191 |
|
| 192 |
+
variables_dict: dict[str, float] = {
|
| 193 |
+
var.name: original_x[i] for i, var in enumerate(qp.variables)
|
| 194 |
+
}
|
| 195 |
+
return SimpleNamespace(variables_dict=variables_dict)
|
| 196 |
|
|
|
|
|
|
|
| 197 |
|
| 198 |
+
# ---- Step 4: rebuild circuit from chosen angles -----------------------
|
| 199 |
|
| 200 |
|
| 201 |
+
def resultsCompressVQC(result: SimpleNamespace, original_qc: QuantumCircuit) -> QuantumCircuit:
|
| 202 |
+
"""Walk ``original_qc`` and, for every ``ry`` gate, swap in the
|
| 203 |
+
candidate angle that the QAOA solution marked as "chosen"
|
| 204 |
+
(variable value above :data:`DECISION_THRESHOLD`). Non-``ry`` gates
|
| 205 |
+
pass through unchanged.
|
| 206 |
|
| 207 |
+
Currently only ``ry`` is rewritten — the QP is built over all four
|
| 208 |
+
rotation types but the rebuild step here conservatively only acts
|
| 209 |
+
on ``ry``; extending it to the others is straightforward if the
|
| 210 |
+
underlying demo circuits ever use them.
|
| 211 |
+
"""
|
|
|
|
|
|
|
| 212 |
compressed_qc = QuantumCircuit(*original_qc.qregs, *original_qc.cregs)
|
| 213 |
|
| 214 |
for i, instr in enumerate(original_qc.data):
|
|
|
|
| 215 |
gate = instr.operation
|
| 216 |
qargs = instr.qubits
|
| 217 |
cargs = instr.clbits
|
|
|
|
| 220 |
|
| 221 |
if gate.name == "ry":
|
| 222 |
for var_name, var_value in result.variables_dict.items():
|
| 223 |
+
if var_value > DECISION_THRESHOLD and var_name.startswith(f"gate_{i}_ry_"):
|
|
|
|
|
|
|
| 224 |
theta_id = int(var_name.split("_")[-1])
|
| 225 |
+
new_theta = theta_id / THETA_ID_SCALE
|
| 226 |
new_gate = RYGate(new_theta)
|
| 227 |
|
|
|
|
| 228 |
compressed_qc.append(new_gate, qargs, cargs)
|
| 229 |
|
| 230 |
+
# NOTE: we deliberately do NOT transpile the compressed circuit
|
| 231 |
+
# here. The original prototype did ``transpile(..., basis_gates=
|
| 232 |
+
# ['sx', 'rz', 'cx', 'id'], optimization_level=3)`` but that moved
|
| 233 |
+
# the compression benefit into the transpiler's pocket and made
|
| 234 |
+
# before/after comparisons confusing. The service layer handles
|
| 235 |
+
# backend-specific transpilation at the point where it's needed.
|
| 236 |
return compressed_qc
|
| 237 |
|
| 238 |
|
| 239 |
+
# ---- Sample VQC generator (used by precompute / ad-hoc testing) --------
|
| 240 |
|
| 241 |
|
| 242 |
+
def gen_example_vqc(out_path: str | None = None) -> QuantumCircuit:
|
| 243 |
+
"""Build a tiny 2-qubit example VQC with symbolic parameters.
|
| 244 |
+
If ``out_path`` is given, additionally dump it as OpenQASM 3."""
|
| 245 |
qc = QuantumCircuit(2)
|
| 246 |
+
theta_0 = Parameter("theta_0")
|
| 247 |
+
theta_1 = Parameter("theta_1")
|
|
|
|
|
|
|
| 248 |
qc.ry(theta_0, 0)
|
| 249 |
qc.ry(theta_1, 1)
|
| 250 |
qc.cx(0, 1)
|
|
|
|
| 252 |
if out_path is not None:
|
| 253 |
with open(out_path, "w") as f:
|
| 254 |
qasm3.dump(qc, f)
|
| 255 |
+
logger.info("Wrote example VQC to %s", out_path)
|
| 256 |
return qc
|
| 257 |
|
| 258 |
|
|
|
|
|
|
|
|
|
|
| 259 |
if __name__ == "__main__":
|
| 260 |
# Minimal CLI entry for ad-hoc testing outside the web app.
|
| 261 |
# Expects one environment variable:
|
| 262 |
# COMPVQC_QPY_FILE - path to a .qpy file holding the VQC to compress
|
| 263 |
import os
|
| 264 |
|
| 265 |
+
logging.basicConfig(level=logging.INFO)
|
| 266 |
+
|
| 267 |
qpy_path = os.environ["COMPVQC_QPY_FILE"]
|
| 268 |
with open(qpy_path, "rb") as f:
|
| 269 |
qc = qpy.load(f)[0]
|
| 270 |
|
| 271 |
+
logger.info("Input circuit:\n%s", qc)
|
| 272 |
|
| 273 |
backend = FakeFez()
|
|
|
|
| 274 |
lut = get_LUT(qc, backend)
|
| 275 |
qp = quadraticProgram_luttoqp(qc, lut)
|
| 276 |
result = admmOptimizedCompVQC(qp)
|
| 277 |
compressed_qc = resultsCompressVQC(result, qc)
|
| 278 |
|
| 279 |
+
logger.info("==== COMPRESSED CIRCUIT ====\n%s", compressed_qc)
|
|
|
|
@@ -1,254 +1,311 @@
|
|
| 1 |
"""QuBound implementation (refactored from Jovin Antony Maria's original).
|
| 2 |
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6 |
"""
|
| 7 |
|
| 8 |
-
from
|
| 9 |
-
from qiskit import QuantumCircuit
|
| 10 |
-
from qiskit_aer.noise import NoiseModel
|
| 11 |
-
from qiskit_aer import AerSimulator
|
| 12 |
-
from qiskit.quantum_info import hellinger_distance # state_fidelity and total variation distance are used for simple Fidelity calculations
|
| 13 |
-
from qiskit import transpile
|
| 14 |
-
from qiskit_ibm_runtime.fake_provider import FakeFez
|
| 15 |
-
from qiskit import qpy
|
| 16 |
-
|
| 17 |
-
import torch
|
| 18 |
-
from torch import nn
|
| 19 |
|
|
|
|
|
|
|
| 20 |
from datetime import datetime, timedelta
|
|
|
|
|
|
|
|
|
|
| 21 |
import numpy as np
|
| 22 |
import pandas as pd
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 23 |
|
| 24 |
-
def get_gate_name_for_pair(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 25 |
target_qubits = list(qubits)
|
| 26 |
-
|
| 27 |
for gate_info in properties.gates:
|
| 28 |
if gate_info.qubits == target_qubits:
|
| 29 |
return gate_info.gate
|
| 30 |
-
|
| 31 |
return None
|
| 32 |
|
| 33 |
-
# function to get the necessary noise data from ibm_cloud
|
| 34 |
-
# gets the properties object for each day of the 14 day window
|
| 35 |
-
def look_back_window_ForError(backend, date_selected = datetime.now()):
|
| 36 |
-
look_back_days = 14
|
| 37 |
-
historical_data = []
|
| 38 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 39 |
if date_selected is None:
|
| 40 |
date_selected = datetime.now()
|
| 41 |
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
for i in range(look_back_days, 0, -1):
|
| 45 |
-
# target_date = datetime.now() - timedelta(days = i) #
|
| 46 |
-
target_date = date_selected - timedelta(days = i)
|
| 47 |
-
# print(target_date)
|
| 48 |
-
|
| 49 |
-
properties = backend.properties(datetime = target_date)
|
| 50 |
|
| 51 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 52 |
"date": target_date.strftime("%Y-%m-%d"),
|
| 53 |
-
"properties": properties
|
| 54 |
-
}
|
| 55 |
-
|
| 56 |
-
|
|
|
|
| 57 |
return historical_data
|
| 58 |
|
| 59 |
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
|
|
|
|
|
|
|
|
|
| 65 |
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
# create a temp circuit, This was done in the q_adapt implementaiton, and compressVQC
|
| 69 |
-
# qc = QuantumCircuit(2)
|
| 70 |
-
# qc.h(0)
|
| 71 |
-
# qc.cx(0, 1)
|
| 72 |
qc.measure_all()
|
| 73 |
-
# print(qc)
|
| 74 |
-
|
| 75 |
qc = transpile(qc, backend, optimization_level=3)
|
|
|
|
| 76 |
simulator = AerSimulator()
|
| 77 |
-
|
| 78 |
-
nonoise_value = simulator.run(qc, shots = 2048).result().get_counts()
|
| 79 |
|
|
|
|
| 80 |
for history in historic_data:
|
| 81 |
-
properties = history[
|
| 82 |
-
noise_model = NoiseModel.from_backend(backend, properties)
|
| 83 |
-
noisy_simulator = AerSimulator(noise_model
|
| 84 |
-
noise_value = noisy_simulator.run(qc, shots
|
| 85 |
|
| 86 |
-
#
|
|
|
|
| 87 |
error = hellinger_distance(nonoise_value, noise_value)
|
| 88 |
labels.append(error)
|
| 89 |
|
| 90 |
-
return torch.tensor(labels, dtype
|
| 91 |
|
| 92 |
-
# this uses the output form the previous funciton to get the
|
| 93 |
-
# T1, Tw, Readout and gate errors
|
| 94 |
-
def extract_time_series_from_historic(historical_data, qubit_indices = [0], gate_qubit = [(0,1)]):
|
| 95 |
-
print("Starting Error values Extraction from historic data.")
|
| 96 |
-
extracted_data = []
|
| 97 |
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 101 |
|
| 102 |
-
|
| 103 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 104 |
|
| 105 |
-
# get the respective T1, T2, readout errors
|
| 106 |
for i in qubit_indices:
|
| 107 |
-
row[f
|
| 108 |
-
row[f
|
| 109 |
-
row[f
|
| 110 |
|
| 111 |
-
# getting the gate errors
|
| 112 |
for g in gate_qubit:
|
| 113 |
gate_name = get_gate_name_for_pair(properties, g)
|
| 114 |
-
row[f
|
| 115 |
|
| 116 |
extracted_data.append(row)
|
| 117 |
|
| 118 |
-
|
| 119 |
-
|
| 120 |
|
|
|
|
| 121 |
|
| 122 |
-
# ---------- Perform QuDeCOM
|
| 123 |
|
| 124 |
-
def decompose_noise(df):
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
|
|
|
| 129 |
residual = df - trend
|
|
|
|
| 130 |
|
| 131 |
-
# extract the prdictable drift and unpredictable fluctuations, according to the paper
|
| 132 |
-
return trend, residual
|
| 133 |
|
|
|
|
| 134 |
|
| 135 |
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
print("preprocessing lstm data ==")
|
| 141 |
data = df.values
|
| 142 |
-
sequences = []
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
return torch.tensor(np.array(sequences), dtype=torch.float32) # convert to torch tensor, so that we can pass it to a lstm
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
#------------------------------
|
| 150 |
-
# Finally now that pre-processing is complete,
|
| 151 |
-
# the LSTM model
|
| 152 |
-
# or QuPRED
|
| 153 |
-
#--------------------------------
|
| 154 |
class QuPred(nn.Module):
|
| 155 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 156 |
super().__init__()
|
| 157 |
self.lstm = nn.LSTM(input_features, blocks, batch_first=True)
|
| 158 |
self.fc = nn.Linear(blocks, 1)
|
| 159 |
|
| 160 |
-
def forward(self, x):
|
| 161 |
_, (h_n, _) = self.lstm(x)
|
| 162 |
return self.fc(h_n[-1])
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
|
|
|
|
|
|
| 170 |
errors = targets - preds
|
| 171 |
return torch.max(confidence * errors, (confidence - 1) * errors).mean()
|
| 172 |
|
| 173 |
-
def train_loop(x_train, y_train):
|
| 174 |
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
|
|
|
|
|
|
| 180 |
|
| 181 |
-
|
| 182 |
-
for epoch in range(epochs):
|
| 183 |
model.train()
|
| 184 |
model.zero_grad()
|
| 185 |
|
| 186 |
-
predictions = model(x_train)
|
| 187 |
-
loss = loss_fn(predictions, y_train, confidence
|
| 188 |
-
|
| 189 |
-
# calculate the gradients
|
| 190 |
loss.backward()
|
| 191 |
-
# make changes to the weights
|
| 192 |
optimizer.step()
|
| 193 |
|
| 194 |
-
if epoch %
|
| 195 |
-
|
| 196 |
-
|
| 197 |
return model
|
| 198 |
|
| 199 |
-
|
|
|
|
|
|
|
|
|
|
| 200 |
model.eval()
|
| 201 |
with torch.no_grad():
|
|
|
|
|
|
|
| 202 |
|
| 203 |
-
# model.eval()
|
| 204 |
-
# with torch.no_grad():
|
| 205 |
-
# # Take the VERY LAST noise, which is today's noise to predict the performance
|
| 206 |
-
# latest_noise = x_train[-1].unsqueeze(0)
|
| 207 |
-
# predicted_bound = model(latest_noise_sequence)
|
| 208 |
-
# print(f"The predicted error bound today: {predicted_bound.item():.4f}")
|
| 209 |
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
return predicted_bound
|
| 214 |
-
|
| 215 |
-
def _train_and_predict(qc, historic_data, provider):
|
| 216 |
"""Shared QuBound pipeline once ``historic_data`` is available.
|
| 217 |
|
| 218 |
-
Pulls the time-series features out of
|
| 219 |
trains the LSTM on noise-aware labels from a Qiskit Aer simulation,
|
| 220 |
-
and returns
|
| 221 |
"""
|
| 222 |
extracted_df = extract_time_series_from_historic(historic_data)
|
| 223 |
trend_df, residual_df = decompose_noise(extracted_df)
|
| 224 |
|
| 225 |
-
combined_df = pd.concat([trend_df, residual_df], axis=1)
|
| 226 |
-
combined_df = combined_df.fillna(0)
|
| 227 |
normalized_df = (combined_df - combined_df.mean()) / combined_df.std()
|
| 228 |
|
| 229 |
-
x_train = create_sequences(normalized_df, window_size=
|
| 230 |
y_train = get_labels_fromNoise(qc, historic_data, provider)
|
| 231 |
-
y_train = y_train[
|
| 232 |
|
| 233 |
model = train_loop(x_train, y_train)
|
| 234 |
final_bound = predict_vqc_bound(model, x_train)
|
| 235 |
return final_bound, model
|
| 236 |
|
| 237 |
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
|
|
|
|
|
|
|
|
|
|
| 241 |
"""Run QuBound against the **live** IBM Quantum Platform API.
|
| 242 |
|
| 243 |
-
Fetches
|
| 244 |
-
Slow (live fetch is ~15 s) and
|
|
|
|
| 245 |
|
| 246 |
Parameters
|
| 247 |
----------
|
| 248 |
qc : QuantumCircuit
|
| 249 |
-
provider : qiskit backend (fake or real) used for
|
| 250 |
-
|
| 251 |
-
|
|
|
|
| 252 |
"""
|
| 253 |
if date is None:
|
| 254 |
date = datetime.now()
|
|
@@ -262,25 +319,29 @@ def call_QuBound(qc, provider, token, date=None):
|
|
| 262 |
return _train_and_predict(qc, historic_data, provider)
|
| 263 |
|
| 264 |
|
| 265 |
-
def call_QuBound_from_cache(
|
| 266 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 267 |
|
| 268 |
Parameters
|
| 269 |
----------
|
| 270 |
qc : QuantumCircuit
|
| 271 |
-
cached_history_path :
|
| 272 |
-
|
| 273 |
-
reference_backend :
|
| 274 |
-
|
| 275 |
-
|
| 276 |
|
| 277 |
Returns
|
| 278 |
-------
|
| 279 |
-
(predicted_bound, model, metadata) :
|
| 280 |
-
|
|
|
|
| 281 |
"""
|
| 282 |
-
import pickle
|
| 283 |
-
|
| 284 |
with open(cached_history_path, "rb") as fh:
|
| 285 |
payload = pickle.load(fh)
|
| 286 |
|
|
@@ -302,19 +363,18 @@ def call_QuBound_from_cache(qc, cached_history_path, reference_backend=None):
|
|
| 302 |
return bound, model, metadata
|
| 303 |
|
| 304 |
|
| 305 |
-
|
| 306 |
-
|
| 307 |
-
|
| 308 |
-
if __name__ == '__main__':
|
| 309 |
# Minimal CLI entry for ad-hoc testing outside the web app.
|
| 310 |
# Expects two environment variables:
|
| 311 |
# IBM_QUANTUM_TOKEN - IBM Quantum Platform API token
|
| 312 |
# QBOUND_QPY_FILE - path to a .qpy file holding the trained VQC
|
| 313 |
import os
|
| 314 |
|
|
|
|
|
|
|
| 315 |
token = os.environ["IBM_QUANTUM_TOKEN"]
|
| 316 |
qpy_path = os.environ["QBOUND_QPY_FILE"]
|
| 317 |
with open(qpy_path, "rb") as file:
|
| 318 |
qc = qpy.load(file)[0]
|
| 319 |
bound, _model = call_QuBound(qc, FakeFez(), token=token)
|
| 320 |
-
|
|
|
|
| 1 |
"""QuBound implementation (refactored from Jovin Antony Maria's original).
|
| 2 |
|
| 3 |
+
Algorithm overview: given a VQC plus 14 days of historical backend noise
|
| 4 |
+
calibration data, train an LSTM to predict the ``hellinger_distance``
|
| 5 |
+
between the noiseless circuit output and today's noisy output — i.e.
|
| 6 |
+
how much the output distribution will drift under the current hardware.
|
| 7 |
+
|
| 8 |
+
Two entry points:
|
| 9 |
+
|
| 10 |
+
* :func:`call_QuBound` — live path, fetches calibration history from
|
| 11 |
+
IBM Quantum Platform (requires a valid token, slow, ~15 s).
|
| 12 |
+
* :func:`call_QuBound_from_cache` — offline path, reads a pickle
|
| 13 |
+
produced by ``scripts/fetch_ibm_history.py``. Used by the HF Space
|
| 14 |
+
demo so it can run without network or credentials.
|
| 15 |
"""
|
| 16 |
|
| 17 |
+
from __future__ import annotations
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 18 |
|
| 19 |
+
import logging
|
| 20 |
+
import pickle
|
| 21 |
from datetime import datetime, timedelta
|
| 22 |
+
from pathlib import Path
|
| 23 |
+
from typing import Any
|
| 24 |
+
|
| 25 |
import numpy as np
|
| 26 |
import pandas as pd
|
| 27 |
+
import torch
|
| 28 |
+
from qiskit import QuantumCircuit, qpy, transpile
|
| 29 |
+
from qiskit.quantum_info import hellinger_distance
|
| 30 |
+
from qiskit_aer import AerSimulator
|
| 31 |
+
from qiskit_aer.noise import NoiseModel
|
| 32 |
+
from qiskit_ibm_runtime import QiskitRuntimeService
|
| 33 |
+
from qiskit_ibm_runtime.fake_provider import FakeFez
|
| 34 |
+
from torch import nn
|
| 35 |
+
|
| 36 |
+
logger = logging.getLogger(__name__)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
# ---- Hyperparameters ---------------------------------------------------
|
| 40 |
+
# Exposed as module-level constants so future ablation studies don't need
|
| 41 |
+
# to hunt them down inside function bodies.
|
| 42 |
+
|
| 43 |
+
HISTORY_WINDOW_DAYS = 14
|
| 44 |
+
"""Number of past days of calibration snapshots to pull from a backend."""
|
| 45 |
+
|
| 46 |
+
PROGRESS_PRINT_INTERVAL = 7
|
| 47 |
+
"""Log a progress message every N days while fetching calibrations."""
|
| 48 |
+
|
| 49 |
+
SHOTS = 2048
|
| 50 |
+
"""Shots per Aer simulator run when producing noisy / noiseless labels."""
|
| 51 |
+
|
| 52 |
+
SEQUENCE_WINDOW_SIZE = 5
|
| 53 |
+
"""Sliding-window length fed into the LSTM (days of context per sample)."""
|
| 54 |
+
|
| 55 |
+
LSTM_INPUT_FEATURES = 8
|
| 56 |
+
"""Per-timestep feature count: T1/T2/readout (x1 qubit) + 1 gate error,
|
| 57 |
+
doubled once trend/residual are concatenated. Kept as a constant because
|
| 58 |
+
it is coupled to :func:`extract_time_series_from_historic` — changing
|
| 59 |
+
the feature extraction must update this value."""
|
| 60 |
+
|
| 61 |
+
LSTM_HIDDEN_BLOCKS = 16
|
| 62 |
+
"""LSTM hidden state size."""
|
| 63 |
+
|
| 64 |
+
LSTM_LEARNING_RATE = 0.01
|
| 65 |
+
LSTM_EPOCHS = 50
|
| 66 |
+
LSTM_LOG_EPOCH_INTERVAL = 10
|
| 67 |
+
|
| 68 |
+
CONFIDENCE_LEVEL = 0.95
|
| 69 |
+
"""Upper-quantile weight in the asymmetric pinball loss; predicts the
|
| 70 |
+
95th-percentile error bound."""
|
| 71 |
+
|
| 72 |
|
| 73 |
+
def get_gate_name_for_pair(
|
| 74 |
+
properties: Any, qubits: tuple[int, int]
|
| 75 |
+
) -> str | None:
|
| 76 |
+
"""Return the two-qubit gate name (``cx``/``cz``/``ecr``) that acts
|
| 77 |
+
on the given qubit pair, according to ``properties.gates``. Returns
|
| 78 |
+
``None`` if no gate targets exactly those qubits."""
|
| 79 |
target_qubits = list(qubits)
|
|
|
|
| 80 |
for gate_info in properties.gates:
|
| 81 |
if gate_info.qubits == target_qubits:
|
| 82 |
return gate_info.gate
|
|
|
|
| 83 |
return None
|
| 84 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 85 |
|
| 86 |
+
def look_back_window_ForError(
|
| 87 |
+
backend: Any, date_selected: datetime | None = None
|
| 88 |
+
) -> list[dict[str, Any]]:
|
| 89 |
+
"""Fetch ``HISTORY_WINDOW_DAYS`` days of ``BackendProperties``
|
| 90 |
+
ending at ``date_selected`` (default: now).
|
| 91 |
+
|
| 92 |
+
Returns a list of ``{"date": "YYYY-MM-DD", "properties": <obj>}``
|
| 93 |
+
dicts ordered from oldest to most recent.
|
| 94 |
+
"""
|
| 95 |
if date_selected is None:
|
| 96 |
date_selected = datetime.now()
|
| 97 |
|
| 98 |
+
logger.info("Starting calibration data collection over %d days", HISTORY_WINDOW_DAYS)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 99 |
|
| 100 |
+
historical_data: list[dict[str, Any]] = []
|
| 101 |
+
for i in range(HISTORY_WINDOW_DAYS, 0, -1):
|
| 102 |
+
target_date = date_selected - timedelta(days=i)
|
| 103 |
+
properties = backend.properties(datetime=target_date)
|
| 104 |
+
historical_data.append(
|
| 105 |
+
{
|
| 106 |
"date": target_date.strftime("%Y-%m-%d"),
|
| 107 |
+
"properties": properties,
|
| 108 |
+
}
|
| 109 |
+
)
|
| 110 |
+
if i % PROGRESS_PRINT_INTERVAL == 0:
|
| 111 |
+
logger.info("Half way done...")
|
| 112 |
return historical_data
|
| 113 |
|
| 114 |
|
| 115 |
+
def get_labels_fromNoise(
|
| 116 |
+
qc: QuantumCircuit, historic_data: list[dict[str, Any]], backend: Any
|
| 117 |
+
) -> torch.Tensor:
|
| 118 |
+
"""For each historical day, compute the Hellinger distance between
|
| 119 |
+
the noiseless counts and the noisy counts (noise model built from
|
| 120 |
+
that day's properties). Returns a 1-D tensor of error labels, one
|
| 121 |
+
per day, suitable as LSTM supervision."""
|
| 122 |
+
logger.info("Computing error labels from circuit noiseless vs. noisy runs")
|
| 123 |
|
| 124 |
+
# Mutation by design: attaches measurements so the Aer shots mean
|
| 125 |
+
# something. Caller doesn't reuse ``qc`` after this point.
|
|
|
|
|
|
|
|
|
|
|
|
|
| 126 |
qc.measure_all()
|
|
|
|
|
|
|
| 127 |
qc = transpile(qc, backend, optimization_level=3)
|
| 128 |
+
|
| 129 |
simulator = AerSimulator()
|
| 130 |
+
nonoise_value = simulator.run(qc, shots=SHOTS).result().get_counts()
|
|
|
|
| 131 |
|
| 132 |
+
labels: list[float] = []
|
| 133 |
for history in historic_data:
|
| 134 |
+
properties = history["properties"]
|
| 135 |
+
noise_model = NoiseModel.from_backend(backend, properties)
|
| 136 |
+
noisy_simulator = AerSimulator(noise_model=noise_model)
|
| 137 |
+
noise_value = noisy_simulator.run(qc, shots=SHOTS).result().get_counts()
|
| 138 |
|
| 139 |
+
# Hellinger is a proper metric on probability distributions,
|
| 140 |
+
# bounded in [0, 1] — convenient for training.
|
| 141 |
error = hellinger_distance(nonoise_value, noise_value)
|
| 142 |
labels.append(error)
|
| 143 |
|
| 144 |
+
return torch.tensor(labels, dtype=torch.float32)
|
| 145 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 146 |
|
| 147 |
+
def extract_time_series_from_historic(
|
| 148 |
+
historical_data: list[dict[str, Any]],
|
| 149 |
+
qubit_indices: list[int] | None = None,
|
| 150 |
+
gate_qubit: list[tuple[int, int]] | None = None,
|
| 151 |
+
) -> pd.DataFrame:
|
| 152 |
+
"""Unpack T1 / T2 / readout error / two-qubit gate error into a
|
| 153 |
+
tidy per-day DataFrame, indexed by date. Defaults to qubit 0 and
|
| 154 |
+
the (0, 1) pair — the smallest circuit we ever exercise."""
|
| 155 |
+
if qubit_indices is None:
|
| 156 |
+
qubit_indices = [0]
|
| 157 |
+
if gate_qubit is None:
|
| 158 |
+
gate_qubit = [(0, 1)]
|
| 159 |
|
| 160 |
+
logger.info("Extracting per-qubit error time series from historic data")
|
| 161 |
|
| 162 |
+
extracted_data: list[dict[str, Any]] = []
|
| 163 |
+
for history in historical_data:
|
| 164 |
+
properties = history["properties"]
|
| 165 |
+
row: dict[str, Any] = {"date": history["date"]}
|
| 166 |
|
|
|
|
| 167 |
for i in qubit_indices:
|
| 168 |
+
row[f"q{i}_t1"] = properties.t1(i)
|
| 169 |
+
row[f"q{i}_t2"] = properties.t2(i)
|
| 170 |
+
row[f"q{i}_readout_err"] = properties.readout_error(i)
|
| 171 |
|
|
|
|
| 172 |
for g in gate_qubit:
|
| 173 |
gate_name = get_gate_name_for_pair(properties, g)
|
| 174 |
+
row[f"gate_err_{g[0]}_{g[1]}"] = properties.gate_error(gate_name, g)
|
| 175 |
|
| 176 |
extracted_data.append(row)
|
| 177 |
|
| 178 |
+
return pd.DataFrame(extracted_data).set_index("date")
|
| 179 |
+
|
| 180 |
|
| 181 |
+
# ---- QuDeCOM: trend / residual split -----------------------------------
|
| 182 |
|
|
|
|
| 183 |
|
| 184 |
+
def decompose_noise(df: pd.DataFrame) -> tuple[pd.DataFrame, pd.DataFrame]:
|
| 185 |
+
"""Split a noise time series into a rolling-mean trend (predictable
|
| 186 |
+
drift) and the residual (unpredictable fluctuations). Matches the
|
| 187 |
+
decomposition described in the QuBound paper."""
|
| 188 |
+
logger.info("Decomposing extracted time series into trend and residual")
|
| 189 |
+
trend = df.rolling(window=3, min_periods=1).mean()
|
| 190 |
residual = df - trend
|
| 191 |
+
return trend, residual
|
| 192 |
|
|
|
|
|
|
|
| 193 |
|
| 194 |
+
# ---- LSTM forecaster ---------------------------------------------------
|
| 195 |
|
| 196 |
|
| 197 |
+
def create_sequences(df: pd.DataFrame, window_size: int = SEQUENCE_WINDOW_SIZE) -> torch.Tensor:
|
| 198 |
+
"""Turn a (days x features) DataFrame into overlapping windows of
|
| 199 |
+
length ``window_size`` suitable as LSTM inputs."""
|
| 200 |
+
logger.debug("Building LSTM input sequences with window=%d", window_size)
|
|
|
|
| 201 |
data = df.values
|
| 202 |
+
sequences = [data[i : i + window_size] for i in range(len(data) - window_size)]
|
| 203 |
+
return torch.tensor(np.array(sequences), dtype=torch.float32)
|
| 204 |
+
|
| 205 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 206 |
class QuPred(nn.Module):
|
| 207 |
+
"""LSTM-based error-bound forecaster.
|
| 208 |
+
|
| 209 |
+
One LSTM layer consumes the daily noise sequence; a final linear
|
| 210 |
+
head projects the last hidden state onto a scalar predicted error.
|
| 211 |
+
"""
|
| 212 |
+
|
| 213 |
+
def __init__(self, input_features: int, blocks: int) -> None:
|
| 214 |
super().__init__()
|
| 215 |
self.lstm = nn.LSTM(input_features, blocks, batch_first=True)
|
| 216 |
self.fc = nn.Linear(blocks, 1)
|
| 217 |
|
| 218 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 219 |
_, (h_n, _) = self.lstm(x)
|
| 220 |
return self.fc(h_n[-1])
|
| 221 |
+
|
| 222 |
+
|
| 223 |
+
def loss_fn(
|
| 224 |
+
preds: torch.Tensor, targets: torch.Tensor, confidence: float = CONFIDENCE_LEVEL
|
| 225 |
+
) -> torch.Tensor:
|
| 226 |
+
"""Asymmetric pinball loss: penalises under-prediction at weight
|
| 227 |
+
``confidence`` and over-prediction at weight ``confidence - 1``,
|
| 228 |
+
so minimising it recovers the ``confidence``-quantile of the error
|
| 229 |
+
distribution (default 95%)."""
|
| 230 |
errors = targets - preds
|
| 231 |
return torch.max(confidence * errors, (confidence - 1) * errors).mean()
|
| 232 |
|
|
|
|
| 233 |
|
| 234 |
+
def train_loop(x_train: torch.Tensor, y_train: torch.Tensor) -> QuPred:
|
| 235 |
+
"""Train a fresh :class:`QuPred` for ``LSTM_EPOCHS`` epochs and
|
| 236 |
+
return the trained model. Hyperparameters live as module-level
|
| 237 |
+
constants above."""
|
| 238 |
+
logger.info("Entering LSTM training loop")
|
| 239 |
+
model = QuPred(input_features=LSTM_INPUT_FEATURES, blocks=LSTM_HIDDEN_BLOCKS)
|
| 240 |
+
optimizer = torch.optim.Adam(model.parameters(), lr=LSTM_LEARNING_RATE)
|
| 241 |
|
| 242 |
+
for epoch in range(LSTM_EPOCHS):
|
|
|
|
| 243 |
model.train()
|
| 244 |
model.zero_grad()
|
| 245 |
|
| 246 |
+
predictions = model(x_train)
|
| 247 |
+
loss = loss_fn(predictions, y_train, confidence=CONFIDENCE_LEVEL)
|
|
|
|
|
|
|
| 248 |
loss.backward()
|
|
|
|
| 249 |
optimizer.step()
|
| 250 |
|
| 251 |
+
if epoch % LSTM_LOG_EPOCH_INTERVAL == 0:
|
| 252 |
+
logger.info("Epoch %d | Loss: %.6f", epoch, loss.item())
|
| 253 |
+
|
| 254 |
return model
|
| 255 |
|
| 256 |
+
|
| 257 |
+
def predict_vqc_bound(model: QuPred, x_train: torch.Tensor) -> float:
|
| 258 |
+
"""Evaluate the trained model on the most recent sequence (today's
|
| 259 |
+
noise) and return its scalar error-bound prediction."""
|
| 260 |
model.eval()
|
| 261 |
with torch.no_grad():
|
| 262 |
+
latest_noise = x_train[-1].unsqueeze(0)
|
| 263 |
+
return float(model(latest_noise).item())
|
| 264 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 265 |
|
| 266 |
+
def _train_and_predict(
|
| 267 |
+
qc: QuantumCircuit, historic_data: list[dict[str, Any]], provider: Any
|
| 268 |
+
) -> tuple[float, QuPred]:
|
|
|
|
|
|
|
|
|
|
| 269 |
"""Shared QuBound pipeline once ``historic_data`` is available.
|
| 270 |
|
| 271 |
+
Pulls the time-series features out of the calibration snapshots,
|
| 272 |
trains the LSTM on noise-aware labels from a Qiskit Aer simulation,
|
| 273 |
+
and returns ``(predicted_error_bound_today, trained_model)``.
|
| 274 |
"""
|
| 275 |
extracted_df = extract_time_series_from_historic(historic_data)
|
| 276 |
trend_df, residual_df = decompose_noise(extracted_df)
|
| 277 |
|
| 278 |
+
combined_df = pd.concat([trend_df, residual_df], axis=1).fillna(0)
|
|
|
|
| 279 |
normalized_df = (combined_df - combined_df.mean()) / combined_df.std()
|
| 280 |
|
| 281 |
+
x_train = create_sequences(normalized_df, window_size=SEQUENCE_WINDOW_SIZE)
|
| 282 |
y_train = get_labels_fromNoise(qc, historic_data, provider)
|
| 283 |
+
y_train = y_train[SEQUENCE_WINDOW_SIZE:].unsqueeze(1)
|
| 284 |
|
| 285 |
model = train_loop(x_train, y_train)
|
| 286 |
final_bound = predict_vqc_bound(model, x_train)
|
| 287 |
return final_bound, model
|
| 288 |
|
| 289 |
|
| 290 |
+
def call_QuBound(
|
| 291 |
+
qc: QuantumCircuit,
|
| 292 |
+
provider: Any,
|
| 293 |
+
token: str,
|
| 294 |
+
date: datetime | None = None,
|
| 295 |
+
) -> tuple[float, QuPred]:
|
| 296 |
"""Run QuBound against the **live** IBM Quantum Platform API.
|
| 297 |
|
| 298 |
+
Fetches ``HISTORY_WINDOW_DAYS`` days of historical noise from
|
| 299 |
+
``ibm_fez`` and trains the LSTM. Slow (live fetch is ~15 s) and
|
| 300 |
+
requires network access plus a valid token.
|
| 301 |
|
| 302 |
Parameters
|
| 303 |
----------
|
| 304 |
qc : QuantumCircuit
|
| 305 |
+
provider : qiskit backend (fake or real) used for transpile + Aer
|
| 306 |
+
noise-model construction during label generation.
|
| 307 |
+
token : IBM Quantum Platform API token.
|
| 308 |
+
date : Reference date; defaults to now.
|
| 309 |
"""
|
| 310 |
if date is None:
|
| 311 |
date = datetime.now()
|
|
|
|
| 319 |
return _train_and_predict(qc, historic_data, provider)
|
| 320 |
|
| 321 |
|
| 322 |
+
def call_QuBound_from_cache(
|
| 323 |
+
qc: QuantumCircuit,
|
| 324 |
+
cached_history_path: str | Path,
|
| 325 |
+
reference_backend: Any = None,
|
| 326 |
+
) -> tuple[float, QuPred, dict[str, Any]]:
|
| 327 |
+
"""Run QuBound against a pickle of pre-fetched 14-day backend
|
| 328 |
+
properties.
|
| 329 |
|
| 330 |
Parameters
|
| 331 |
----------
|
| 332 |
qc : QuantumCircuit
|
| 333 |
+
cached_history_path : Path to the pickle produced by
|
| 334 |
+
``scripts/fetch_ibm_history.py``.
|
| 335 |
+
reference_backend : Backend used for transpile + simulator
|
| 336 |
+
construction. Defaults to ``FakeFez`` (matches the ``ibm_fez``
|
| 337 |
+
calibration in the cache).
|
| 338 |
|
| 339 |
Returns
|
| 340 |
-------
|
| 341 |
+
(predicted_bound, model, metadata) : ``metadata`` is a dict
|
| 342 |
+
describing the cached data source (backend name, fetch date,
|
| 343 |
+
day count, date range).
|
| 344 |
"""
|
|
|
|
|
|
|
| 345 |
with open(cached_history_path, "rb") as fh:
|
| 346 |
payload = pickle.load(fh)
|
| 347 |
|
|
|
|
| 363 |
return bound, model, metadata
|
| 364 |
|
| 365 |
|
| 366 |
+
if __name__ == "__main__":
|
|
|
|
|
|
|
|
|
|
| 367 |
# Minimal CLI entry for ad-hoc testing outside the web app.
|
| 368 |
# Expects two environment variables:
|
| 369 |
# IBM_QUANTUM_TOKEN - IBM Quantum Platform API token
|
| 370 |
# QBOUND_QPY_FILE - path to a .qpy file holding the trained VQC
|
| 371 |
import os
|
| 372 |
|
| 373 |
+
logging.basicConfig(level=logging.INFO)
|
| 374 |
+
|
| 375 |
token = os.environ["IBM_QUANTUM_TOKEN"]
|
| 376 |
qpy_path = os.environ["QBOUND_QPY_FILE"]
|
| 377 |
with open(qpy_path, "rb") as file:
|
| 378 |
qc = qpy.load(file)[0]
|
| 379 |
bound, _model = call_QuBound(qc, FakeFez(), token=token)
|
| 380 |
+
logger.info("Final bound: %s", bound)
|
|
@@ -1,50 +1,39 @@
|
|
| 1 |
-
|
| 2 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
from qiskit import QuantumCircuit
|
| 4 |
-
from qiskit import qasm2, qasm3, qpy
|
| 5 |
-
from qiskit_ibm_runtime.fake_provider import FakeFez, FakeMarrakesh, FakeTorino
|
| 6 |
-
from qiskit import transpile
|
| 7 |
from qiskit.quantum_info import Statevector, state_fidelity
|
| 8 |
|
| 9 |
-
|
| 10 |
-
return qc.draw("mpl")
|
| 11 |
-
|
| 12 |
-
def qasmFile_toCircuit(file):
|
| 13 |
-
"""Load a Qiskit QPY or QASM file-like object into a QuantumCircuit."""
|
| 14 |
-
try:
|
| 15 |
-
if isinstance(file, (bytes, bytearray)):
|
| 16 |
-
file_obj = io.BytesIO(file)
|
| 17 |
-
else:
|
| 18 |
-
file_obj = file
|
| 19 |
-
if hasattr(file_obj, "seek"):
|
| 20 |
-
file_obj.seek(0)
|
| 21 |
-
|
| 22 |
-
qc = qpy.load(file_obj)[0]
|
| 23 |
-
return qc
|
| 24 |
-
except Exception as exc:
|
| 25 |
-
if hasattr(file, "seek"):
|
| 26 |
-
file.seek(0)
|
| 27 |
-
raise RuntimeError(f"Could not load uploaded circuit file: {exc}") from exc
|
| 28 |
-
|
| 29 |
-
def transpile_optim(qc, backend, optim):
|
| 30 |
-
optim_qc = transpile(qc, backend=backend, optimization_level=optim,basis_gates=['sx', 'rz', 'cx', 'id'])
|
| 31 |
-
return optim_qc
|
| 32 |
-
|
| 33 |
-
def simpleFidelityEstimator(qc):
|
| 34 |
-
|
| 35 |
-
# qc = QuantumCircuit(2)
|
| 36 |
-
# qc.h(0)
|
| 37 |
-
# qc.cx(0, 1)
|
| 38 |
-
# print(qc)
|
| 39 |
-
|
| 40 |
-
qc = qc.remove_final_measurements(inplace=False) # remove the measurements since statevector doesnt do measurements
|
| 41 |
-
print(qc)
|
| 42 |
|
| 43 |
-
final_state = Statevector.from_instruction(qc)
|
| 44 |
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 48 |
fidelity = state_fidelity(final_state, target_state)
|
| 49 |
-
|
| 50 |
-
return fidelity
|
|
|
|
| 1 |
+
"""Small Qiskit helpers used by the pipeline.
|
| 2 |
+
|
| 3 |
+
Historically this module collected a handful of utility functions ported
|
| 4 |
+
from Jovin's Streamlit prototype; most of them were superseded by the
|
| 5 |
+
FastAPI service layer (circuit loading lives in
|
| 6 |
+
``app/services/circuit_service.py``, transpilation is inlined at the
|
| 7 |
+
call site, and matplotlib drawing is never used in headless serving).
|
| 8 |
+
|
| 9 |
+
What remains is the one helper still consumed at runtime:
|
| 10 |
+
``simpleFidelityEstimator``, called from
|
| 11 |
+
``workflow_service._handle_fidelity`` to score the output circuit
|
| 12 |
+
against the all-zeros state.
|
| 13 |
+
"""
|
| 14 |
+
|
| 15 |
+
from __future__ import annotations
|
| 16 |
+
|
| 17 |
+
import logging
|
| 18 |
+
|
| 19 |
from qiskit import QuantumCircuit
|
|
|
|
|
|
|
|
|
|
| 20 |
from qiskit.quantum_info import Statevector, state_fidelity
|
| 21 |
|
| 22 |
+
logger = logging.getLogger(__name__)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 23 |
|
|
|
|
| 24 |
|
| 25 |
+
def simpleFidelityEstimator(qc: QuantumCircuit) -> float:
|
| 26 |
+
"""Compute ``<0...0|U|0...0>`` for the given circuit.
|
| 27 |
+
|
| 28 |
+
Strips any final measurements (``Statevector`` can't handle them),
|
| 29 |
+
evolves the all-zeros state through ``qc``, and returns the fidelity
|
| 30 |
+
against ``|0...0>``. Good enough for the demo's "did the circuit
|
| 31 |
+
stay close to its noiseless target" sanity check, though obviously
|
| 32 |
+
not representative of arbitrary target states.
|
| 33 |
+
"""
|
| 34 |
+
qc = qc.remove_final_measurements(inplace=False)
|
| 35 |
+
final_state = Statevector.from_instruction(qc)
|
| 36 |
+
target_state = Statevector.from_label("0" * qc.num_qubits)
|
| 37 |
fidelity = state_fidelity(final_state, target_state)
|
| 38 |
+
logger.debug("simpleFidelityEstimator: fidelity=%.6f", fidelity)
|
| 39 |
+
return float(fidelity)
|
|
@@ -1,33 +1,70 @@
|
|
| 1 |
"""QuCAD implementation (refactored from Jovin Antony Maria's original).
|
| 2 |
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6 |
"""
|
| 7 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
import numpy as np
|
| 9 |
-
from scipy.optimize import minimize
|
| 10 |
from qiskit import qpy, transpile
|
| 11 |
-
from qiskit_aer.primitives import EstimatorV2 as AerEstimator
|
| 12 |
from qiskit.quantum_info import SparsePauliOp
|
| 13 |
from qiskit_aer.noise import NoiseModel
|
|
|
|
| 14 |
from qiskit_ibm_runtime import QiskitRuntimeService
|
| 15 |
-
from
|
| 16 |
from sklearn.cluster import KMeans
|
| 17 |
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
num_qubits = len(props.qubits)
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
qubit_gate_errors = {i: [] for i in range(num_qubits)}
|
| 29 |
for g in props.gates:
|
| 30 |
-
if g.gate in
|
| 31 |
for q_idx in g.qubits:
|
| 32 |
qubit_gate_errors[q_idx].append(g.parameters[0].value)
|
| 33 |
|
|
@@ -37,43 +74,74 @@ def extract_noise_features(props):
|
|
| 37 |
t2 = props.t2(i)
|
| 38 |
avg_cx = np.mean(qubit_gate_errors[i]) if qubit_gate_errors[i] else 0
|
| 39 |
features.append([t1, t2, avg_cx])
|
| 40 |
-
|
| 41 |
return np.array(features)
|
| 42 |
|
| 43 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 44 |
pub = (vqc, observable, theta_values)
|
| 45 |
job = estimator.run([pub])
|
| 46 |
result = job.result()[0]
|
| 47 |
qnn_expectation = result.data.evs
|
| 48 |
-
penalty = (rho / 2) * np.linalg.norm(theta_values - z + u)**2
|
| 49 |
return float(qnn_expectation + penalty)
|
| 50 |
|
| 51 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 52 |
n = vqc.num_parameters
|
| 53 |
theta = np.random.uniform(-np.pi, np.pi, n)
|
| 54 |
z, u = np.zeros(n), np.zeros(n)
|
| 55 |
-
|
| 56 |
noisy_estimator = AerEstimator()
|
| 57 |
noisy_estimator.options.backend_options = {
|
| 58 |
-
"method": "density_matrix",
|
| 59 |
-
"noise_model": noise_model
|
| 60 |
}
|
| 61 |
-
noisy_estimator.options.run_options = {"shots":
|
| 62 |
-
|
| 63 |
observable = SparsePauliOp.from_list([("Z" + "I" * (vqc.num_qubits - 1), 1)])
|
| 64 |
-
history = {"loss": [], "sparsity": []}
|
|
|
|
|
|
|
| 65 |
|
| 66 |
-
print(f"[QuCAD] Training with Noise Profile: {backend_ibm.name}")
|
| 67 |
-
|
| 68 |
for i in range(iterations):
|
| 69 |
res = minimize(
|
| 70 |
-
qucad_loss_noisy,
|
| 71 |
-
theta,
|
| 72 |
args=(vqc, noisy_estimator, observable, z, u, rho),
|
| 73 |
-
method=
|
| 74 |
-
options={
|
| 75 |
)
|
| 76 |
theta = res.x
|
|
|
|
|
|
|
|
|
|
|
|
|
| 77 |
threshold = np.sqrt(2 * lam / rho)
|
| 78 |
temp_z = theta + u
|
| 79 |
z = np.where(np.abs(temp_z) > threshold, temp_z, 0)
|
|
@@ -81,50 +149,66 @@ def run_qucad_training_noisy(vqc, noise_model, backend_ibm, iterations=5, lam=0.
|
|
| 81 |
|
| 82 |
history["loss"].append(res.fun)
|
| 83 |
history["sparsity"].append(np.count_nonzero(z))
|
| 84 |
-
|
| 85 |
|
| 86 |
return theta, z, history
|
| 87 |
|
| 88 |
-
def get_current_noise_multiplier(current_props, baseline_props):
|
| 89 |
-
"""Modified to check global drift against baseline for deployment selection."""
|
| 90 |
-
t1_ratios = [baseline_props.t1(i) / current_props.t1(i) for i in range(len(current_props.qubits))]
|
| 91 |
-
return np.mean(t1_ratios)
|
| 92 |
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 97 |
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 98 |
clusters = lut["clusters"]
|
| 99 |
-
# Simple selection: find centroid closest to current multiplier
|
| 100 |
query = current_multiplier
|
| 101 |
best_dist = float("inf")
|
| 102 |
best_cluster = None
|
| 103 |
|
| 104 |
for c in clusters:
|
| 105 |
-
dist = abs(query - np.mean(c["centroid"]))
|
| 106 |
if dist < best_dist:
|
| 107 |
best_dist = dist
|
| 108 |
best_cluster = c
|
| 109 |
|
| 110 |
-
|
| 111 |
deployed_circuit = vqc.assign_parameters(best_cluster["weights"])
|
| 112 |
-
|
| 113 |
-
# Optimization: Use the best_qubits identified during LUT generation
|
| 114 |
deployed_circuit = transpile(
|
| 115 |
-
deployed_circuit,
|
| 116 |
initial_layout=best_cluster["best_qubits"],
|
| 117 |
-
optimization_level=3
|
| 118 |
)
|
| 119 |
return deployed_circuit
|
| 120 |
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 128 |
all_snapshots = []
|
| 129 |
for day in range(days):
|
| 130 |
cal_date = datetime.now() - timedelta(days=day)
|
|
@@ -132,52 +216,43 @@ def generate_qucad_lut(vqc, backend, days=20, clusters=4):
|
|
| 132 |
if props:
|
| 133 |
all_snapshots.append(extract_noise_features(props))
|
| 134 |
|
| 135 |
-
#
|
| 136 |
-
# Shape: (num_qubits, 3 features)
|
| 137 |
avg_qubit_performance = np.mean(np.array(all_snapshots), axis=0)
|
| 138 |
|
| 139 |
-
|
| 140 |
-
kmeans = KMeans(n_clusters=clusters, random_state=42)
|
| 141 |
qubit_labels = kmeans.fit_predict(avg_qubit_performance)
|
| 142 |
|
| 143 |
-
lut = {"clusters": []}
|
| 144 |
-
|
| 145 |
-
# Generate a model for each "Tier" of qubit quality
|
| 146 |
for c in range(clusters):
|
| 147 |
-
# Identify indices of qubits in this cluster
|
| 148 |
qubit_indices = np.where(qubit_labels == c)[0].tolist()
|
| 149 |
-
|
| 150 |
-
# We need enough qubits in the cluster to run the VQC
|
| 151 |
if len(qubit_indices) < vqc.num_qubits:
|
| 152 |
continue
|
| 153 |
-
|
| 154 |
-
# Select the best subset from this cluster (first N qubits)
|
| 155 |
-
mapping_subset = qubit_indices[:vqc.num_qubits]
|
| 156 |
|
| 157 |
-
|
|
|
|
| 158 |
noise_model = NoiseModel.from_backend(backend)
|
| 159 |
theta_trained, z_mask, _ = run_qucad_training_noisy(
|
| 160 |
-
vqc, noise_model, backend, iterations=
|
| 161 |
)
|
| 162 |
|
| 163 |
-
lut["clusters"].append(
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
|
|
|
| 170 |
|
| 171 |
return lut
|
| 172 |
|
| 173 |
-
def get_noiseModel_andBackend_ondate(token, date_time=None):
|
| 174 |
-
"""Fetch noise model + backend handle for a given calibration date.
|
| 175 |
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
"""
|
| 181 |
if date_time is None:
|
| 182 |
date_time = datetime.now()
|
| 183 |
service = QiskitRuntimeService(
|
|
@@ -198,6 +273,8 @@ if __name__ == "__main__":
|
|
| 198 |
# QUCAD_QPY_FILE - path to a .qpy file holding the VQC
|
| 199 |
import os
|
| 200 |
|
|
|
|
|
|
|
| 201 |
token = os.environ["IBM_QUANTUM_TOKEN"]
|
| 202 |
qpy_path = os.environ["QUCAD_QPY_FILE"]
|
| 203 |
|
|
@@ -217,16 +294,19 @@ if __name__ == "__main__":
|
|
| 217 |
|
| 218 |
robust_theta = final_theta * (final_mask != 0)
|
| 219 |
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
|
| 224 |
bound_vqc = vqc.assign_parameters(robust_theta)
|
| 225 |
robust_vqc_compressed = transpile(bound_vqc, optimization_level=3)
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
|
|
|
|
|
|
|
|
|
|
| 230 |
|
| 231 |
qucad_bank = generate_qucad_lut(vqc, backend_ibm)
|
| 232 |
-
|
|
|
|
| 1 |
"""QuCAD implementation (refactored from Jovin Antony Maria's original).
|
| 2 |
|
| 3 |
+
Algorithm overview: train a VQC's parameters with an ADMM-style
|
| 4 |
+
soft-thresholding step that pushes near-zero weights exactly to zero
|
| 5 |
+
— producing a compact mask of "useful" parameters. Together with
|
| 6 |
+
per-qubit noise features and K-means clustering, this gives a look-up
|
| 7 |
+
table that selects the best qubit mapping for deployment on a drifting
|
| 8 |
+
device.
|
| 9 |
+
|
| 10 |
+
The only entry point used by the web app is
|
| 11 |
+
:func:`run_qucad_training_noisy`. The LUT + deployment functions are
|
| 12 |
+
retained for parity with the original CLI pipeline but are not wired
|
| 13 |
+
into the FastAPI service.
|
| 14 |
"""
|
| 15 |
|
| 16 |
+
from __future__ import annotations
|
| 17 |
+
|
| 18 |
+
import logging
|
| 19 |
+
from datetime import datetime, timedelta
|
| 20 |
+
from typing import Any
|
| 21 |
+
|
| 22 |
import numpy as np
|
|
|
|
| 23 |
from qiskit import qpy, transpile
|
|
|
|
| 24 |
from qiskit.quantum_info import SparsePauliOp
|
| 25 |
from qiskit_aer.noise import NoiseModel
|
| 26 |
+
from qiskit_aer.primitives import EstimatorV2 as AerEstimator
|
| 27 |
from qiskit_ibm_runtime import QiskitRuntimeService
|
| 28 |
+
from scipy.optimize import minimize
|
| 29 |
from sklearn.cluster import KMeans
|
| 30 |
|
| 31 |
+
logger = logging.getLogger(__name__)
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
# ---- Hyperparameters ---------------------------------------------------
|
| 35 |
+
|
| 36 |
+
TWO_QUBIT_GATES: tuple[str, ...] = ("cx", "ecr", "cz")
|
| 37 |
+
"""Gate names we treat as "the" two-qubit error source per qubit."""
|
| 38 |
+
|
| 39 |
+
SHOTS_PER_EVAL = 1024
|
| 40 |
+
"""Aer shots used per ADMM objective evaluation."""
|
| 41 |
+
|
| 42 |
+
QUCAD_DEFAULT_ITERATIONS = 5
|
| 43 |
+
QUCAD_DEFAULT_LAM = 0.01
|
| 44 |
+
QUCAD_DEFAULT_RHO = 500.0
|
| 45 |
+
"""ADMM hyperparameters: ``lam`` is the ℓ1 weight, ``rho`` the quadratic
|
| 46 |
+
penalty coefficient. Defaults match Jovin's original Streamlit config."""
|
| 47 |
+
|
| 48 |
+
COBYLA_MAXITER = 20
|
| 49 |
+
"""Inner-loop COBYLA iterations per ADMM outer iteration."""
|
| 50 |
+
|
| 51 |
+
LUT_DEFAULT_DAYS = 20
|
| 52 |
+
LUT_DEFAULT_CLUSTERS = 4
|
| 53 |
+
KMEANS_RANDOM_STATE = 42
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
# ---- Feature extraction ------------------------------------------------
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def extract_noise_features(props: Any) -> np.ndarray:
|
| 60 |
+
"""Per-qubit noise features as a ``(num_qubits, 3)`` matrix of
|
| 61 |
+
``[T1, T2, avg_two_qubit_gate_error]``."""
|
| 62 |
num_qubits = len(props.qubits)
|
| 63 |
+
|
| 64 |
+
# Aggregate two-qubit gate errors back onto each participating qubit.
|
| 65 |
+
qubit_gate_errors: dict[int, list[float]] = {i: [] for i in range(num_qubits)}
|
|
|
|
| 66 |
for g in props.gates:
|
| 67 |
+
if g.gate in TWO_QUBIT_GATES:
|
| 68 |
for q_idx in g.qubits:
|
| 69 |
qubit_gate_errors[q_idx].append(g.parameters[0].value)
|
| 70 |
|
|
|
|
| 74 |
t2 = props.t2(i)
|
| 75 |
avg_cx = np.mean(qubit_gate_errors[i]) if qubit_gate_errors[i] else 0
|
| 76 |
features.append([t1, t2, avg_cx])
|
| 77 |
+
|
| 78 |
return np.array(features)
|
| 79 |
|
| 80 |
+
|
| 81 |
+
# ---- ADMM training -----------------------------------------------------
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def qucad_loss_noisy(
|
| 85 |
+
theta_values: np.ndarray,
|
| 86 |
+
vqc: Any,
|
| 87 |
+
estimator: AerEstimator,
|
| 88 |
+
observable: SparsePauliOp,
|
| 89 |
+
z: np.ndarray,
|
| 90 |
+
u: np.ndarray,
|
| 91 |
+
rho: float,
|
| 92 |
+
) -> float:
|
| 93 |
+
"""ADMM inner objective: noisy expectation value of ``observable``
|
| 94 |
+
plus a quadratic proximal penalty ``(rho/2) * ||theta - z + u||^2``
|
| 95 |
+
pulling ``theta`` towards the current consensus ``z``."""
|
| 96 |
pub = (vqc, observable, theta_values)
|
| 97 |
job = estimator.run([pub])
|
| 98 |
result = job.result()[0]
|
| 99 |
qnn_expectation = result.data.evs
|
| 100 |
+
penalty = (rho / 2) * np.linalg.norm(theta_values - z + u) ** 2
|
| 101 |
return float(qnn_expectation + penalty)
|
| 102 |
|
| 103 |
+
|
| 104 |
+
def run_qucad_training_noisy(
|
| 105 |
+
vqc: Any,
|
| 106 |
+
noise_model: NoiseModel,
|
| 107 |
+
backend_ibm: Any,
|
| 108 |
+
iterations: int = QUCAD_DEFAULT_ITERATIONS,
|
| 109 |
+
lam: float = QUCAD_DEFAULT_LAM,
|
| 110 |
+
rho: float = QUCAD_DEFAULT_RHO,
|
| 111 |
+
) -> tuple[np.ndarray, np.ndarray, dict[str, list]]:
|
| 112 |
+
"""ADMM training with soft-thresholding. Returns the final
|
| 113 |
+
``(theta, mask, history)`` where ``mask`` (= ``z`` in ADMM) has the
|
| 114 |
+
same shape as ``theta`` but with near-zero entries zeroed out; the
|
| 115 |
+
non-zero positions represent the "kept" parameters."""
|
| 116 |
n = vqc.num_parameters
|
| 117 |
theta = np.random.uniform(-np.pi, np.pi, n)
|
| 118 |
z, u = np.zeros(n), np.zeros(n)
|
| 119 |
+
|
| 120 |
noisy_estimator = AerEstimator()
|
| 121 |
noisy_estimator.options.backend_options = {
|
| 122 |
+
"method": "density_matrix",
|
| 123 |
+
"noise_model": noise_model,
|
| 124 |
}
|
| 125 |
+
noisy_estimator.options.run_options = {"shots": SHOTS_PER_EVAL}
|
| 126 |
+
|
| 127 |
observable = SparsePauliOp.from_list([("Z" + "I" * (vqc.num_qubits - 1), 1)])
|
| 128 |
+
history: dict[str, list] = {"loss": [], "sparsity": []}
|
| 129 |
+
|
| 130 |
+
logger.info("[QuCAD] Training with noise profile: %s", backend_ibm.name)
|
| 131 |
|
|
|
|
|
|
|
| 132 |
for i in range(iterations):
|
| 133 |
res = minimize(
|
| 134 |
+
qucad_loss_noisy,
|
| 135 |
+
theta,
|
| 136 |
args=(vqc, noisy_estimator, observable, z, u, rho),
|
| 137 |
+
method="COBYLA",
|
| 138 |
+
options={"maxiter": COBYLA_MAXITER},
|
| 139 |
)
|
| 140 |
theta = res.x
|
| 141 |
+
|
| 142 |
+
# Soft-threshold step: anything with magnitude under
|
| 143 |
+
# sqrt(2*lam/rho) gets pushed to zero (the ℓ1 prox operator
|
| 144 |
+
# under the ADMM quadratic).
|
| 145 |
threshold = np.sqrt(2 * lam / rho)
|
| 146 |
temp_z = theta + u
|
| 147 |
z = np.where(np.abs(temp_z) > threshold, temp_z, 0)
|
|
|
|
| 149 |
|
| 150 |
history["loss"].append(res.fun)
|
| 151 |
history["sparsity"].append(np.count_nonzero(z))
|
| 152 |
+
logger.info("Iter %d | cost=%.4f | nonzeros=%d", i, res.fun, np.count_nonzero(z))
|
| 153 |
|
| 154 |
return theta, z, history
|
| 155 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 156 |
|
| 157 |
+
# ---- Deployment / LUT (CLI-only; not consumed by web app) --------------
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
def get_current_noise_multiplier(current_props: Any, baseline_props: Any) -> float:
|
| 161 |
+
"""Ratio of baseline T1 to current T1 averaged over all qubits —
|
| 162 |
+
a coarse "how much has the device drifted" signal used to pick
|
| 163 |
+
which LUT cluster to deploy.
|
| 164 |
+
|
| 165 |
+
Kept for parity with the original CLI pipeline; not called by the
|
| 166 |
+
web service layer.
|
| 167 |
"""
|
| 168 |
+
t1_ratios = [
|
| 169 |
+
baseline_props.t1(i) / current_props.t1(i)
|
| 170 |
+
for i in range(len(current_props.qubits))
|
| 171 |
+
]
|
| 172 |
+
return float(np.mean(t1_ratios))
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
def deploy_qucad_model(vqc: Any, lut: dict[str, Any], current_multiplier: float) -> Any:
|
| 176 |
+
"""Pick the LUT cluster whose centroid is closest to the current
|
| 177 |
+
drift multiplier and compile the VQC against that cluster's best
|
| 178 |
+
qubits."""
|
| 179 |
clusters = lut["clusters"]
|
|
|
|
| 180 |
query = current_multiplier
|
| 181 |
best_dist = float("inf")
|
| 182 |
best_cluster = None
|
| 183 |
|
| 184 |
for c in clusters:
|
| 185 |
+
dist = abs(query - np.mean(c["centroid"]))
|
| 186 |
if dist < best_dist:
|
| 187 |
best_dist = dist
|
| 188 |
best_cluster = c
|
| 189 |
|
| 190 |
+
logger.info("[QuCAD] Deploying model using qubit-cluster mapping")
|
| 191 |
deployed_circuit = vqc.assign_parameters(best_cluster["weights"])
|
|
|
|
|
|
|
| 192 |
deployed_circuit = transpile(
|
| 193 |
+
deployed_circuit,
|
| 194 |
initial_layout=best_cluster["best_qubits"],
|
| 195 |
+
optimization_level=3,
|
| 196 |
)
|
| 197 |
return deployed_circuit
|
| 198 |
|
| 199 |
+
|
| 200 |
+
def generate_qucad_lut(
|
| 201 |
+
vqc: Any,
|
| 202 |
+
backend: Any,
|
| 203 |
+
days: int = LUT_DEFAULT_DAYS,
|
| 204 |
+
clusters: int = LUT_DEFAULT_CLUSTERS,
|
| 205 |
+
) -> dict[str, Any]:
|
| 206 |
+
"""Aggregate per-qubit noise features over ``days`` of calibration
|
| 207 |
+
snapshots, cluster qubits into quality tiers via K-means, and train
|
| 208 |
+
one QuCAD model per tier. Returns a LUT mapping tier → (centroid,
|
| 209 |
+
trained weights, best qubit layout)."""
|
| 210 |
+
logger.info("[QuCAD] Analyzing qubit reliability over %d days", days)
|
| 211 |
+
|
| 212 |
all_snapshots = []
|
| 213 |
for day in range(days):
|
| 214 |
cal_date = datetime.now() - timedelta(days=day)
|
|
|
|
| 216 |
if props:
|
| 217 |
all_snapshots.append(extract_noise_features(props))
|
| 218 |
|
| 219 |
+
# Shape: (num_qubits, 3 features), averaged across time.
|
|
|
|
| 220 |
avg_qubit_performance = np.mean(np.array(all_snapshots), axis=0)
|
| 221 |
|
| 222 |
+
kmeans = KMeans(n_clusters=clusters, random_state=KMEANS_RANDOM_STATE)
|
|
|
|
| 223 |
qubit_labels = kmeans.fit_predict(avg_qubit_performance)
|
| 224 |
|
| 225 |
+
lut: dict[str, Any] = {"clusters": []}
|
| 226 |
+
|
|
|
|
| 227 |
for c in range(clusters):
|
|
|
|
| 228 |
qubit_indices = np.where(qubit_labels == c)[0].tolist()
|
|
|
|
|
|
|
| 229 |
if len(qubit_indices) < vqc.num_qubits:
|
| 230 |
continue
|
|
|
|
|
|
|
|
|
|
| 231 |
|
| 232 |
+
mapping_subset = qubit_indices[: vqc.num_qubits]
|
| 233 |
+
|
| 234 |
noise_model = NoiseModel.from_backend(backend)
|
| 235 |
theta_trained, z_mask, _ = run_qucad_training_noisy(
|
| 236 |
+
vqc, noise_model, backend, iterations=QUCAD_DEFAULT_ITERATIONS
|
| 237 |
)
|
| 238 |
|
| 239 |
+
lut["clusters"].append(
|
| 240 |
+
{
|
| 241 |
+
"centroid": kmeans.cluster_centers_[c],
|
| 242 |
+
"weights": theta_trained * (z_mask != 0),
|
| 243 |
+
"best_qubits": mapping_subset,
|
| 244 |
+
}
|
| 245 |
+
)
|
| 246 |
+
logger.info("Cluster %d: %d qubits grouped; mapping assigned", c, len(qubit_indices))
|
| 247 |
|
| 248 |
return lut
|
| 249 |
|
|
|
|
|
|
|
| 250 |
|
| 251 |
+
def get_noiseModel_andBackend_ondate(
|
| 252 |
+
token: str, date_time: datetime | None = None
|
| 253 |
+
) -> tuple[NoiseModel, Any, Any]:
|
| 254 |
+
"""Fetch ``(noise_model, backend, target_props)`` for a given
|
| 255 |
+
calibration date. Requires a live IBM Quantum Platform token."""
|
| 256 |
if date_time is None:
|
| 257 |
date_time = datetime.now()
|
| 258 |
service = QiskitRuntimeService(
|
|
|
|
| 273 |
# QUCAD_QPY_FILE - path to a .qpy file holding the VQC
|
| 274 |
import os
|
| 275 |
|
| 276 |
+
logging.basicConfig(level=logging.INFO)
|
| 277 |
+
|
| 278 |
token = os.environ["IBM_QUANTUM_TOKEN"]
|
| 279 |
qpy_path = os.environ["QUCAD_QPY_FILE"]
|
| 280 |
|
|
|
|
| 294 |
|
| 295 |
robust_theta = final_theta * (final_mask != 0)
|
| 296 |
|
| 297 |
+
logger.info("--- Summary ---")
|
| 298 |
+
logger.info("Original parameters: %d", num_params)
|
| 299 |
+
logger.info("Compressed parameters: %d", int(np.count_nonzero(final_mask)))
|
| 300 |
|
| 301 |
bound_vqc = vqc.assign_parameters(robust_theta)
|
| 302 |
robust_vqc_compressed = transpile(bound_vqc, optimization_level=3)
|
| 303 |
+
logger.info("--- QuCAD compression results ---")
|
| 304 |
+
logger.info("Original depth: %d", vqc.depth())
|
| 305 |
+
logger.info("Robust depth: %d", robust_vqc_compressed.depth())
|
| 306 |
+
logger.info(
|
| 307 |
+
"Gate reduction: %d gates removed",
|
| 308 |
+
vqc.size() - robust_vqc_compressed.size(),
|
| 309 |
+
)
|
| 310 |
|
| 311 |
qucad_bank = generate_qucad_lut(vqc, backend_ibm)
|
| 312 |
+
logger.info("LUT: %s", qucad_bank)
|