From 58acc2e9343bb2c780154f6d5ea9f9d011d4f022 Mon Sep 17 00:00:00 2001 From: Pyhroff Date: Sat, 24 Oct 2026 12:05:06 +0530 Subject: [PATCH] Fix Add.build_call_graph CNOT count for unequal register bitsizes (#1818) --- qualtran/bloqs/arithmetic/addition.py | 10 +++++++++- qualtran/bloqs/arithmetic/addition_test.py | 11 +++++++++++ 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/qualtran/bloqs/arithmetic/addition.py b/qualtran/bloqs/arithmetic/addition.py index 7da0af6e7..d008f6779 100644 --- a/qualtran/bloqs/arithmetic/addition.py +++ b/qualtran/bloqs/arithmetic/addition.py @@ -219,7 +219,15 @@ def decompose_from_registers( def build_call_graph(self, ssa: 'SympySymbolAllocator') -> 'BloqCountDictT': n = self.b_dtype.bitsize - n_cnot = (n - 2) * 6 + 3 + m = self.a_dtype.bitsize + if not is_symbolic(n) and n == 1: + return {CNOT(): 1} + if m == n: + n_cnot: SymbolicInt = (n - 2) * 6 + 3 + elif not is_symbolic(m) and not is_symbolic(n): + n_cnot = (n - 2) * 3 + 2 + 3 * m - 3 + else: + n_cnot = (n - 2) * 3 + 2 + sympy.Piecewise((3 * n - 5, sympy.Eq(m, n)), (3 * m - 3, True)) return {And(): n - 1, And().adjoint(): n - 1, CNOT(): n_cnot} def get_ctrl_system(self, ctrl_spec: 'CtrlSpec') -> Tuple['Bloq', 'AddControlledT']: diff --git a/qualtran/bloqs/arithmetic/addition_test.py b/qualtran/bloqs/arithmetic/addition_test.py index 85af0f39e..53ddd4c00 100644 --- a/qualtran/bloqs/arithmetic/addition_test.py +++ b/qualtran/bloqs/arithmetic/addition_test.py @@ -205,6 +205,17 @@ def test_addition_gate_counts(n: int): qlt_testing.assert_equivalent_bloq_counts(add, ignore_split_join) +@pytest.mark.parametrize( + "m,n", + [(a, b) for b in range(1, 7) for a in range(1, b + 1)], +) +def test_addition_gate_counts_unequal_bitsizes(m: int, n: int): + add = Add(QUInt(m), QUInt(n)) + qlt_testing.assert_valid_bloq_decomposition(add) + assert add.t_complexity() == add.decompose_bloq().t_complexity() + qlt_testing.assert_equivalent_bloq_counts(add, ignore_split_join) + + @pytest.mark.parametrize('a,b', itertools.product(range(2**3), repeat=2)) def test_add_tensor_contract(a, b): num_bits = 5