Skip to content

memq_dqc.verify

verify

Verification helpers for memq_dqc outputs.

dist_to_mono_circuit

dist_to_mono_circuit(dist_circuit_path: str) -> str

Convert a distributed circuit to an executable monolithic circuit.

Takes a distributed circuit and rewrites it into an equivalent, locally-executable form by:

  • replacing remote operations with their local equivalents (rcx -> cx, rcp -> cp, rcry -> cry, rcz -> cz, rswap -> swap), keeping only the two data-qubit operands;
  • dropping the cat-entanglement scaffolding (catent / catdisent) that wraps remote operations, since the local equivalents need no shared entanglement;
  • removing communication-qubit (c*) declarations and any remaining gates that act on communication qubits;
  • dropping the custom distgates.inc include, which is no longer referenced once remote operations are removed.

Parameters:

Name Type Description Default
dist_circuit_path str

Path to the distributed circuit file.

required

Returns:

Type Description
str

A qasm string representing the monolithic version of the distributed

str

circuit.

Source code in src/memq_dqc/verify/verify.py
def dist_to_mono_circuit(dist_circuit_path: str) -> str:
    """Convert a distributed circuit to an executable monolithic circuit.

    Takes a distributed circuit and rewrites it into an equivalent,
    locally-executable form by:

    - replacing remote operations with their local equivalents (``rcx`` ->
      ``cx``, ``rcp`` -> ``cp``, ``rcry`` -> ``cry``, ``rcz`` -> ``cz``,
      ``rswap`` -> ``swap``), keeping only the two data-qubit operands;
    - dropping the cat-entanglement scaffolding (``catent`` / ``catdisent``)
      that wraps remote operations, since the local equivalents need no
      shared entanglement;
    - removing communication-qubit (``c*``) declarations and any remaining
      gates that act on communication qubits;
    - dropping the custom ``distgates.inc`` include, which is no longer
      referenced once remote operations are removed.

    Args:
        dist_circuit_path: Path to the distributed circuit file.

    Returns:
        A qasm string representing the monolithic version of the distributed
        circuit.
    """
    dist_prog = parse_qasm_file(dist_circuit_path)
    return dump_qasm_program(dist_to_mono_program(dist_prog))

dist_to_mono_program

dist_to_mono_program(dist_program: Program) -> Program

Rewrite a distributed program into a monolithic program.

Performs the same rewrite as dist_to_mono_circuit but operates on an in-memory program rather than a file, so no serialization round-trip is required. See dist_to_mono_circuit for the full list of transformations applied.

Parameters:

Name Type Description Default
dist_program Program

Parsed distributed OpenQASM 3 program.

required

Returns:

Type Description
Program

An equivalent monolithic OpenQASM 3 program with remote

Program

operations replaced by their local equivalents.

Source code in src/memq_dqc/verify/verify.py
def dist_to_mono_program(dist_program: ast.Program) -> ast.Program:
    """Rewrite a distributed program into a monolithic program.

    Performs the same rewrite as [dist_to_mono_circuit][memq_dqc.verify.verify.dist_to_mono_circuit] but operates
    on an in-memory program rather than a file, so no serialization
    round-trip is required. See [dist_to_mono_circuit][memq_dqc.verify.verify.dist_to_mono_circuit] for the full
    list of transformations applied.

    Args:
        dist_program: Parsed distributed OpenQASM 3 program.

    Returns:
        An equivalent monolithic OpenQASM 3 program with remote
        operations replaced by their local equivalents.
    """
    new_statements = []
    # iterate through program statements and remove remote gates
    for stmt in dist_program.statements:
        if not isinstance(stmt, ast.Statement):
            new_statements.append(stmt)
            continue
        # Remove custom library includes
        if isinstance(stmt, ast.Include):
            included_file = stmt.filename
            if "distgates.inc" in included_file:
                continue
        if is_comm_qubit_declaration(stmt):
            continue
        # Replace remote gates with local equivalents
        if isinstance(stmt, ast.QuantumGate):
            # replace RCX w/ CX
            name = stmt.name.name
            if name == "rcx":
                stmt = rename_quantum_gate(stmt, "cx")
                stmt.qubits = non_comm_qubits(stmt.qubits)[:2]
            elif name == "rcp":
                stmt = rename_quantum_gate(stmt, "cp")
                stmt.qubits = non_comm_qubits(stmt.qubits)[:2]
            elif name == "rcry":
                stmt = rename_quantum_gate(stmt, "cry")
                stmt.qubits = non_comm_qubits(stmt.qubits)[:2]
            elif name == "rcz":
                stmt = rename_quantum_gate(stmt, "cz")
                stmt.qubits = non_comm_qubits(stmt.qubits)[:2]
            # replace RSWAP w/ SWAP
            elif name == "rswap":
                stmt = rename_quantum_gate(stmt, "swap")
                stmt.qubits = non_comm_qubits(stmt.qubits)[:2]
            # drop cat-entanglement scaffolding around remote operations
            elif name in ("catent", "catdisent"):
                continue
            elif any(is_comm_qubit_reference(qubit) for qubit in stmt.qubits):
                continue
            if any(
                annotation.keyword == CAT_PROXY_X_ANNOTATION
                for annotation in stmt.annotations
            ):
                # This verifier intentionally removes the cat protocol. The
                # deferred proxy action goes with it; preserve the data gate.
                stmt = clone_statement_node(stmt)
                stmt.annotations = [
                    annotation
                    for annotation in stmt.annotations
                    if annotation.keyword != CAT_PROXY_X_ANNOTATION
                ]
        new_statements.append(stmt)
    return ast.Program(version=dist_program.version, statements=new_statements)

manual_cost_verification

manual_cost_verification(qasm: str) -> int

Return the total manual cost of remote operations in a QASM string.

Costs are in e-bit pairs

rswap costs REMOTE_SWAP_EBIT_COST (two teleportations). rcp, rcry, rcx, and rcz each cost REMOTE_GATE_EBIT_COST.

Parameters:

Name Type Description Default
qasm str

OpenQASM source code to analyze.

required

Returns:

Type Description
int

Sum of remote operation costs.

Source code in src/memq_dqc/verify/verify.py
def manual_cost_verification(qasm: str) -> int:
    """Return the total manual cost of remote operations in a QASM string.

    Costs are in e-bit pairs:
        ``rswap`` costs `REMOTE_SWAP_EBIT_COST` (two teleportations).
        ``rcp``, ``rcry``, ``rcx``, and ``rcz`` each cost
        `REMOTE_GATE_EBIT_COST`.

    Args:
        qasm: OpenQASM source code to analyze.

    Returns:
        Sum of remote operation costs.
    """
    program = parse_qasm_source(qasm)
    total_cost = 0

    for statement in program.statements:
        if not isinstance(statement, ast.QuantumGate):
            continue
        total_cost += _REMOTE_OPERATION_COSTS.get(statement.name.name, 0)

    return total_cost

verify_distributed_circuit

verify_distributed_circuit(
    original: Program | str,
    distributed: Program | str,
    *,
    method: Literal["sampling", "statevector"] = "sampling",
    shots: int = 50000000,
    fidelity_threshold: float = 0.9,
    max_qubits: int = 28,
    atol: float = 1e-09,
    verbosity: Literal["quiet", "info", "debug"] = "quiet",
) -> bool

Verify the correctness of a distributed circuit.

Evaluates the distributed circuit as a single, monolithic circuit where remote operations are assumed to operate perfectly, then compares it to the original circuit using the chosen method:

  • "sampling" simulates both circuits for shots shots and compares their measured output distributions via Hellinger fidelity. This is an approximate, stochastic check whose accuracy depends on the shot count.
  • "statevector" computes each circuit's exact output distribution from its statevector (no shots) for circuits with final measurements and checks that they match within atol. The comparison is mapped through each circuit's own measurement-to-classical-bit mapping, so it is invariant to how data qubits are laid out or relabeled across QPUs. It preserves the full classical output width, including unwritten bits. This is deterministic and exact, but memory grows as 2**n in the qubit count n.

Parameters:

Name Type Description Default
original Program | str

The original circuit, either as a parsed OpenQASM 3 program or a path to its .qasm file.

required
distributed Program | str

The distributed circuit, either as a parsed OpenQASM 3 program or a path to its .qasm file.

required
method Literal['sampling', 'statevector']

Verification method, either "sampling" (default) or "statevector".

'sampling'
shots int

Number of shots to execute the circuits for. Used only by the "sampling" method.

50000000
fidelity_threshold float

The minimum Hellinger fidelity required for the distributed circuit to be considered correct. Used only by the "sampling" method.

0.9
max_qubits int

Maximum circuit width the "statevector" method will attempt before raising, to avoid exhausting memory. Used only by the "statevector" method.

28
atol float

Maximum total-variation distance between the exact output distributions for the circuits to be considered equivalent. Used only by the "statevector" method.

1e-09
verbosity Literal['quiet', 'info', 'debug']

Logging verbosity for this workflow call.

'quiet'

Returns:

Type Description
bool

True if the distributed circuit reproduces the original circuit's

bool

output distribution under the chosen method, False otherwise.

Raises:

Type Description
ValueError

If method is not "sampling" or "statevector", or if the "statevector" method is used on a circuit wider than max_qubits or without measurements.

Source code in src/memq_dqc/verify/verify.py
def verify_distributed_circuit(
    original: ast.Program | str,
    distributed: ast.Program | str,
    *,
    method: Literal["sampling", "statevector"] = "sampling",
    shots: int = 50000000,
    fidelity_threshold: float = 0.90,
    max_qubits: int = 28,
    atol: float = 1e-9,
    verbosity: Literal["quiet", "info", "debug"] = "quiet",
) -> bool:
    """Verify the correctness of a distributed circuit.

    Evaluates the distributed circuit as a single, monolithic circuit where
    remote operations are assumed to operate perfectly, then compares it to
    the original circuit using the chosen ``method``:

    - ``"sampling"`` simulates both circuits for ``shots`` shots and compares
      their measured output distributions via Hellinger fidelity. This is an
      approximate, stochastic check whose accuracy depends on the shot count.
    - ``"statevector"`` computes each circuit's exact output distribution from
      its statevector (no shots) for circuits with final measurements and
      checks that they match within ``atol``.
      The comparison is mapped through each circuit's own
      measurement-to-classical-bit mapping, so it is invariant to how data
      qubits are laid out or relabeled across QPUs. It preserves the full
      classical output width, including unwritten bits. This is deterministic
      and exact, but memory grows as ``2**n`` in the qubit count ``n``.

    Args:
        original: The original circuit, either as a parsed OpenQASM 3
            program or a path to its ``.qasm`` file.
        distributed: The distributed circuit, either as a parsed
            OpenQASM 3 program or a path to its ``.qasm`` file.
        method: Verification method, either ``"sampling"`` (default) or
            ``"statevector"``.
        shots: Number of shots to execute the circuits for. Used only by the
            ``"sampling"`` method.
        fidelity_threshold: The minimum Hellinger fidelity required for the
            distributed circuit to be considered correct. Used only by the
            ``"sampling"`` method.
        max_qubits: Maximum circuit width the ``"statevector"`` method will
            attempt before raising, to avoid exhausting memory. Used only by
            the ``"statevector"`` method.
        atol: Maximum total-variation distance between the exact output
            distributions for the circuits to be considered equivalent. Used
            only by the ``"statevector"`` method.
        verbosity: Logging verbosity for this workflow call.

    Returns:
        True if the distributed circuit reproduces the original circuit's
        output distribution under the chosen method, False otherwise.

    Raises:
        ValueError: If ``method`` is not ``"sampling"`` or ``"statevector"``,
            or if the ``"statevector"`` method is used on a circuit wider than
            ``max_qubits`` or without measurements.
    """
    with workflow_logging(verbosity):
        if method not in ("sampling", "statevector"):
            raise ValueError(
                f"Unsupported method {method!r}; expected 'sampling' or "
                "'statevector'."
            )

        overall_timer = StepTimer()
        if method == "sampling":
            logger.info(
                "Starting distributed circuit verification: method=sampling "
                "shots=%d fidelity_threshold=%.3f.",
                shots,
                fidelity_threshold,
            )
        else:
            logger.info(
                "Starting distributed circuit verification: "
                "method=statevector max_qubits=%d atol=%.1e.",
                max_qubits,
                atol,
            )

        original_load_timer = StepTimer()
        if isinstance(original, ast.Program):
            qc_orig = qiskit.qasm3.loads(dump_qasm_program(original))
        else:
            qc_orig = qiskit.qasm3.load(original)
        logger.debug(
            "Loaded original circuit in %.3fs.",
            original_load_timer.elapsed_seconds(),
        )

        mono_timer = StepTimer()
        if isinstance(distributed, ast.Program):
            mono_qasm = dump_qasm_program(dist_to_mono_program(distributed))
        else:
            mono_qasm = dist_to_mono_circuit(distributed)
        qc_dist_mono = qiskit.qasm3.loads(str(mono_qasm))
        logger.debug(
            "Converted distributed circuit to monolithic form in %.3fs.",
            mono_timer.elapsed_seconds(),
        )

        if method == "sampling":
            return _verify_by_sampling(
                qc_orig,
                qc_dist_mono,
                shots=shots,
                fidelity_threshold=fidelity_threshold,
                overall_timer=overall_timer,
            )
        return _verify_by_statevector(
            qc_orig,
            qc_dist_mono,
            max_qubits=max_qubits,
            atol=atol,
            overall_timer=overall_timer,
        )