diff --git a/qiskit/circuit/commutation_checker.py b/qiskit/circuit/commutation_checker.py index cb3e40685bee..2a809bf7e348 100644 --- a/qiskit/circuit/commutation_checker.py +++ b/qiskit/circuit/commutation_checker.py @@ -144,7 +144,7 @@ def commute( # being the lowest possible indices so the identity can be tensored before it. extra_qarg2 = num_qubits - len(qarg1) if extra_qarg2: - id_op = _identity_op(2**extra_qarg2) + id_op = _identity_op(extra_qarg2) operator_1 = id_op.tensor(operator_1) op12 = operator_1.compose(operator_2, qargs=qarg2, front=False) op21 = operator_1.compose(operator_2, qargs=qarg2, front=True) diff --git a/releasenotes/notes/fix-memory-commutation-checker-dbb441de68706b6f.yaml b/releasenotes/notes/fix-memory-commutation-checker-dbb441de68706b6f.yaml new file mode 100644 index 000000000000..dee3704aae08 --- /dev/null +++ b/releasenotes/notes/fix-memory-commutation-checker-dbb441de68706b6f.yaml @@ -0,0 +1,9 @@ +--- +fixes: + - | + Fixed an issue with the :class:`~.CommutationChecker` class where it would + attempt to internally allocate an array for :math:`2^{n}` qubits when it + only needed an array to represent :math:`n` qubits. This could cause + an excessive amount of memory for wide gates, for example a 4 qubit + gate would require 32 gigabytes instead of 2 kilobytes. + Fixed `#9197 `__ diff --git a/test/python/circuit/test_commutation_checker.py b/test/python/circuit/test_commutation_checker.py index c44252a64f3e..6ab74e484ae6 100644 --- a/test/python/circuit/test_commutation_checker.py +++ b/test/python/circuit/test_commutation_checker.py @@ -18,7 +18,7 @@ from qiskit import ClassicalRegister from qiskit.test import QiskitTestCase -from qiskit.circuit import QuantumRegister, Parameter +from qiskit.circuit import QuantumRegister, Parameter, Qubit from qiskit.circuit import CommutationChecker from qiskit.circuit.library import ( ZGate, @@ -357,6 +357,12 @@ def test_complex_gates(self): res = comm_checker.commute(lf3, [0, 1, 2], [], lf4, [0, 1, 2], []) self.assertTrue(res) + def test_c7x_gate(self): + """Test wide gate works correctly.""" + qargs = [Qubit() for _ in [None] * 8] + res = CommutationChecker().commute(XGate(), qargs[:1], [], XGate().control(7), qargs, []) + self.assertFalse(res) + if __name__ == "__main__": unittest.main()