How Does The Qiskit Transpiler Work?
Tags: Open Source, Quantum Computing, Python, Explainer, Qiskit

By Eric Michiels

If you hope to run a quantum program on real quantum hardware, then transpilation is critical. The transpiler rewrites an abstract quantum circuit into a functionally equivalent one that matches the constraints and characteristics of a specific target quantum device. It’s a cornerstone for quantum computing today — so it’s important for the quantum-interested to understand how it works.

Not only is transpilation essential, but it also ensures that our quantum circuits run as efficiently as possible on any quantum computing architecture, so that our code can take advantage of rapidly evolving hardware and software technologies. The science of transpilation is also an ongoing area for software, mathematics, physics, and computer architecture research.

“Developing and evolving the transpiler is an exciting project”, says Kevin Krsulich, Lead Quantum Software Engineer at IBM Quantum, “giving rise to a variety of challenges and requiring a rich set of complementary skills.”

Quantum algorithm developers create quantum circuits using a set of abstract, device-agnostic quantum gates to represent and solve a problem. However, real quantum devices can only execute a limited set of hardware-specific, physically calibrated quantum gates. As such, quantum computation requires translation from the human-defined gates into machine-compatible gates, optimizing the performance where possible. Moreover, the target device may have practical constraints such as the connectivity between its qubits, while we must also compensate for the effects of noise, decoherence, and errors.

But why do we call it transpilation? “As the outcome of this translation flow results in the same level of programming language, the term transpilation is more appropriate than compilation”, says Nick Bronn, IBM Research Staff Member for Experimental Quantum Computing. “Transpilation results in an equivalent circuit, meaning that the unitary implementing the transpiled circuit would be identical to the unitary of the original circuit, but with the transpiled circuit being physically realizable with the quantum hardware. The probabilistic outcomes of the measurements of both circuits will be the same.”

As such, transpilation comes with two key components. The first is establishing compatibility, which translates a quantum circuit into an equivalent one that is executable on a specific device and that preserves the same measurement outcomes. Second, the optimization step finds an implementation which takes maximal advantage of target device resources, while minimizing the impact of decoherence and errors.

The compatibility step has several important roles. If the developer defines custom instructions, then Qiskit rewrites them using the standard virtual gate set. Next, the transpiler rewrites the virtual circuit using the native gate set of the target device, and maps the specified virtual qubits used in the circuit onto the hardware’s native qubits. If the developer’s circuit employs two-qubit gates defined for not-connected native qubits, then the transpiler resolves this issue by adding SWAP operations. As each SWAP operation significantly increases the overall noise, the transpiler tries to add a minimum number of additional SWAP operations. The transpiler considers the device architecture, differentiating between, for example, superconducting and ion trap quantum computers, and also considers specific device characteristics.

The optimization step occurs following two complementary approaches. The first step, named “logical reductions,” removes pairs of gates that are each other’s inverse and logically result in a zero operation, makes chains of multiple single qubit gates more compact, and analyses the commutation possibilities of gates — potentially leading to further gate cancellations. The second step, called “device-specific reductions,” leverages the noise information of a given device by selecting a layout of qubits that has a favorable noise profile, synthesizes collections of gates applied to neighboring qubits, and reduces crosstalk and decoherence. Crosstalk occurs when multiple instructions are executed in parallel and corrupt the quantum state, leading to incorrect program execution, and it is a major source of noise in today’s quantum devices. Through Crosstalk Adaptive Scheduling, the transpiler finds an optimal instruction schedule that maximizes fidelity.

Qiskit offers several tools for quantum developers hoping to experiment with transpilation themselves, which you can learn more about in the Qiskit documentation here. First, the basis_gates parameter allows developers to deviate from the default device’s built-in gates. Next, there are many possible ways to map virtual qubits onto the physical qubits. “This choice can dramatically impact the overall depth of the transpiled circuit by up to a factor of 10”, said Krsulich. The tandem of settings initial_layout and layout_method are the popular levers for changing this mapping. The former redefines the physical qubit numbering. The latter specifies which connection pattern is applied, and its options include a trivial one-to-one mapping, a dense connected subset of physical connected qubits, and a noise adaptive approach which tries to minimize the total accumulated readout and two-qubit errors. Quantum developers can influence the routing stage as well, or how the transpiler extends the circuit with additional SWAP gates in order to effectively perform two-qubit gates. The routing_method keyword defines the applied tactic: the greedy basic method inserts any needed SWAP gates to execute the next 2-qubit gate, lookahead apples a search algorithm to find the best SWAPs to be inserted while reducing the number of layers and associated costs, and stochastic deepens the search to apply the most optimal SWAP gates.

“One of our key objectives is easing the experimentation efforts by researchers and quantum hardware providers”, said Krsulich. “Of course, full support for the new OpenQASM 3.0 standard is the ambition as well, supporting functions like classical control flows, explicit timing and embedded pulse-level definitions for example”.

As often is the case in development, there is a conflict between the richness of options and associated controls on one hand and making the technology consumable on the other hand. The Qiskit transpiler provides a compromise via its optimization levels. There are 4 levels, from 0 to 3, and the higher its value, the more time Qiskit is going to spend in finding an optimal implementation of the original circuit, often characterized by higher fidelity and lower depth. A longer classical transpilation time is the tax we pay for the sake of faster and more accurate quantum circuit execution. Optimization level 0 indicates that no optimization must be done and is typically used for characterization experiments or error amplification assessments, such as if one wanted to examine the error rate of 10 consecutive SX or SQRT(X) gates on one qubit. Higher optimization levels include the optimizations applied within the lower levels. Smart weapons such as changing the device layout, commutation of qubits in the virtual circuit, adjacent gate cancellations, and complete gate block resynthesis live in the optimization levels’ arsenal.

If you transpiled a variety of circuits with different optimization levels, then you will see a general trend that the transpilation time increases as the optimization level increases. It may occur that the optimization level 0 process is slower than optimization level 1 process, because the latter finds a gate compaction approach that benefits the rest of the process stages and passes. Though circuit depth will generally decrease with an increasing optimization level, there are cases where depth is not reduced any more after a certain level, as Kuba Pilch found in his blog.

There are plenty of other places for experimentation with transpilation. For example, there’s partial transpilation for parameterized circuits. Researchers can use the seed_transpiler parameter to try to generate reproducible and deterministic transpiler outcomes for repeatable experiments. Developers can also consult the disassembler tool to know exactly how the transpiled circuit looked when it reached the device. One can even generate a log of the passes run and visualize it with built-in Python logging tools. The “icing on the cake” is the Direct Acyclic Graph (DAG) visualization, which provides a graphical representation for deeper inspection pass after pass. Developers can even build a custom “callback” function to implement a kind of pause option.

The transpilation can take place at several locations, explained Bronn. If you installed Qiskit locally to run Jupyter Notebooks that access quantum devices, the transpilation runs on your laptop. When you use the IBM Quantum Lab environment, it runs on a classical server in the IBM Cloud. A smart flavor of the latter comes with the recent Qiskit Runtime. This execution model is invented for algorithms that require many iterations of combined circuit executions and classical processing and supports transpilation in this Runtime environment as well.

For those sending jobs to quantum hardware and concerned about the time transpilation takes, transpilation does not affect the sequencing of the job in the queuing system of the selected target device, since transpilation happens before the job goes to the backend. Research might soon happen on real-time circuit optimization as well, said Bronn. Optimizing transpilation time is especially important for use cases requiring iteration between quantum and classical processing, such as with Variational Quantum Eigensolvers (VQE). For now, partially transpiled circuits can play a key role in speedup, here.

“Look at the recent new architecture provided by Qiskit Runtime, which allows for tremendous performance gains when computations need to cycle through many iterations in a hybrid quantum-classical process. Partially transpiled quantum circuits can be uploaded close to the quantum device, for usage by the developers themselves or other authorized users, after passing required any parameters,” said Krsulich.

Circuit transpilation is an exciting, ongoing research journey. For example, the team has recently been working on template optimization, which allows one to express subcircuits closer to the native interaction between superconducting qubits, and which allows us to re-express these subcircuits in terms of ZX rotations, said Bronn. These rotations are generated by the cross-resonance interaction between qubits and are then substituted by scaled pulse schedules.

Looking forward, the team is thinking about the evolution from the physical qubits today to the creation of logical qubits using quantum error correction in the future. Where and how will transpilation fit in this process? And, perhaps one day, the transpiler could select the best fitting target quantum computer autonomously, based on the input circuit, from an ensemble of available target devices. We’re looking forward to seeing the transpiler’s evolution alongside quantum computers generally.

Want to read more stories like these? Visit the Qiskit Medium homepage and click Follow.