[unitary-synthesis] Valid 3-qubit custom unitary remains unsynthesized; simple permutations lower to oversized circuits

Open
#4,778 0 comments 0 reactions 0 assignees View on GitHub

Maintainers usually reply within 1 day

Nobody has claimed this yet.

Assessment

Difficulty
4/5
Estimated time
3-5 days
Newbie friendliness
55/100
Issue type
Bug
Clarity
Mostly clear
Activity status
Quiet
Tech stack
cpp, python
Domain
compilers

Research direction

Start with make_unitary_synthesis_repro.py and generate bitflip.qke, toffoli.qke, and monomial.qke. Run cudaq-opt with --unitary-synthesis, then with the additional canonicalization and specialization options, and inspect the resulting gate counts and remaining custom operations. Done means monomial is synthesized and the simple permutations produce substantially smaller decompositions matching the stated expectations.

Written by the indexing model from the issue text.

Description

stale-notified

Hi CUDA-Q team,

This report comes from my local work on a PR attempt for 3-qubit custom-operation synthesis during UnitaryHack 2026 / issue #2242. I was not able to submit that PR because of the UnitaryHack 2026 PR limit, so I continued testing the current main locally and found two cases that seem worth tracking.

This is intended as a focused follow-up report. The general 3-qubit synthesis path is useful, and the random dense and random monomial unitaries I tried did synthesize successfully. The cases below are specific structured inputs where the current behavior is either incomplete or much larger than expected.

Environment tested: origin/main at 1b23e94d on 2026-06-24. The commands below assume cudaq-opt built from current main is on PATH; alternatively set CUDAQ_OPT=/path/to/cudaq-opt.

Reproducer setup

Generate three 3-qubit custom-unitary kernels as Quake IR:

cat > make_unitary_synthesis_repro.py <<'PY'
from cmath import exp
from pathlib import Path

N = 8

def zero_matrix():
    return [[0j for _ in range(N)] for _ in range(N)]


def matmul_adj_self(m):
    return [
        [sum(m[k][r].conjugate() * m[k][c] for k in range(N)) for c in range(N)]
        for r in range(N)
    ]


def unitary_residual(m):
    gram = matmul_adj_self(m)
    return max(abs(gram[r][c] - (1 if r == c else 0)) for r in range(N) for c in range(N))

def from_mapping(cols, phases=None):
    phases = phases or [1] * N
    m = zero_matrix()
    for r, (c, phase) in enumerate(zip(cols, phases)):
        m[r][c] = complex(phase)
    return m


def write_quake(name, m):
    rows = ",\n".join(
        "    " + ", ".join(f"({z.real:.17e},{z.imag:.17e})" for z in row)
        for row in m
    )
    Path(f"{name}.qke").write_text(f'''module attributes {{quake.mangled_name_map = {{__nvqpp__mlirgen__kernel = "__nvqpp__mlirgen__kernel_PyKernelEntryPointRewrite"}}}} {{
  func.func @__nvqpp__mlirgen__kernel() attributes {{"cudaq-entrypoint"}} {{
    %0 = quake.alloca !quake.veq<3>
    %1 = quake.extract_ref %0[0] : (!quake.veq<3>) -> !quake.ref
    %2 = quake.extract_ref %0[1] : (!quake.veq<3>) -> !quake.ref
    %3 = quake.extract_ref %0[2] : (!quake.veq<3>) -> !quake.ref
    quake.custom_unitary_constant @__nvqpp__mlirgen__{name}_generator_1.rodata %1, %2, %3 : (!quake.ref, !quake.ref, !quake.ref) -> ()
    return
  }}
  cc.global constant private @__nvqpp__mlirgen__{name}_generator_1.rodata (dense<[
{rows}
  ]> : tensor<64xcomplex<f64>>) : !cc.array<complex<f64> x 64>
}}''')


# X on all three qubits: row r has a 1 at column r xor 0b111.
bitflip = from_mapping([r ^ 0b111 for r in range(N)])
write_quake("bitflip", bitflip)

# Toffoli / CCX: swap basis states 6 and 7.
toffoli_cols = list(range(N))
toffoli_cols[6], toffoli_cols[7] = 7, 6
toffoli = from_mapping(toffoli_cols)
write_quake("toffoli", toffoli)

# A valid monomial unitary: permutation [4,7,6,5,0,1,2,3] with unit-modulus phases.
monomial = from_mapping(
    [4, 7, 6, 5, 0, 1, 2, 3],
    [exp(0.3j), 1, -1j, exp(-0.7j), 1, -1, 1j, -1j],
)
write_quake("monomial", monomial)

for name, matrix in [("bitflip", bitflip), ("toffoli", toffoli), ("monomial", monomial)]:
    residual = unitary_residual(matrix)
    assert residual < 1e-14, (name, residual)
    print(f"{name} unitary_residual={residual:.3e}")
PY

python3 make_unitary_synthesis_repro.py

Expected setup output:

bitflip unitary_residual=0.000e+00
toffoli unitary_residual=0.000e+00
monomial unitary_residual=0.000e+00

Finding 1: valid unitary is left unsynthesized

monomial.qke is a valid 3-qubit unitary: exactly one unit-modulus nonzero entry per row and per column. I would expect --unitary-synthesis to replace the custom operation with native Quake operations and leave no quake.custom_unitary_constant in the output.

Command:

"${CUDAQ_OPT:-cudaq-opt}" --unitary-synthesis monomial.qke > monomial.out 2> monomial.err
printf 'custom_unitary_constant count: '
grep -c 'quake.custom_unitary_constant' monomial.out || true
cat monomial.err

Expected result:

custom_unitary_constant count: 0

Actual result on 1b23e94d:

custom_unitary_constant count: 1
monomial.qke:7:5: warning: unitary-synthesis: could not synthesize this custom operation within the reconstruction tolerance; leaving it unchanged.

The graceful fallback is good, but the practical result is that a valid 3-qubit unitary can survive --unitary-synthesis unchanged. That can still block targets or lowerings that require native gates.

Finding 2: simple permutations lower to oversized circuits

The pure permutation examples do synthesize, but they lower through a large generic decomposition even when the structure is very simple.

Command:

count() { grep -c "$1" "$2" || true; }

for case in bitflip toffoli; do
  "${CUDAQ_OPT:-cudaq-opt}" \
    --unitary-synthesis \
    --canonicalize \
    --apply-op-specialization \
    --aggressive-inlining \
    "${case}.qke" > "${case}.out"

  printf '%-8s custom=%s x_controlled=%s x_plain=%s rz=%s ry=%s rx=%s r1=%s h=%s total_listed_gates=%s\n' \
    "${case}" \
    "$(count 'quake.custom_unitary_constant' "${case}.out")" \
    "$(count 'quake.x \[' "${case}.out")" \
    "$(count 'quake.x %' "${case}.out")" \
    "$(count 'quake.rz' "${case}.out")" \
    "$(count 'quake.ry' "${case}.out")" \
    "$(count 'quake.rx' "${case}.out")" \
    "$(count 'quake.r1' "${case}.out")" \
    "$(count 'quake.h' "${case}.out")" \
    "$(grep -Ec 'quake\.(x|h|rz|ry|rx|r1)' "${case}.out" || true)"
done

Actual result on 1b23e94d:

bitflip  custom=0 x_controlled=22 x_plain=0 rz=39 ry=16 rx=12 r1=3 h=8 total_listed_gates=100
toffoli  custom=0 x_controlled=16 x_plain=0 rz=24 ry=5  rx=4  r1=2 h=0 total_listed_gates=51

Expected result:

  • bitflip is just X on each of the three qubits, so I would expect three single-qubit X gates and zero two-qubit gates.
  • toffoli has standard decompositions around six CNOT-like gates plus one-qubit gates, so I would not expect 16 controlled-X operations and 51 listed gate operations.

Why this matters

Monomial and permutation matrices naturally show up in custom operations for reversible classical logic, oracle construction, basis-state relabeling, multi-controlled-X variants, and bit or wire permutations. For these cases, two-qubit gate count is often the important cost, and the first finding means one valid structured unitary may not lower at all.

Dominant language
C++
Stars
1.2k
Forks
508
Avg merge
1d 19h
Merged PRs (30d)
100

Getting set up

Open in Codespaces

Starts the project's dev container in your browser, under your own GitHub account.

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from NVIDIA/cuda-quantum

All issues in NVIDIA/cuda-quantum

Similar issues

More C++ issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.