# Synthesize CUDA-Q kernels to Clifford+T

> Explore optimized synthesis with fo-synth-cudaq

Source: https://docs.q-ctrl.com/fire-opal/ftqc/compile/synthesize-cuda-q-kernels-to-cliffordt

Fault-tolerant algorithms often require decomposing arbitrary unitary operations using a restricted discrete gate set.
The `fo-synth-cudaq` package adds optimized synthesis to the CUDA-Q compiler, approximating those operations with Clifford+T kernels containing native H, S, T, X, Z, and CNOT (`cx`) instructions.
Clifford gates alone are not universal; adding the non-Clifford T gate enables universal quantum computation through approximation.
T gates typically require costly magic-state resources in fault-tolerant implementations, so T-count is a useful resource indicator alongside CNOT count and circuit depth.

In this tutorial, you will compile a small CUDA-Q kernel to Clifford+T, measure the approximation error, trade accuracy for synthesis cost, compare the result with CUDA-Q's built-in Clifford+T target, and import the synthesized kernel into CUDA-Q Logical.

## Install and import the package

The `fo-synth-cudaq` package requires Python 3.12 to 3.14 on Linux (x86_64 or aarch64), the platforms supported by the CUDA-Q 0.16 and CUDA-Q Logical packages it depends on.
macOS and Windows are not supported.
Install the package in the Python environment used by your Jupyter kernel:

```shell
pip install fo-synth-cudaq
```

The package installs CUDA-Q and CUDA-Q Logical as dependencies.
Restart the kernel if you installed or upgraded packages while it was running.

Importing `fo_synth_cudaq` loads the synthesis plugin and registers the `fo-synth-ftqc-clifford-t` CUDA-Q target.
On import, CUDA-Q 0.16 warns that CUDA-Q Logical is in preview and that some of its APIs will change.
These notices don't affect this tutorial.


```python
import re
from collections import Counter
from time import perf_counter
import numpy as np
from IPython.display import Markdown, display
import cudaq
import fo_synth_cudaq
```

    /artifacts/cudaq-linux-venv/lib/python3.12/site-packages/cudaq/__init__.py:260: UserWarning: cudaq-logical is in preview. Its APIs, behavior, and documentation may change substantially in upcoming versions.
      from . import logical  # noqa: F401


    /tmp/ipykernel_7/717334618.py:6: FutureWarning: The CUDA-Q `sample` and `observe` algorithmic primitives will change in a future release. Existing code may require updates. See https://nvidia.github.io/cuda-quantum/latest/using/migration/upcoming_changes.html for details.
      import cudaq


## Compile your first kernel

To use the synthesizer, select the `fo-synth-ftqc-clifford-t` target with `cudaq.set_target`.
The target has one argument:

| Argument | Accepted values | Meaning |
| --- | --- | --- |
| `epsilon` | A string containing a positive number, such as `"1e-6"` | Maximal allowed distance between each synthesized single-qubit unitary and the ideal one, in terms of the operator norm |

Pass `epsilon` as a string, because CUDA-Q rejects numeric target arguments.
Always set `epsilon` explicitly.
The examples below use values from `1e-2` to `1e-7`, staying above the warning threshold.

**Very small tolerances emit warnings.** The synthesizer warns when called with tolerance `<= 1e-8`. Such tolerances may significantly extend synthesis time and/or fail to find a solution. Also, only devices with a quantum error correction (QEC) error per cycle of about `1e-20` could take advantage of such accurate synthesis, whereas current long-term projections for achievable error per cycle are larger.

When you select this target, CUDA-Q first decomposes your kernel into single-qubit gates and CNOTs.
The synthesizer then moves single-qubit gates through CNOTs where possible and fuses each run of consecutive single-qubit gates on a qubit into one arbitrary single-qubit unitary (an SU(2) `u3` gate).
Finally, it approximates (with the provided tolerance as an upper bound) each fused unitary with a Clifford+T sequence.
Kernels can act on any number of qubits: the unit of synthesis is always a single-qubit run, and the CNOT structure of the kernel is kept.

Once the target is set, CUDA-Q applies the synthesizer whenever you run, simulate, or analyze a kernel.
For example, `cudaq.estimate_resources` compiles a kernel for the current target and counts its gates without running it.

The kernel below applies arbitrary rotations to two qubits on both sides of a CNOT.
Rotation angles are in radians.


```python
@cudaq.kernel
def first_kernel():
    qubits = cudaq.qvector(2)
    rx(0.31, qubits[0])
    ry(0.27, qubits[1])
    rz(0.4, qubits[0])
    x.ctrl(qubits[0], qubits[1])
    rz(-0.53, qubits[1])
    ry(0.7, qubits[0])


cudaq.set_target("fo-synth-ftqc-clifford-t", epsilon="1e-6")
first_resources = cudaq.estimate_resources(first_kernel)

print("Compiled operations:", first_resources.to_dict())
```

    Compiled operations: {'z': 2, 'cx': 1, 'h': 223, 't': 221, 's': 112}


The compiled kernel contains only Clifford gates (such as H, S, X, and Z), T gates, and the original CNOT.
You can also run kernels on this target with `cudaq.sample`, or inspect the compiled gates with `cudaq.translate(kernel, format="openqasm2")`.

## Measure approximation error

The `epsilon` target argument is an upper bound on the **operator-norm error minimized over global phase** of each synthesized single-qubit unitary.
The operator norm of a matrix is its largest singular value.
For the difference between a target unitary $U$ and its approximation $V$, it measures the largest output-state-vector difference over normalized input states.
Here, we minimize that difference over a global phase: $\epsilon = \min_\phi \lVert U - e^{i\phi}V \rVert_{\mathrm{op}}$.
Global phase does not change measurement probabilities, so two unitaries that differ only by a global phase have zero error under this metric.

For a single-qubit unitary, the **average gate infidelity** $1-F_{\mathrm{avg}}$ is related to this error by

$$
1-F_{\mathrm{avg}} = \frac{2}{3}\epsilon^2\left(1-\frac{\epsilon^2}{4}\right) \approx \frac{2}{3}\epsilon^2,
$$

where the approximation holds for small errors and $F_{\mathrm{avg}}$ averages output-state fidelity over uniformly distributed pure input states.

To check a whole kernel, compare the unitary of the compiled kernel with the ideal one.
Under a synthesis target, `cudaq.get_unitary` compiles the kernel with that target's passes before simulating it, so it returns the unitary of the synthesized kernel.
The `ideal_unitary` helper below instead simulates the kernel on the `qpp-cpu` target, which doesn't synthesize.
The `operator_error` function finds the shortest arc containing the eigenphases of the relative unitary.
Centering that arc gives the optimal global-phase adjustment; its width determines the operator-norm distance.
Use these diagnostics only for small kernels without measurements, because the matrix size grows exponentially with qubit count.
Because `ideal_unitary` switches to the `qpp-cpu` target, select a synthesis target again before compiling more kernels.


```python
def ideal_unitary(kernel):
    """Return the unitary of a kernel simulated without synthesis."""
    cudaq.set_target("qpp-cpu")
    return np.array(cudaq.get_unitary(kernel))


def operator_error(target_matrix, result_matrix):
    """Return the operator-norm distance between unitaries up to global phase."""
    relative = target_matrix.conj().T @ result_matrix
    full_turn = 2 * np.pi
    phases = np.sort(np.angle(np.linalg.eigvals(relative)) % full_turn)
    gaps = np.diff(np.append(phases, phases[0] + full_turn))
    arc_width = full_turn - np.max(gaps)
    return float(2 * np.sin(arc_width / 4))


first_ideal = ideal_unitary(first_kernel)
cudaq.set_target("fo-synth-ftqc-clifford-t", epsilon="1e-6")
first_synthesized = np.array(cudaq.get_unitary(first_kernel))
first_error = operator_error(first_ideal, first_synthesized)
print(f"Whole-kernel error: {first_error:.3e}")
```

    Whole-kernel error: 1.958e-06


## Trade approximation accuracy for synthesis cost

Smaller `epsilon` values require a closer approximation, typically increasing the number of T gates and synthesis effort.
Larger values permit a coarser approximation that may use fewer resources.

To illustrate, below you can compile the same kernel with four values of `epsilon`.
The Seconds column is the time `cudaq.estimate_resources` takes to compile the kernel and count its gates.


```python
print(f"{'Epsilon':>8} {'Error':>11} {'T':>5} {'Gates':>7} {'Seconds':>9}")
for epsilon in ["1e-2", "1e-4", "1e-6", "1e-7"]:
    cudaq.set_target("fo-synth-ftqc-clifford-t", epsilon=epsilon)
    start = perf_counter()
    resources = cudaq.estimate_resources(first_kernel)
    elapsed = perf_counter() - start
    error = operator_error(first_ideal, np.array(cudaq.get_unitary(first_kernel)))
    print(
        f"{epsilon:>8} {error:11.3e} {resources.count('t'):5d} "
        f"{resources.count():7d} {elapsed:9.4f}"
    )
```

     Epsilon       Error     T   Gates   Seconds
        1e-2   2.075e-02    71     176    0.0488


        1e-4   2.092e-04   154     386    0.0481
        1e-6   1.958e-06   221     559    0.0504


        1e-7   2.983e-07   266     686    0.1484


Notice how tightening `epsilon` changes the T-count and gate count, not just the error column.

**Epsilon is not a whole-kernel error budget.**
The whole-kernel error can exceed `epsilon`, because each synthesized single-qubit unitary contributes its own error.
For a full kernel, a conservative bound is `N * epsilon`, where `N` is the number of fused single-qubit unitaries actually sent to synthesis.
It is not the number of input gates or emitted Clifford+T instructions.
If you know your kernel contains `N` unitaries to synthesize and require a kernel bound of `budget`, choose `epsilon` no greater than `budget / N`.
For example, ten synthesized unitaries at `epsilon="1e-4"` give a conservative whole-kernel bound of `1e-3`, not `1e-4`.

## Compare with CUDA-Q's gridsynth target

CUDA-Q 0.16 includes a built-in Clifford+T target, `compiler-bench-ftqc-clifford-t`.
It decomposes single-qubit gates into Clifford gates and Z rotations, then approximates each remaining Z rotation separately with the gridsynth algorithm, using `epsilon` per rotation.
In contrast, `fo-synth-ftqc-clifford-t` approximates each fused single-qubit run as one arbitrary unitary.
Both targets keep the CNOTs of the decomposed kernel.

To compare them, use a three-qubit layered ansatz in which each qubit receives Y, Z, and X rotations before, between, and after two CNOT ladders.
The cell below draws the original logical circuit before synthesis with `cudaq.draw`.
Because `cudaq.draw` wraps its output at 80 columns and has no option to turn wrapping off, the `draw_unfolded` helper joins the wrapped pieces to show the circuit on one line.
`cudaq.draw` also compiles the kernel for the current target, so select the `qpp-cpu` target first to draw the kernel as written.


```python
@cudaq.kernel
def ansatz():
    qubits = cudaq.qvector(3)
    ry(0.42, qubits[0])
    rz(-0.37, qubits[0])
    rx(0.87, qubits[0])
    ry(1.13, qubits[1])
    rz(0.58, qubits[1])
    rx(0.33, qubits[1])
    ry(-0.66, qubits[2])
    rz(0.29, qubits[2])
    rx(0.47, qubits[2])
    x.ctrl(qubits[0], qubits[1])
    x.ctrl(qubits[1], qubits[2])
    ry(0.81, qubits[0])
    rz(0.17, qubits[0])
    rx(0.26, qubits[0])
    ry(-0.24, qubits[1])
    rz(0.93, qubits[1])
    rx(0.19, qubits[1])
    ry(0.55, qubits[2])
    rz(-0.71, qubits[2])
    rx(0.50, qubits[2])
    x.ctrl(qubits[0], qubits[1])
    x.ctrl(qubits[1], qubits[2])
    ry(0.36, qubits[0])
    rz(0.69, qubits[0])
    rx(0.31, qubits[0])
    ry(-0.48, qubits[1])
    rz(0.28, qubits[1])
    rx(0.42, qubits[1])
    ry(0.62, qubits[2])
    rz(0.92, qubits[2])
    rx(0.46, qubits[2])


def draw_unfolded(kernel):
    """Return the text drawing of a kernel on one line, without wrapping."""
    separator = "\n\n" + "#" * 80 + "\n\n"
    pieces = [
        piece.strip("\n").split("\n") for piece in cudaq.draw(kernel).split(separator)
    ]
    rows = zip(*[[line.removesuffix("»") for line in piece] for piece in pieces])
    return "\n".join("".join(row) for row in rows)


cudaq.set_target("qpp-cpu")
print(draw_unfolded(ansatz))
```

         ╭──────────╮ ╭───────────╮╭──────────╮     ╭──────────╮╭──────────╮ ╭──────────╮                  ╭──────────╮╭──────────╮ ╭──────────╮            
    q0 : ┤ ry(0.42) ├─┤ rz(-0.37) ├┤ rx(0.87) ├──●──┤ ry(0.81) ├┤ rz(0.17) ├─┤ rx(0.26) ├───────────────●──┤ ry(0.36) ├┤ rz(0.69) ├─┤ rx(0.31) ├────────────
         ├──────────┤ ├──────────┬╯├──────────┤╭─┴─╮╰──────────╯├──────────┴╮├──────────┤ ╭──────────╮╭─┴─╮╰──────────╯├──────────┴╮├──────────┤╭──────────╮
    q1 : ┤ ry(1.13) ├─┤ rz(0.58) ├─┤ rx(0.33) ├┤ x ├─────●──────┤ ry(-0.24) ├┤ rz(0.93) ├─┤ rx(0.19) ├┤ x ├─────●──────┤ ry(-0.48) ├┤ rz(0.28) ├┤ rx(0.42) ├
         ├──────────┴╮├──────────┤ ├──────────┤╰───╯   ╭─┴─╮    ├──────────┬╯├──────────┴╮├─────────┬╯╰───╯   ╭─┴─╮    ├──────────┬╯├──────────┤├──────────┤
    q2 : ┤ ry(-0.66) ├┤ rz(0.29) ├─┤ rx(0.47) ├────────┤ x ├────┤ ry(0.55) ├─┤ rz(-0.71) ├┤ rx(0.5) ├─────────┤ x ├────┤ ry(0.62) ├─┤ rz(0.92) ├┤ rx(0.46) ├
         ╰───────────╯╰──────────╯ ╰──────────╯        ╰───╯    ╰──────────╯ ╰───────────╯╰─────────╯         ╰───╯    ╰──────────╯ ╰──────────╯╰──────────╯


The cell below compiles the ansatz with both targets at the same `epsilon`.
Because the two targets partition a kernel into different synthesis units, the same `epsilon` doesn't guarantee the same whole-kernel error.
The Achieved error column, the measured whole-kernel error, is therefore the test of a fair comparison: a target that achieves a lower error with fewer resources is better on both counts.
The Runtime (sec) column is the time `cudaq.estimate_resources` takes to compile the kernel and count its gates.
Bold values mark the best result in each column; tied columns have no bold value.
The Factor of improvement row divides each gridsynth value by the `fo-synth-ftqc-clifford-t` value, so a factor above 1 means the Q-CTRL target is better in that column.

Note that the gridsynth target's output varies slightly each time it compiles a kernel, even with a fixed random seed.
Because `cudaq.estimate_resources` and `cudaq.get_unitary` each compile the kernel, that target's error and gate counts come from separate compilations and can change a little between runs of the notebook.
The `fo-synth-ftqc-clifford-t` target produces the same output every time.


```python
ansatz_ideal = ideal_unitary(ansatz)
epsilon = "8e-4"
vendors = {
    "fo-synth-ftqc-clifford-t": "Q-CTRL",
    "compiler-bench-ftqc-clifford-t": "NVIDIA",
}
results = {}
for target in vendors:
    cudaq.set_target(target, epsilon=epsilon)
    start = perf_counter()
    resources = cudaq.estimate_resources(ansatz)
    runtime = perf_counter() - start
    error = operator_error(ansatz_ideal, np.array(cudaq.get_unitary(ansatz)))
    results[target] = {
        "Achieved error": error,
        "T": resources.count("t"),
        "CNOT": resources.count_controls("x", 1),
        "Total Gates": resources.count(),
        "Runtime (sec)": runtime,
    }

formats = {
    "Achieved error": "{:.3e}",
    "T": "{}",
    "CNOT": "{}",
    "Total Gates": "{}",
    "Runtime (sec)": "{:.4f}",
}
table = [
    "| Synthesizer | Epsilon | " + " | ".join(formats) + " |",
    "| --- | --- |" + " ---: |" * len(formats),
]
for target, metrics in results.items():
    values = []
    for column, template in formats.items():
        value = template.format(metrics[column])
        others = [results[name][column] for name in results if name != target]
        # Bold a value only if it is strictly lower than every other target's value.
        if all(metrics[column] < other for other in others):
            value = f"**{value}**"
        values.append(value)
    synthesizer = f"`{target}` ({vendors[target]})"
    table.append(f"| {synthesizer} | {epsilon} | " + " | ".join(values) + " |")

# Divide each gridsynth value by the Q-CTRL value, so factors above 1 favor Q-CTRL.
qctrl = results["fo-synth-ftqc-clifford-t"]
nvidia = results["compiler-bench-ftqc-clifford-t"]
# Leave the CNOT cell blank, because both targets keep the same CNOTs.
factors = [
    "" if column == "CNOT" else f"**{nvidia[column] / qctrl[column]:.2f}×**"
    for column in formats
]
table.append("| **Factor of improvement** | | " + " | ".join(factors) + " |")

display(Markdown("\n".join(table)))
```


| Synthesizer | Epsilon | Achieved error | T | CNOT | Total Gates | Runtime (sec) |
| --- | --- | ---: | ---: | ---: | ---: | ---: |
| `fo-synth-ftqc-clifford-t` (Q-CTRL) | 8e-4 | **2.855e-03** | **226** | 4 | **598** | **0.0740** |
| `compiler-bench-ftqc-clifford-t` (NVIDIA) | 8e-4 | 4.578e-03 | 832 | 4 | 2181 | 0.2072 |
| **Factor of improvement** | | **1.60×** | **3.68×** |  | **3.65×** | **2.80×** |


Notice that at the same `epsilon`, `fo-synth-ftqc-clifford-t` achieves a lower whole-kernel error while using about a quarter as many T gates and total gates as the gridsynth target, with a shorter runtime.
Both targets keep the kernel's four CNOTs.
The gain comes from synthesizing each fused single-qubit run once, rather than decomposing it into several Z rotations and synthesizing each one separately.
Tightening the gridsynth target's `epsilon` lowers its error, but increases its T-count further.
The preferable result depends on your kernel and resource priorities: for kernels where each single-qubit run is a single Z rotation, the two targets synthesize the same units and give similar counts, so neither target is guaranteed to win for every kernel.

## Import into CUDA-Q Logical

The `fo_synth_cudaq.import_cudaq` function compiles a kernel with the same synthesis passes and imports the result into CUDA-Q Logical, which is in preview in CUDA-Q 0.16.
It returns a `cudaq.logical.compiler.Build` without executing the kernel, and doesn't depend on the current target.
Pass any kernel arguments after the kernel, and the synthesis tolerance as the keyword-only `precision` argument.
The `precision` argument is a number with the same meaning as the target's `epsilon`; always set it explicitly.

The cell below imports the first kernel and counts the logical operations in the resulting CUDA-Q Logical program.


```python
build = fo_synth_cudaq.import_cudaq(first_kernel, precision=1e-6)
logical_operations = Counter(re.findall(r"#qlx\.action<(\w+)>", build.to_mlir()))

print("Logical operations:", dict(logical_operations))
```

    Logical operations: {'z': 2, 'h': 223, 't': 221, 's': 112, 'cx': 1}


The logical operation counts match those of the `fo-synth-ftqc-clifford-t` target at `epsilon="1e-6"` above, because `import_cudaq` runs the same synthesis passes.
You can inspect the full CUDA-Q Logical program with `build.to_mlir()`.

## Recognize unsupported inputs

The `import_cudaq` function doesn't support kernels that call other kernels, and raises a `ValueError` for them.
The `fo-synth-ftqc-clifford-t` target supports such kernels, so use the target to compile, run, or count resources for them instead.


```python
@cudaq.kernel
def rotate(qubit: cudaq.qubit):
    ry(0.4, qubit)


@cudaq.kernel
def caller():
    qubits = cudaq.qvector(2)
    rotate(qubits[0])
    x.ctrl(qubits[0], qubits[1])


try:
    fo_synth_cudaq.import_cudaq(caller, precision=1e-6)
except ValueError as error:
    print(f"ValueError: {error}")

cudaq.set_target("fo-synth-ftqc-clifford-t", epsilon="1e-6")
print("Target resources:", cudaq.estimate_resources(caller).to_dict())
```

    ValueError: Kernel 'caller' calls another kernel, which import_cudaq does not support. Inline the called kernel, or use the fo-synth-ftqc-clifford-t target.
    Target resources: {'s': 29, 'h': 59, 't': 59, 'cx': 1}


## Choose settings for your own kernel

You have now learned how to create QEC-ready CUDA-Q kernels with the Fire Opal Clifford+T synthesizer! In particular, you have learned:
- How to select the `fo-synth-ftqc-clifford-t` target and pass `epsilon` as a string.
- How to choose a per-unitary `epsilon` that accounts for your kernel's error budget.
- How to compare the synthesizer with CUDA-Q's gridsynth target by the whole-kernel error each achieves and the resources each uses.
- How to import a synthesized kernel into CUDA-Q Logical with `import_cudaq`, and when to use the target instead.

You should now be ready to try the synthesizer out on your own kernels. Or, to explore performance beyond the examples here, use our `fo-synth-benchmarks` package to test the Fire Opal synthesizer against a broad variety of synthesis targets.
Follow the [Benchmark Clifford+T synthesis](https://docs.q-ctrl.com/fire-opal/ftqc/compile/benchmark-cliffordt-synthesis.md) tutorial to compare synthesis runtime and T-counts across targets.
