iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🪐

Playing with CUDA-Q (1) — Creating a Bell State

に公開

Objective

NVIDIA Accelerates Quantum Computing Centers Worldwide with CUDA-Q Platform

On May 13, 2024, in Hamburg, Germany — ISC — NVIDIA today announced that its open-source NVIDIA CUDA-Q™ platform will accelerate quantum computing efforts at national supercomputing centers worldwide.

That was released quite a while ago, so I figured I'd give it a try.

Starting with the Tutorial

Installation

See Quick Start.

pip install cudaq

It says that's fine, but I want to do various things, so for now I'll do the following. I'll use Google Colab.

cudaq qbraid qiskit 'qiskit[visualization] qiskit-aer'

Countermeasures for Circuit Visualization

If not rendered in a monospaced font, the ASCII art circuit will be misaligned, so I'll take countermeasures. In a Windows environment, you can use Consolas, so I'll prepare the following utility.

from IPython.display import HTML, display

def show_fixed(text, font="Consolas, Roboto Mono, monospace", size=13):
    text = text.expandtabs(4)
    esc = (text.replace("&", "&")
               .replace("<", "&lt;")
               .replace(">", "&gt;"))
    html = f'<pre style="font-family:{font}; font-size:{size}px; white-space:pre; font-variant-ligatures:none;">{esc}</pre>'
    display(HTML(html))

Specifying the Target

The CUDA-Q Simulation Backends explains that you can specify a target such as CPU or GPU.

For example, for "OpenMP CPU-only" you can specify qpp-cpu, for "Single-GPU" using cuStateVec you can specify nvidia, for "Single-GPU" using cuTensorNet you can specify tensornet, and among tensor networks, if you want to use MPS (Matrix Product State), you can specify tensornet-mps. If nothing is specified, the default will choose either nvidia or qpp-cpu.

For now, I'll set it to qpp-cpu.

import cudaq

cudaq.set_target('qpp-cpu')

Creating a Bell State

You can refer to Validate your Installation. It applies a Hadamard gate, then a controlled-X gate, and finally measures in the Z-basis.

Since it's troublesome to encounter errors later, it's a good idea to compile the kernel... well, the quantum circuit part, in advance and check for errors.

qubit_count = 2

@cudaq.kernel
def kernel():
    qubits = cudaq.qvector(qubit_count)
    h(qubits[0])
    for i in range(1, qubit_count):
        x.ctrl(qubits[0], qubits[i])
    mz(qubits)

try:
    kernel.compile()
except Exception as e:
    print(e)

If you use an unknown gate like abc, you'll see the following error.

If you skip this, you might later get an AssertionError and be forced to restart the Colab session, which is a hassle.

But Colab is warning?

First of all, warnings appear saying "not defined" for all gates. That's a bit puzzling.

Looking closely, there is a @cudaq.kernel decorator above the function. I'll leave the details to the Appendix, but roughly looking at kernel_decorator.py, it says: "takes the decorated function as input and optionally lowers its AST representation to executable code via MLIR. This decorator enables full JIT compilation mode, where the function is lowered to an MLIR representation."

In other words, a function with @cudaq.kernel is treated as a "Python function AST" for CUDA-Q, which is then JIT-compiled into an intermediate representation, becoming executable code that runs on the CUDA-Q backend.

So, it's like a DSL (Domain-Specific Language) for CUDA-Q using Python, hence the warnings appear. It can't be helped.

Visualizing the Circuit

Now that we have defined the kernel, I want to visualize the quantum circuit.

If you visualize it using a monospaced font as shown below, you get the usual diagram. Of course, if you change the browser's default font settings beforehand, you don't need to use the utility.

show_fixed(str(cudaq.draw(kernel)))

Sampling

You can verify \frac{1}{\sqrt{2}}(|00\rangle + |11\rangle) as follows.

result = cudaq.sample(kernel)
print(result)

{ 00:484 11:516 }

Actually, even if you don't write mz(qubits) in the kernel, calling cudaq.sample will give you sampling results for all qubits. If you want to measure only specific qubits, you can do it as follows.

mz(qubits[0])

I Want to Use Qiskit

So I understand the basic usage of CUDA-Q, but it's a bit tricky if you're not used to it. Then I happened to glance at the paper arXiv:2507.12480 LLM-Powered Quantum Code Transpilation, which says something really nice:

Transpiling quantum code from one QSDK (e.g., IBM’s Qiskit) to another (e.g., Google’s Cirq) is critical for achieving cross-platform interoperability and hardware abstraction in quantum computing workflows.
...
In another study, Arulandu [6] developed a Python-based transpiler designed to convert OpenQASM 3.0 programs into CUDA-Q kernels. Building on existing OpenQASM parsing tools, the transpiler supports a substantial subset of the OpenQASM 3.0 specification, including features such as custom gates, control and adjoint modifiers, and binary expressions.
...
[6] A. C. Arulandu, “Transpiling openqasm 3.0 programs to cuda-q kernels.” https://arulandu.com/assets/pdf/cs252-qasm-cudaq-transpiler.pdf, 2024.Accessed: 2025-05-16.

Looking at Mr. A. C. Arulandu's paper, it suggests contributions to qBraid, specifically a pull-request for OpenQASM 3.0 to CUDA-Q Transpiler #857. This is exactly why I set up qbraid and qiskit at the beginning. Let's actually try it.

First Attempt

Simply using from qbraid.transpiler.conversions import openqasm3_to_cudaq is fine, but if you casually write a circuit in Qiskit and try to convert it, you'll get an exception. Using QuantumCircuit.measure_all inserts barriers, but this is not supported.

Writing a Quantum Circuit Without Barriers

The simplest way is to prevent barriers from being inserted automatically, as shown below.

from qiskit import QuantumCircuit, qasm3

qc = QuantumCircuit(2, 2)
qc.h(0)
qc.cx(0, 1)
qc.measure([0, 1], [0, 1])

Here I'll try a more exaggerated approach: using PassManager to remove barriers as shown below. Actually, this is overkill, so implementing it with the above method is the correct way.

The OpenQASM 3.0 output is as follows:

OPENQASM 3.0;
include "stdgates.inc";
bit[2] meas;
qubit[2] q;
h q[0];
cx q[0], q[1];
meas[0] = measure q[0];
meas[1] = measure q[1];

Conversion to CUDA-Q Kernel via OpenQASM 3.0

As a recap, you can convert as follows. Calling show_fixed(str(cudaq.draw(kernel))) will display the circuit diagram shown above in ASCII art. Sampling will give the same results.

from qbraid.transpiler.conversions import openqasm3_to_cudaq

try:
    kernel = openqasm3_to_cudaq(qasm3.dumps(qc))
except Exception as e:
    print(e)

Obtaining OpenQASM 2.0 from a CUDA-Q Kernel

Conversely, you can also obtain OpenQASM from a CUDA-Q kernel. After checking the API implementation, it appears that currently it converts to OpenQASM 2.0. The content seems reasonable.

print(cudaq.translate(kernel, format="openqasm2"))
// Code generated by NVIDIA's nvq++ compiler
OPENQASM 2.0;

include "qelib1.inc";

gate nvqpp__mlirgen____nvqppBuilderKernel_OY2IYXXW60 q0 {
  h q0;
}

gate nvqpp__mlirgen____nvqppBuilderKernel_TREV53PON9 q0 {
  x q0;
}

qreg var0[2];
h var0[0];
cx var0[0], var0[1];
creg var3[1];
measure var0[0] -> var3[0];
creg var4[1];
measure var0[1] -> var4[0];

Visualizing with Qiskit

Below, we load the OpenQASM 2.0 and convert it to a QuantumCircuit. Visualizing it gives a familiar feel.

qc2 = QuantumCircuit.from_qasm_str(cudaq.translate(kernel, format="openqasm2"))
qc2.draw("mpl", style="clifford")

Summary

I tried out various things while briefly looking at the tutorial. I found it a bit difficult to write a CUDA-Q kernel from scratch, so I also tried converting from Qiskit, which I'm more familiar with.

I think I have a basic understanding now, so I would like to explore other aspects as well.

References

Appendix

A Brief Dive into @cudaq.kernel

The kernel_decorator.py file states: "takes the decorated function as input and optionally lowers its AST representation to executable code via MLIR. This decorator enables full JIT compilation mode, where the function is lowered to an MLIR representation." Extracting only the interesting parts yields the following. It shows that it is essentially a mechanism that wraps the function with a JIT compiler.

[kernel_decorator.py]

# This file implements the decorator mechanism needed to
# JIT compile CUDA-Q kernels. It exposes the cudaq.kernel()
# decorator which hooks us into the JIT compilation infrastructure
# which maps the AST representation to an MLIR representation and ultimately
# executable code.


class PyKernelDecorator(object):
    """
    The `PyKernelDecorator` serves as a standard Python decorator that takes 
    the decorated function as input and optionally lowers its  AST 
    representation to executable code via MLIR. This decorator enables full JIT
    compilation mode, where the function is lowered to an MLIR representation.

    This decorator exposes a call overload that executes the code via the 
    MLIR `ExecutionEngine` for the MLIR mode. 
    """

    def __init__(self,
                 function,
                 verbose=False,
                 module=None,
                 kernelName=None,
                 funcSrc=None,
                 signature=None,
                 location=None,
                 overrideGlobalScopedVars=None):

        is_deserializing = isinstance(function, str)

        ...

    def compile(self):
        """
        Compile the Python function AST to MLIR. This is a no-op 
        if the kernel is already compiled. 
        """

        ...

    def __call__(self, *args):
        """
        Invoke the CUDA-Q kernel. JIT compilation of the kernel AST to MLIR 
        will occur here if it has not already occurred, except when the target
        requires custom handling.
        """

        ...
        # Compile, no-op if the module is not None
        self.compile()
        ...
        if self.returnType == None:
            cudaq_runtime.pyAltLaunchKernel(self.name,
                                            self.module,
                                            *processedArgs,
                                            callable_names=callableNames)
        else:
            result = cudaq_runtime.pyAltLaunchKernelR(
                self.name,
                self.module,
                mlirTypeFromPyType(self.returnType, self.module.context),
                *processedArgs,
                callable_names=callableNames)
            return result


def kernel(function=None, **kwargs):
    if function:
        return PyKernelDecorator(function)
    else:

        def wrapper(function):
            return PyKernelDecorator(function, **kwargs)

        return wrapper
GitHubで編集を提案

Discussion