Defining targets and customizing compilation¶
Note
This page is currently Python only.
The last sections of this page, from Using custom compile targets for finer-grained compilation control onward, rely on experimental APIs to control the compilation. These APIs are likely to change significantly in upcoming releases. Please do not hesitate to open an issue on our GitHub repository if you run into problems, or would like to share suggestions or make feature requests.
Behind the scenes, CUDA-Q must compile kernels defined in Python or C++ into a form that can be executed on the target. This happens transparently any time a quantum kernel is launched (known as just-in-time (JIT) compilation). In this page, we look at the options available to configure and modify this compilation step, focusing on the most common use cases. For a complete description of compile targets, including IR profiles, multi-stage targets and how compilation pipelines are inferred, see Using compile targets to customize compilation.
Compiling for built-in targets¶
Throughout this page, we compile a kernel qpe that implements quantum
phase estimation on 6 qubits, with 4 data qubits and 2 ancilla. Have a look at
the source.
if you are interested in the full implementation.
At the most basic level, a compiler’s job is to take this high-level
description of a computation and produce a circuit that a given target is able
to execute. Setting for instance the target to iqm will cause the compiler
to produce a circuit that uses the basis gates available on IQM’s hardware. In
emulation mode, the compiled kernel is not submitted to IQM’s servers. To
inspect the compiled circuit, we use cudaq.estimate(), which counts the
gates and qubits that the compiled kernel uses:
cudaq.set_target("iqm", emulate=True)
results = cudaq.estimate(qpe)
# 555 gates on 6 qubits: 473 `phased_rx`, 78 `cz` and 4 `mz`.
print(results.resources)
As you can see from the resource estimates, the resulting circuit only contains
cz and phased_rx gates, alongside measurements.
Note
When running the code above, CUDA-Q will warn you that it is unable to
obtain a copy of the device architecture, which it would normally use for
routing the circuit. You can fix the warning by either providing a valid IQM
token or passing a mapping_file directly as an option to
cudaq.set_target. See the IQM backend and its
advanced use cases for more
information.
The compiler also supports synthesizing circuits to discrete gate sets, often required to encode circuits using quantum error correcting codes. We can for instance select CUDA-Q’s built-in Clifford+T target to express the same kernel in terms of Cliffords (CNOT, H, S, X, Z) and T gates:
CLIFFORD_T_TARGET = "compiler-bench-ftqc-clifford-t"
cudaq.set_target(CLIFFORD_T_TARGET)
results = cudaq.estimate(qpe)
# 3262 gates on 6 qubits: 1313 `h`, 610 `s`, 1301 `t`, 6 `x`, 4 `z`,
# 22 `cx`, 2 `swap` and 4 `mz`.
print(results.resources)
Note that as this gate set is discrete, the resulting circuit can only
implement arbitrary rotation angles up to a certain approximation error (by
default 1e-10). The cudaq-logical package allows you to configure the
precision of the approximation, see below. For more details on how rotations
are approximated, see Rotation Synthesis.
Controlling the optimization level of the compiler¶
The simplest configuration option that can be modified to adjust the behavior
of the compiler is the optimization level. This is a number between 0 and 3
that can be passed as the optimization_level argument to any of the CUDA-Q
kernel launch functions, such as sample, observe or estimate. It
controls which compiler optimizations should be enabled. As with the
-O0 to -O3 flags of classical compilers, higher levels correspond to
more aggressive optimizations, which should result in fewer gates in the final
compiled program:
Level 0: only the transformations required to lower the kernel to the target, such as decomposing gates into the target’s gate set.
Level 1: cheap local rewrites of adjacent or commuting gates, such as gate cancellation and rotation merging.
Level 2: analyses across the whole kernel, such as phase folding and re-synthesis. These take more compile time but usually produce smaller circuits.
Level 3: reserved for more expensive search-based optimizations. It currently behaves like level 2.
When no level is specified, the compiler currently uses level 2.
Note
Advanced compiler optimizations (optimization_level greater than 1) are
currently only enabled by default for targets using the Clifford+T gate set.
Support for optimizations on noisy hardware and simulators is still
experimental and can be enabled using custom targets, see below.
Depending on the compile target, the compiler will prioritize different metrics and may optimize for different cost functions. Using the previous Clifford+T target, we can see a 67% reduction in T gate count as the optimization level increases:
cudaq.set_target(CLIFFORD_T_TARGET)
# T count per level: 3897 (level 0), 3797 (level 1) and 1301 (levels 2 and 3).
for level in (0, 1, 2, 3):
resources = cudaq.estimate(qpe, optimization_level=level).resources
print(f'optimization_level = {level}:\n{resources}\n')
Since level 2 is the default, its result is identical to the one obtained in the previous section. Optimization levels 2 and 3 are currently identical.
A Clifford+T target is also shipped with the cudaq-logical package, CUDA-Q’s quantum error correction toolkit. It comes with a simple constructor to override the desired approximation precision:
import cudaq.logical as cql
cudaq.set_target(cql.targets.clifford_t_target(precision=1e-6))
# 2271 T gates (versus 3897 for precision=1e-10).
estimate = cudaq.estimate(qpe, optimization_level=0)
print(f"{estimate.resources.count('t')} T")
Loosening the precision reduces the number of T gates required to approximate each rotation, at the cost of a less accurate circuit.
Using custom compile targets for finer-grained compilation control¶
The optimization level is a useful high-level setting to control how much
effort is spent on optimization. When finer-grained control is required over
the compilation, you can tweak the built-in targets to suit your needs, or
even define your own custom compile targets from scratch. From here on, we rely
on the experimental cudaq._experimental module, see the note at the top of
this page. The examples below cover a few common use cases;
see Using compile targets to customize compilation
for the other available profiles, multi-stage targets and lowering options.
To start with, here is how to retrieve the full configuration of the built-in Clifford+T compile target we have been using:
from cudaq._experimental import get_compile_target
cudaq.set_target(CLIFFORD_T_TARGET)
clifford_t_target = get_compile_target()
# ```
# CompileTarget(stages=[CompilationStage(ir_output_profile=QuakeUnmappedProfile(
# basis_gates=['h', 's', 't', 'x', 'y', 'z', 'swap', 'x(1)', 'y(1)', 'z(1)'],
# approximation_tolerance=1e-10, cost_model=CostModel.t_count, ...),
# lowering=inferred)], ...)
# ```
print(clifford_t_target)
The Clifford+T compile target is defined by a single compilation stage
clifford_t_target.stages[0]. The stage is defined using an
ir_output_profile, which characterizes the kinds of quantum circuits that
the target supports. Among other things, it lists the basis gates that the
compiled circuit may use, the tolerance used to approximate rotations, and the
cost model that the optimizations aim to minimize.
We can for instance replace the allowed basis gates with CNOTs (written
x(1), that is an x gate with one control), Hadamards, x gates
and rz rotations. As a result, the compiler no longer synthesizes the rotations
present in the qpe kernel:
new_basis_gates = ['x(1)', 'h', 'x', 'rz']
new_target = clifford_t_target
stage = clifford_t_target.stages[0]
profile = stage.ir_output_profile
profile.basis_gates = new_basis_gates
stage.ir_output_profile = profile
new_target.stages = [stage]
# Same as before, but with `basis_gates=['x(1)', 'h', 'x', 'rz']`.
print(new_target)
# Pass a named target and a compile target: kernels run on the named target,
# but are compiled against the given compile target.
cudaq.set_target("qpp-cpu", compile_target=new_target)
# Gate counts per level, in addition to 8 `h`, 1 `x` and 4 `mz`:
# level 0: 78 `cx` and 48 `rz`
# level 1: 50 `cx` and 45 `rz`
# level 2: 28 `cx` and 20 `rz`
for level in range(3):
resources = cudaq.estimate(qpe, optimization_level=level).resources
print(resources)
Note that a CUDA-Q target is made of a runtime component (where a kernel
should execute), and a compile component (how a kernel should be compiled).
We only wish to override the compile part of the target. This is why when using
cudaq.set_target, we still specify a base built-in target (in our case, the
QPP simulator): the runtime component remains unchanged from the built-in,
while the compile target gets overridden by our custom target.
However, as configured, our custom target still optimizes for T count. This no
longer makes sense now that we have changed the gate set. We can instead define
our own compile target from scratch, using controlled-Z gates (written z(1)),
Hadamards, x gates and rx and rz rotations, and minimizing the number of
two-qubit gates:
from cudaq._experimental import CompileTarget, QuakeUnmappedProfile, CostModel
nisq_gates = ["h", "x", "rx", "rz", "z(1)"]
nisq_profile = QuakeUnmappedProfile(basis_gates=nisq_gates,
cost_model=CostModel.two_qubit_gate_count)
nisq_target = CompileTarget(ir_output_profile=nisq_profile)
cudaq.set_target("qpp-cpu", compile_target=nisq_target)
# Gate counts per level, in addition to 1 `x` and 4 `mz`:
# level 0: 78 `cz`, 164 `h` and 48 `rz`
# level 1: 50 `cz`, 108 `h` and 48 `rz`
# level 2: 28 `cz`, 64 `h` and 17 `rz`
for level in range(3):
resources = cudaq.estimate(qpe, optimization_level=level).resources
print(resources)
In this case, optimization level 2 matches the performance achieved by the T-count optimized compilation.
Customizing all the way¶
Finally, to get maximal control over the compiler, users can choose to bypass the CUDA-Q pre-defined compilation options altogether and provide a custom MLIR compilation pipeline. The example below only decomposes the gates into the requested basis and applies no optimizations, which is why it produces the same circuit as the previous target at optimization level 0:
from cudaq._experimental import CustomPipelineLowering
# Just decompose the gates and do nothing else.
custom_pipeline = "decomposition{basis=" + ",".join(nisq_gates) + "}"
custom_target = CompileTarget(custom_pipeline=CustomPipelineLowering(
mid_level_pipeline=custom_pipeline))
cudaq.set_target("qpp-cpu", compile_target=custom_target)
resources = cudaq.estimate(qpe).resources
# 295 gates: 78 `cz`, 164 `h`, 48 `rz`, 1 `x` and 4 `mz`.
print(resources)
Here we only override the mid-level pipeline. CustomPipelineLowering also
accepts further arguments, see
Using compile targets to customize compilation
for more details.
Defining custom pipelines is mostly useful for experimentation, when doing research or developing new custom targets. Expect to have to update and adjust your custom pipeline over time, as the CUDA-Q compiler evolves. A pipeline that works well today may become outdated and may not be designed to leverage features that will ship with future releases of CUDA-Q.