Skip to content

Implements optimizations A.1 and A.2 for Quantum Shannon Decomposition #7390

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 6 commits into
base: main
Choose a base branch
from

Conversation

codrut3
Copy link
Contributor

@codrut3 codrut3 commented May 29, 2025

Fixes #6777

I checked that with the current PR, the circuit depth after transpiler matches that obtained by Qiskit.

The runtime is slow due merge_single_qubit_gates_to_phased_x_and_z. I wrote a different implementation for the special case used by the Shannon decomposition. With this, the runtime is halved. I believe merge_single_qubit_gates_to_phased_x_and_z can be optimized too.

@codrut3 codrut3 requested review from vtomole and a team as code owners May 29, 2025 21:56
@codrut3 codrut3 requested a review from tanujkhattar May 29, 2025 21:56
@github-actions github-actions bot added the size: L 250< lines changed <1000 label May 29, 2025
@codrut3
Copy link
Contributor Author

codrut3 commented May 29, 2025

@NoureldinYosri Please have a look!

@codrut3
Copy link
Contributor Author

codrut3 commented May 29, 2025

For future reference, this is the script I used to benchmark the decomposition:

# pylint: disable=wrong-or-nonexistent-copyright-notice
"""Tests performance of quantum Shannon decomposition.
"""

import sys
import time

from scipy.stats import unitary_group

import cirq
import qiskit.qasm2


if not sys.warnoptions:
    import warnings
    warnings.simplefilter("ignore")


def main():
    for n_qubits in range(3, 9):
        U = unitary_group.rvs(2**n_qubits)
        qubits = [cirq.NamedQubit(f'q{i}') for i in range(n_qubits)]
        start_time = time.time()
        circuit = cirq.Circuit(cirq.quantum_shannon_decomposition(qubits, U))
        elapsed_time = time.time() - start_time
        print(f'Depth for {n_qubits} qubits (no transpiler): {len(circuit)} ({elapsed_time:.2f} sec)')
        print(f'Number of CZ gates (no transpiler): {len(list(circuit.findall_operations_with_gate_type(cirq.CZPowGate)))}')
        print(f'Number of CNOT gates (no transpiler): {len(list(circuit.findall_operations_with_gate_type(cirq.CXPowGate)))}')


        # Export to qasm
        qasm_str = cirq.qasm(circuit, args=cirq.QasmArgs(version="2.0"))
        qiskit_circuit = qiskit.qasm2.loads(qasm_str, include_path=('.',), custom_instructions=qiskit.qasm2.LEGACY_CUSTOM_INSTRUCTIONS, custom_classical=(), strict=False)

        # Run qiskit transpiler
        start_time = time.time()
        opt_circuit = qiskit.compiler.transpile(qiskit_circuit, basis_gates=["cz", "u3"], optimization_level=3)
        elapsed_time = time.time() - start_time
        print(f'Qiskit depth for {n_qubits} qubits (with transpiler): {opt_circuit.depth()} ({elapsed_time:.2f} sec)')
        print(f'Qiskit gate counts for {n_qubits} qubits (with transpiler): {dict(opt_circuit.count_ops())}')

        # Run cirq transpiler
        start_time = time.time()
        circuit = cirq.optimize_for_target_gateset(circuit, gateset=cirq.CZTargetGateset(preserve_moment_structure=False), max_num_passes=None)
        elapsed_time = time.time() - start_time
        print(f'Cirq depth for {n_qubits} qubits (with transpiler): {len(circuit)} ({elapsed_time:.2f} sec)')
        # Count the operations
        operation_counts = {}
        for op in circuit.all_operations():
            gate_type = op.gate.__class__
            if isinstance(op.gate, cirq.CZPowGate):
                gate_type = 'cz'
            elif isinstance(op.gate, cirq.PhasedXZGate):
                gate_type = 'u3'
            if gate_type not in operation_counts:
                operation_counts[gate_type] = 0
            operation_counts[gate_type] += 1
        print(f'Cirq gate counts for {n_qubits} qubits (with transpiler): {operation_counts}')


if __name__ == '__main__':
    main()
Copy link

codecov bot commented May 29, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 98.68%. Comparing base (12eab31) to head (b31d996).
Report is 1 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main    #7390   +/-   ##
=======================================
  Coverage   98.68%   98.68%           
=======================================
  Files        1112     1112           
  Lines       97642    97703   +61     
=======================================
+ Hits        96359    96421   +62     
+ Misses       1283     1282    -1     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.
@NoureldinYosri NoureldinYosri requested review from NoureldinYosri and removed request for tanujkhattar May 30, 2025 00:13
@NoureldinYosri NoureldinYosri self-assigned this May 30, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
size: L 250< lines changed <1000
2 participants