Synthesize Qiskit circuits to Clifford+T
Explore optimized synthesis strategies with fo-synth-qiskit
Fault-tolerant algorithms often require decomposing arbitrary unitary operations, such as rotations, using a restricted discrete gate set. The fo-synth-qiskit package performs optimized synthesis to approximate those operations with Clifford+T circuits containing native H, S, T, X, 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 synthesize a small circuit, supply equivalent Qiskit and OpenQASM inputs, and measure how approximation tolerance and compilation strategy change the result.
Install and import the package
Use Python 3.11 or newer and install the package in the Python environment used by your Jupyter kernel:
pip install fo-synth-qiskitIf not already present in your environment, the package installs Qiskit and the OpenQASM 3 importer as dependencies. Restart the kernel if you installed or upgraded packages while it was running.
import warnings
from pathlib import Path
from tempfile import TemporaryDirectory
from time import perf_counter
import numpy as np
from fo_synth_qiskit import (
SynthesisStrategy,
UnsupportedOperationWarning,
synthesize_clifford_t,
)
from qiskit import QuantumCircuit, qasm2, qasm3
from qiskit.circuit import Parameter
from qiskit.quantum_info import OperatorSynthesize your first circuit
The synthesize_clifford_t function is the entry point for synthesis. It has three arguments:
| Argument | Accepted values | Meaning |
|---|---|---|
circuit | A QuantumCircuit, OpenQASM 2 or 3 source string, or path-like object | The circuit to compile |
tolerance | A number in (0, 1]; default 1e-6 | Maximal allowed distance between the synthesized unitary and the ideal operation, in terms of the operator norm |
strategy | SynthesisStrategy.SU2 or SynthesisStrategy.SU4, or strings "su2" or "su4"; default SynthesisStrategy.SU2 | Selects single-qubit synthesis or combined two-qubit-block synthesis |
Only circuit is required.
You can supply circuit and tolerance positionally or by keyword, but strategy is keyword-only.
Start with a numeric single-qubit U gate.
Its three angles are in radians.
Calling the function without optional arguments uses tolerance 1e-6 and the SU(2) strategy.
circuit = QuantumCircuit(1)
circuit.u(0.5, 0.7, -0.3, 0)
original_circuit = circuit.copy()
default_result = synthesize_clifford_t(circuit)
print("Input operations:", dict(circuit.count_ops()))
print("Output operations:", dict(default_result.count_ops()))
print("Input unchanged:", circuit == original_circuit)
print("New circuit returned:", default_result is not circuit)Input operations: {'u': 1}
Output operations: {'h': 54, 't': 50, 's': 28}
Input unchanged: True
New circuit returned: True
The returned object is a new QuantumCircuit on the original wires, where the U gate has been replaced by individual native gates.
The synthesizer also tracks global phase in the output circuit's global_phase attribute.
Measure approximation error
The tolerance argument to synthesize_clifford_t provides an upper bound to operator-norm error minimized over global phase.
The operator norm of a matrix is its largest singular value.
For the difference between a target unitary
For the single-qubit unitaries considered here, the average gate infidelity
where the approximation holds for small errors and
The helper below 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 this diagnostic only for small, fully bound unitary circuits: constructing a full circuit matrix scales exponentially with qubit count and is not appropriate for measurements, resets, or dynamic control flow.
def operator_error(target, result):
"""Return the operator-norm distance between unitaries up to global phase."""
target_matrix = Operator(target).data
result_matrix = Operator(result).data
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))
print(f"Default-call error: {operator_error(circuit, default_result):.3e}")Default-call error: 9.731e-07
Supply OpenQASM inputs
The synthesize_clifford_t function also accepts OpenQASM 2 and OpenQASM 3 source strings, as shown below.
qasm_sources = {"OpenQASM 2": qasm2.dumps(circuit), "OpenQASM 3": qasm3.dumps(circuit)}
source_results = {}
for label, source in qasm_sources.items():
result = synthesize_clifford_t(circuit=source, tolerance=1e-3)
source_results[label] = result
print(f"{label} source error: {operator_error(circuit, result):.3e}")OpenQASM 2 source error: 8.497e-04
OpenQASM 3 source error: 8.497e-04
Instead of a source string, you can supply a pathlib.Path or another os.PathLike object pointing to a .qasm source file.
Note that a plain string such as "circuit.qasm" is interpreted as QASM source, not as a filename, and fails header validation.
Files must contain UTF-8 OpenQASM 2 or 3 source with the appropriate header.
This example creates and automatically removes temporary files; substitute the path to your own file in a real workflow.
file_results = {}
with TemporaryDirectory() as directory:
for label, source in qasm_sources.items():
qasm_path = Path(directory) / "circuit.qasm"
qasm_path.write_text(source, encoding="utf-8")
result = synthesize_clifford_t(qasm_path, tolerance=1e-3)
file_results[label] = result
print(f"{label} file error: {operator_error(circuit, result):.3e}")OpenQASM 2 file error: 8.497e-04
OpenQASM 3 file error: 8.497e-04
Trade approximation accuracy for synthesis cost
Smaller tolerance 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 synthesize the same single-qubit target with four tolerances.
tolerance_results = {}
print(
f"{'Tolerance':>10} {'Error':>11} {'T':>5} {'Gates':>7} {'Depth':>7} {'Seconds':>9}"
)
for tolerance in [1e-2, 1e-3, 1e-4, 1e-6]:
start = perf_counter()
result = synthesize_clifford_t(circuit, tolerance)
elapsed = perf_counter() - start
tolerance_results[tolerance] = result
counts = result.count_ops()
error = operator_error(circuit, result)
print(
f"{tolerance:10.0e} {error:11.3e} {counts.get('t', 0):5d} "
f"{result.size():7d} {result.depth():7d} {elapsed:9.4f}"
) Tolerance Error T Gates Depth Seconds
1e-02 8.798e-03 15 46 46 0.0019
1e-03 8.497e-04 27 76 76 0.0010
1e-04 9.814e-05 37 102 102 0.0018
1e-06 9.731e-07 50 132 132 0.0017
Notice how tightening the error target changes the T-count and depth, not just the error column.
Tolerance is not a whole-circuit error budget.
For a full circuit, a conservative bound is N * tolerance, where N is the number of single-qubit runs and two-qubit blocks actually sent to synthesis after decomposition and collection.
It is not the number of input gates or emitted Clifford+T instructions.
If you know your circuit contains N unitaries to synthesize and require a circuit bound of epsilon, choose a per-unit tolerance no greater than epsilon / N.
For example, ten synthesized unitaries at tolerance 1e-4 give a conservative full-circuit bound of 1e-3, not 1e-4.
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 QEC error per cycle ~1e-20 could take advantage of such accurate synthesis, whereas current long-term projections for achievable error per cycle are larger.
Compare synthesis strategies
The default strategy="su2" decomposes supported operations into CNOT and single-qubit U gates, merges adjacent single-qubit runs, and synthesizes those runs.
The CNOT structure produced by decomposition is retained.
With strategy="su4", the synthesizer collects numeric two-qubit blocks and synthesizes them jointly, using SU(2) for remaining single-qubit runs.
Joint synthesis can change CNOT structure inside those blocks, creating a different resource tradeoff.
A two-qubit block counts as one synthesized unitary for tolerance accounting.
Both strategies accept multi-qubit circuits. The distinction is the size of the blocks synthesized, not the number of qubits in the input circuit.
To illustrate, the example below has three non-native interactions on the same pair of qubits so that there is a genuine two-qubit region to collect. Note that the tolerance applies to each synthesized block, and the strategies partition the circuit differently. We therefore choose their tolerances independently to obtain approximately equal measured whole-circuit errors, then compare the required resources.
interactions = QuantumCircuit(2)
interactions.rxx(0.31, 0, 1)
interactions.ryy(-0.29, 0, 1)
interactions.rzz(0.17, 0, 1)
strategy_tolerances = {SynthesisStrategy.SU2: 3.2e-4, SynthesisStrategy.SU4: 1e-3}
strategy_results = {}
print(
f"{'Strategy':>8} {'Tolerance':>11} {'Error':>11} {'T':>5} {'CX':>5} "
f"{'Gates':>7} {'Depth':>7} {'Seconds':>9}"
)
for strategy, tolerance in strategy_tolerances.items():
start = perf_counter()
result = synthesize_clifford_t(interactions, tolerance=tolerance, strategy=strategy)
elapsed = perf_counter() - start
strategy_results[str(strategy)] = result
counts = result.count_ops()
error = operator_error(interactions, result)
print(
f"{strategy:>8} {tolerance:11.3e} "
f"{error:11.3e} {counts.get('t', 0):5d} "
f"{counts.get('cx', 0):5d} {result.size():7d} {result.depth():7d} {elapsed:9.4f}"
)Strategy Tolerance Error T CX Gates Depth Seconds
su2 3.200e-04 5.297e-04 101 6 288 282 0.0073
su4 1.000e-03 4.915e-04 101 4 277 184 0.0114
Notice that in this case, the SU(4) strategy produces a lower whole-circuit error, CNOT count, overall gate count, and depth, at the cost of higher runtime. The preferable result depends on your circuit, architecture, and resource priorities; neither strategy is guaranteed to win for every circuit.
Preserve existing native gates
The SU(4) strategy preserves original native H, S, T, X, and CX instructions, including in mixed circuits and control-flow bodies. Consequently, a circuit that is already entirely native retains its T-count and CNOT count exactly, as shown below.
native = QuantumCircuit(2)
native.h(0)
native.t(1)
native.cx(0, 1)
native.s(0)
native.x(1)
preserved = synthesize_clifford_t(native, strategy="su4")
print("Before:", dict(native.count_ops()))
print("After: ", dict(preserved.count_ops()))
print("Circuit preserved:", preserved == native)Before: {'h': 1, 't': 1, 'cx': 1, 's': 1, 'x': 1}
After: {'h': 1, 't': 1, 'cx': 1, 's': 1, 'x': 1}
Circuit preserved: True
Preserved native instructions also form collection boundaries on the wires they touch. For example, an original native CX separating two non-native regions is not absorbed to make one larger SU(4) block.
Recognize and resolve incomplete synthesis
A successful return does not always mean every operation is Clifford+T.
For example, a rotation with an unbound parameter cannot be numerically approximated.
Its symbolic U representation remains in the output, and the synthesizer emits UnsupportedOperationWarning.
Capture and display that expected warning so you can inspect the incomplete result.
theta = Parameter("theta")
parameterized = QuantumCircuit(1)
parameterized.ry(theta, 0)
with warnings.catch_warnings(record=True) as caught:
warnings.simplefilter("always", UnsupportedOperationWarning)
incomplete = synthesize_clifford_t(parameterized, tolerance=1e-3)
for warning in caught:
print(f"{warning.category.__name__}: {warning.message}")
print("Remaining parameters:", [str(value) for value in incomplete.parameters])
print("Output operations:", dict(incomplete.count_ops()))UnsupportedOperationWarning: Output contains unsupported operations: u
Remaining parameters: ['theta']
Output operations: {'u': 1}
After binding the parameter to an angle in radians, you can proceed with synthesis.
bound = incomplete.assign_parameters({theta: 0.31})
complete = synthesize_clifford_t(bound, tolerance=1e-3)
print("Remaining parameters:", list(complete.parameters))
print("Output operations:", dict(complete.count_ops()))
print(f"Bound-circuit error: {operator_error(bound, complete):.3e}")Remaining parameters: []
Output operations: {'t': 30, 'h': 29, 's': 18, 'x': 1}
Bound-circuit error: 6.511e-04
Opaque operations without a usable decomposition or matrix can also remain unsynthesized.
Under either strategy, the function emits one UnsupportedOperationWarning per call listing the unique unsupported operation names, including those in nested control-flow bodies.
Measurements, resets, barriers, and delays are passed through unchanged.
Control-flow conditions and structure are retained, and bodies are synthesized recursively using the selected strategy.
If your circuits contain any such non-unitary operations, they are not suitable for analysis with the operator_error helper function defined above.
Choose settings for your own circuit
You have now learned how to create QEC-ready circuits with the Fire Opal Clifford+T synthesizer! In particular, you have learned:
- How to supply a bound
QuantumCircuit, QASM source, or a QASMPathaccording to where your circuit originates. - How to choose a per-unitary
tolerancethat accounts for your circuit's error budget. - How to modify the synthesis
strategy, and the resource tradeoff that it creates. - How to check unsupported-operation warnings to verify that the returned circuit is fully synthesized.
You should now be ready to try the synthesizer out on your own circuits. 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 tutorial to compare synthesis runtime and T-counts across targets.
