NVIDIA / cuda-quantum

C++ and Python support for the CUDA Quantum programming model for heterogeneous quantum-classical workflows
https://nvidia.github.io/cuda-quantum/
Other
467 stars 166 forks source link

ConcatOp Canonicalization #573

Closed amccaskey closed 9 months ago

amccaskey commented 1 year ago

I would like to demonstrate lowering


__qpu__ void cnotKernel(cudaq::qubit &q, cudaq::qubit &r) {
  x<cudaq::ctrl>(q, r);
}

__qpu__ void multiCtrlTest() {
  cudaq::qreg q(4);
  cudaq::control(cnotKernel, {q[0], q[1]}, q[2], q[3]);
}

If I run

bin/cudaq-quake demo/multicontrol_decomp.cpp | \
  bin/cudaq-opt --canonicalize --apply-op-specialization  \
      --inline --quake-multicontrol-decomposition \
      --quantinuum-gate-set-mapping --canonicalize

you get

func.func @__nvqpp__mlirgen__function_multiCtrlTest._Z13multiCtrlTestv() attributes {"cudaq-entrypoint", "cudaq-kernel"} {
    %0 = quake.alloca !quake.ref
    %1 = quake.alloca !quake.veq<4>
    %2 = quake.extract_ref %1[0] : (!quake.veq<4>) -> !quake.ref
    %3 = quake.extract_ref %1[1] : (!quake.veq<4>) -> !quake.ref
    %4 = quake.concat %2, %3 : (!quake.ref, !quake.ref) -> !quake.veq<2>
    %5 = quake.extract_ref %1[2] : (!quake.veq<4>) -> !quake.ref
    %6 = quake.extract_ref %1[3] : (!quake.veq<4>) -> !quake.ref
    %7 = quake.concat %4 : (!quake.veq<2>) -> !quake.veq<2>
    %8 = quake.extract_ref %7[0] : (!quake.veq<2>) -> !quake.ref
    %9 = quake.extract_ref %7[1] : (!quake.veq<2>) -> !quake.ref
    quake.h %0 : (!quake.ref) -> ()
    quake.x [%9] %0 : (!quake.ref, !quake.ref) -> ()
    quake.t<adj> %0 : (!quake.ref) -> ()
    quake.x [%8] %0 : (!quake.ref, !quake.ref) -> ()
   ... more ...

Notice the quake.concat operations that remain. They are superfluous and could probably be optimized away. Is there any way to do that? Here we extract qubits 0 and 1, and concat them to a veq<2>, then we run concat again (looks like a no-op), and then just extract those qubits back out. Ideally, we could have just extracted from the original veq and been done.

amccaskey commented 1 year ago

I will leave this open for future work to investigate more general cases of concat op canonicalization. See comment thread on #574