Skip to content

Lesson 44: TKET / pytket, XACC and ProjectQ

44.1 Learning Outcomes

By the end of this hour a student will be able to:

  1. Explain the compiler-first design philosophy behind TKET.
  2. Use pytket passes to optimise circuits and interoperate with other SDKs.
  3. Describe XACC's service-oriented architecture and its HPC role.
  4. Describe ProjectQ's compiler-engine pipeline and its pedagogical value.
  5. Choose a compilation toolchain and quantify the benefit.

44.2 TKET / pytket — Compilation as the Product

Quantinuum's TKET is written in C++ with a Python interface (pytket). Its premise is that on NISQ hardware, two-qubit gate count is the binding constraint, so the compiler — not the SDK — is where the value lies.

TKET is retargetable and SDK-agnostic: you can write a circuit in Qiskit, optimise it with TKET, and run it on IonQ.

Installation

pip install pytket
pip install pytket-qiskit pytket-cirq pytket-braket pytket-quantinuum

Basic use

from pytket import Circuit
from pytket.extensions.qiskit import AerBackend

c = Circuit(2, 2)
c.H(0).CX(0, 1).measure_all()

backend = AerBackend()
compiled = backend.get_compiled_circuit(c)
result = backend.run_circuit(compiled, n_shots=1000)
print(result.get_counts())

Interoperability — TKET's practical superpower

from pytket.extensions.qiskit import qiskit_to_tk, tk_to_qiskit
from pytket.extensions.cirq  import cirq_to_tk, tk_to_cirq
from pytket.qasm import circuit_from_qasm, circuit_to_qasm

tk_circ = qiskit_to_tk(qiskit_circuit)      # import from Qiskit
# ... optimise with TKET ...
qiskit_circ = tk_to_qiskit(tk_circ)         # export back
\[ \boxed{\ \text{Write in your favourite SDK} \ \to\ \text{optimise with TKET} \ \to\ \text{run anywhere.}\ } \]

Optimisation passes

from pytket.passes import (FullPeepholeOptimise, CliffordSimp, RemoveRedundancies,
                           SequencePass, DecomposeBoxes, PauliSimp,
                           SynthesiseTket, KAKDecomposition)

FullPeepholeOptimise().apply(c)     # the general-purpose workhorse
CliffordSimp().apply(c)             # resynthesise Clifford subcircuits
PauliSimp().apply(c)                # exponentiated-Pauli resynthesis (chemistry, QAOA)
RemoveRedundancies().apply(c)       # cancel adjacent inverses
KAKDecomposition().apply(c)         # optimal 2-qubit resynthesis (<= 3 CNOTs)

custom = SequencePass([DecomposeBoxes(), FullPeepholeOptimise(), CliffordSimp()])
custom.apply(c)

The most important passes.

Pass What it does Typical CX saving
RemoveRedundancies cancels \(GG^\dagger\) pairs 5–15 %
KAKDecomposition any 2-qubit unitary → at most 3 CNOTs (provably optimal) 10–30 %
CliffordSimp resynthesises Clifford blocks 15–40 %
PauliSimp reorders and merges \(e^{i\theta P}\) terms 30–60 % on chemistry/QAOA
FullPeepholeOptimise applies a curated sequence of the above 20–50 %

PauliSimp deserves special mention. Chemistry (UCCSD, Trotterised Hamiltonians) and QAOA circuits consist almost entirely of exponentiated Pauli strings \(e^{i\theta P}\). PauliSimp reorders commuting terms and merges their CNOT ladders, which is why TKET's advantage is largest exactly where circuits matter most.

Architecture-aware routing

from pytket.architecture import Architecture
from pytket.passes import DefaultMappingPass, RoutingPass
from pytket.placement import GraphPlacement

arch = Architecture([(0,1), (1,2), (2,3), (3,4)])      # a line
DefaultMappingPass(arch).apply(c)

TKET's routing consistently inserts fewer SWAPs than competitors in published benchmarks — the main source of its measured advantage.

44.3 XACC — Quantum Computing for HPC

Oak Ridge National Laboratory's XACC (eXtreme-scale ACCelerator) treats a QPU as an accelerator attached to a classical supercomputer, exactly as XACC's designers treat GPUs.

The service-oriented architecture

   Application  (C++ / Python)
        |
   XACC Framework
    /   |     |    \
Compilers  IRTransformations  Accelerators  Observables
    |         |                   |
 XASM      optimisation      IBM, Rigetti,
 Quil,                       IonQ, TNQVM,
 OpenQASM                    simulators

Every component is a plugin discovered at runtime, so a new backend is added without touching application code.

Example

import xacc

qpu = xacc.getAccelerator('aer', {'shots': 1024})
buf = xacc.qalloc(2)

xacc.qasm('''
.compiler xasm
.circuit bell
.qbit q
H(q[0]);
CX(q[0], q[1]);
Measure(q[0]);
Measure(q[1]);
''')

bell = xacc.getCompiled('bell')
qpu.execute(buf, bell)
print(buf.getMeasurementCounts())

Where XACC matters

  • C++ first, so it links directly into existing HPC simulation codes (NWChem, LAMMPS).
  • MPI-aware, so quantum tasks can be distributed across a cluster.
  • TNQVM — a tensor-network simulator that scales to hundreds of qubits on supercomputers.
  • Embedded QPU calls inside classical simulations — for example, a molecular-dynamics code calling a VQE for the electronic-structure step.

XACC's users are national laboratories, not individual researchers. It is the right answer when the quantum computation is one step inside a large classical HPC workflow.

44.4 ProjectQ — The Teaching Compiler

ETH Zürich's ProjectQ (Steiger, Häner, Troyer, 2018) is small, readable and beautifully structured. Its lasting contribution is the compiler-engine pipeline.

The engine list

from projectq import MainEngine
from projectq.ops import H, CNOT, Measure, All
from projectq.backends import Simulator
from projectq.setups import restrictedgateset

eng = MainEngine(backend=Simulator(),
                 engine_list=[TagRemover(), LocalOptimizer(5),
                              AutoReplacer(rule_set), InstructionFilter(...)])

q = eng.allocate_qureg(2)
H | q[0]
CNOT | (q[0], q[1])
All(Measure) | q
eng.flush()
print(int(q[0]), int(q[1]))

The | operator for gate application (H | qubit) is ProjectQ's distinctive syntax, echoing Dirac notation.

The pipeline concept

User code -> Engine1 -> Engine2 -> ... -> Backend
              (tag)    (optimise)         (simulator/hardware)

Each engine receives a stream of commands, transforms it, and forwards it. Compilation happens while you write, not as a separate step — which makes the compilation process unusually visible and is exactly why ProjectQ is such a good teaching tool.

Its historical significance. ProjectQ demonstrated the modular compiler-engine architecture that Qiskit's PassManager and TKET's pass system both later adopted. Development has slowed, so it is now recommended for understanding how compilers work, not for production.

44.5 Comparative Summary

Framework Origin Language Killer feature Use when
pytket / TKET Quantinuum C++/Python best-in-class optimisation you need every CNOT saved
XACC ORNL C++/Python HPC integration quantum inside a classical HPC workflow
ProjectQ ETH Zürich Python readable compiler pipeline teaching compiler internals
Qiskit IBM Python ecosystem general use
Cirq Google Python hardware transparency device research

44.6 Solved Problems

Problem 1 — Measuring TKET's optimisation benefit

A 6-qubit UCCSD chemistry circuit has 320 CNOTs after naive compilation. Estimate the CNOT count after TKET's FullPeepholeOptimise and PauliSimp, and compute the fidelity improvement at \(\epsilon_{\text{CX}} = 8\times10^{-3}\).

Solution.

Baseline.

\[ F_{\text{naive}} = (1 - 0.008)^{320} = 0.992^{320} = e^{320\ln0.992} = e^{-2.5697} = \mathbf{0.0766} \]

7.7 % fidelity — the circuit is unusable.

After FullPeepholeOptimise (typical 35 % CNOT reduction):

\[ 320\times0.65 = 208\ \text{CNOTs} \]
\[ F = 0.992^{208} = e^{-1.670} = \mathbf{0.1882} \]

After PauliSimp as well (UCCSD is entirely exponentiated Paulis — typical 50 % total reduction):

\[ 320\times0.50 = 160\ \text{CNOTs} \]
\[ F = 0.992^{160} = e^{-1.285} = \mathbf{0.2767} \]

Summary.

Compilation CNOTs Fidelity Improvement
Naive 320 0.0766 1.0×
FullPeepholeOptimise 208 0.1882 2.5×
+ PauliSimp 160 0.2767 3.6×

Why a 3.6× fidelity gain matters so much. Estimating an observable to precision \(\epsilon\) requires shots scaling as \(1/(F^2\epsilon^2)\) — the signal is attenuated by \(F\), so the variance penalty goes as \(F^{-2}\):

\[ \frac{S_{\text{naive}}}{S_{\text{optimised}}} = \left(\frac{0.2767}{0.0766}\right)^{2} = 3.61^{2} = \mathbf{13\times} \]
\[ \boxed{\ \textbf{A 50 \% CNOT reduction cuts the shot budget — and the cost — by }13\times.\ } \]

On Braket's IonQ pricing (L41), a $13 000 experiment becomes a $1 000 experiment. The compiler pays for itself immediately.

Problem 2 — Cross-framework workflow

Write a workflow that builds a circuit in Qiskit, optimises it with TKET, and runs it on IonQ via Braket. Explain each step's rationale.

Solution.

# ---------- 1. BUILD in Qiskit (best ecosystem, familiar syntax) ----------
from qiskit import QuantumCircuit
import numpy as np

qc = QuantumCircuit(4)
qc.h(range(4))
for i in range(3):
    qc.cx(i, i+1)
    qc.rz(np.pi/4, i+1)
    qc.cx(i, i+1)
qc.measure_all()
print("Qiskit CX count:", qc.count_ops().get('cx', 0))     # 6

# ---------- 2. OPTIMISE with TKET (best compiler) ----------
from pytket.extensions.qiskit import qiskit_to_tk, tk_to_qiskit
from pytket.passes import FullPeepholeOptimise, PauliSimp, SequencePass

tk = qiskit_to_tk(qc)
print("TKET CX before:", tk.n_gates_of_type(OpType.CX))
SequencePass([PauliSimp(), FullPeepholeOptimise()]).apply(tk)
print("TKET CX after :", tk.n_gates_of_type(OpType.CX))

# ---------- 3. RUN on IonQ via Braket (best fidelity + all-to-all) ----------
from pytket.extensions.braket import BraketBackend

backend = BraketBackend(device="Aria-1", region="us-east-1",
                        s3_bucket="my-bucket", s3_folder="results")
compiled = backend.get_compiled_circuit(tk)      # final device-specific compilation
handle = backend.process_circuit(compiled, n_shots=1000)
print(backend.get_result(handle).get_counts())

Rationale for each step.

Step Tool Why
Build Qiskit largest ecosystem, most familiar to students, best documentation
Optimise TKET independently benchmarked as the strongest optimiser; PauliSimp targets exactly this circuit's \(e^{i\theta ZZ}\) structure
Run IonQ via Braket all-to-all connectivity means zero SWAPs; IonQ's native \(ZZ\) gate matches the circuit

Expected result on this circuit. The pattern CX, Rz, CX is exactly \(e^{-i\theta Z\otimes Z/2}\) (L34 §2.3). PauliSimp recognises the three such blocks, notes that adjacent ones share a qubit and their CNOT ladders can be merged, and reduces the CNOT count from 6 to 4.

\[ F: (0.996)^{6} = 0.976 \ \longrightarrow\ (0.996)^{4} = 0.984 \]

Modest here because the circuit is tiny; on a full 20-qubit UCCSD circuit the same pass saves hundreds of CNOTs.

The general principle.

\[ \boxed{\ \textbf{The frameworks are interoperable. Use each where it is strongest — that is the professional workflow.}\ } \]

Problem 3 — Understanding the KAK decomposition bound

Explain why any two-qubit unitary needs at most 3 CNOTs, and compute the saving when a naive compilation used 6.

Solution.

The parameter-counting argument.

\(SU(4)\) — the group of two-qubit unitaries up to global phase — has dimension

\[ \dim SU(4) = 4^{2} - 1 = \mathbf{15\ \text{real parameters}} . \]

A circuit of \(k\) CNOTs interleaved with arbitrary single-qubit gates provides:

  • Single-qubit gates: \(2(k+1)\) of them (a layer before each CNOT and one after), each contributing 3 parameters — but global phases and commuting phases reduce the independent count.
  • The standard counting gives: with \(k\) CNOTs you can reach at most \(3\times2(k+1) - (\text{redundancies})\) parameters.

The precise result (Vidal–Dawson, Vatan–Williams, 2004):

CNOTs Parameters reachable Covers \(SU(4)\)?
0 6 no (product unitaries only)
1 9 no
2 12 no
3 15 yes — exactly enough
\[ \boxed{\ \textbf{Any two-qubit unitary decomposes into at most 3 CNOTs, and this is tight.}\ } \]

The constructive form (KAK / Cartan decomposition).

\[ U = (A_1\otimes A_2)\,\exp\!\big(i(c_1 XX + c_2 YY + c_3 ZZ)\big)\,(B_1\otimes B_2) \]

where \(A_i, B_i \in SU(2)\) and the central "canonical" part needs exactly 3 CNOTs in general — and fewer in special cases: 2 CNOTs if one \(c_i = 0\), 1 CNOT if two vanish, 0 if all three do.

The saving from 6 to 3.

\[ \text{CNOT reduction} = 50\% \]

At \(\epsilon_{\text{CX}} = 10^{-2}\):

\[ F_{6} = 0.99^{6} = 0.9415, \qquad F_{3} = 0.99^{3} = 0.9703 \]
\[ \text{error reduction} = \frac{1 - 0.9415}{1 - 0.9703} = \frac{0.0585}{0.0297} = \mathbf{1.97\times} \]

Where this arises in practice. Any circuit containing arbitrary two-qubit blocks — a variational ansatz with cirq.MatrixGate on pairs, a compiled Hamiltonian evolution, a decomposed Toffoli. TKET's KAKDecomposition pass finds the optimal form automatically. A naive decomposition routinely uses 6–9 CNOTs where 3 suffice.

Problem 4 — Designing an HPC-integrated workflow with XACC

A materials-science group runs classical DFT on a supercomputer and wants to replace the strongly-correlated part with a VQE. Design the XACC workflow.

Solution.

The scientific setup. Density functional theory handles most of a material's electrons well but fails for strongly correlated orbitals (transition-metal \(d\)-electrons). The DFT + embedding approach treats a small active space with a higher-accuracy method — here, a VQE.

Why XACC rather than Qiskit.

  1. The DFT code is C++/Fortran running under MPI on thousands of cores. XACC is a C++ library that links directly; calling Python from an MPI Fortran code is painful.
  2. The VQE is called inside the self-consistency loop, thousands of times — the overhead of process boundaries matters.
  3. XACC's TNQVM tensor-network simulator runs on the same supercomputer, so the "quantum" step can be simulated at scale until real hardware is ready.

The workflow.

[ MPI rank 0..N: classical DFT ]
            |
            |  active-space Hamiltonian (a few orbitals)
            v
[ XACC: build Observable from the fermionic Hamiltonian ]
            |
            |  Jordan-Wigner / Bravyi-Kitaev mapping
            v
[ XACC: VQE with UCCSD ansatz ]
            |
     +------+-------+
     |              |
 [ TNQVM sim ]  [ real QPU via IBM/IonQ plugin ]
     |              |
     +------+-------+
            |
            v
   ground-state energy -> back into the DFT self-consistency loop
#include "xacc.hpp"
#include "xacc_observable.hpp"

int main(int argc, char** argv) {
    xacc::Initialize(argc, argv);

    // Hamiltonian produced by the classical DFT code
    auto H = xacc::quantum::getObservable("pauli", hamiltonian_string);

    auto accelerator = xacc::getAccelerator("tnqvm", {{"tnqvm-visitor","exatn"}});
    auto optimizer   = xacc::getOptimizer("nlopt", {{"algorithm","cobyla"}});
    auto ansatz      = xacc::getService<xacc::Instruction>("uccsd");

    auto vqe = xacc::getAlgorithm("vqe", {{"ansatz", ansatz},
                                          {"observable", H},
                                          {"accelerator", accelerator},
                                          {"optimizer", optimizer}});
    auto buffer = xacc::qalloc(n_qubits);
    vqe->execute(buffer);

    double energy = (*buffer)["opt-val"].as<double>();
    xacc::Finalize();
    return 0;
}

The key architectural benefit. Switching from the TNQVM simulator to real hardware is a one-line change:

auto accelerator = xacc::getAccelerator("ibm:ibmq_kolkata");

No application code changes. That plugin architecture is precisely what a long-lived HPC codebase needs: the quantum backend will change many times over the code's lifetime, but the science code should not.

Honest assessment. Today the TNQVM simulator gives better results than any available QPU for active spaces of practical size, so the "quantum" step is currently classical. The value of the workflow now is readiness — when hardware improves, the pipeline already exists.

Problem 5 — Choosing a compilation toolchain

Recommend a toolchain for each scenario, quantifying the benefit where possible.

(a) A 50-qubit QAOA circuit on IBM hardware, minimising CNOTs. (b) A teaching demonstration of how compilers insert SWAPs. (c) A VQE embedded in a Fortran molecular-dynamics code. (d) Rapid prototyping of a QML idea. (e) Publishing a benchmark comparing compiler quality.

Solution.

(a) 50-qubit QAOA on IBM → Qiskit for construction, TKET for compilation.

QAOA circuits are exponentiated Pauli strings, so PauliSimp is directly applicable. Published benchmarks put TKET 10–30 % below Qiskit's transpiler on two-qubit count for such circuits.

Quantified. Suppose Qiskit level 3 yields 400 CNOTs and TKET yields 320. At \(\epsilon_{\text{CX}} = 8\times10^{-3}\):

\[ F_{\text{Qiskit}} = 0.992^{400} = 0.0403, \qquad F_{\text{TKET}} = 0.992^{320} = 0.0766 \]
\[ \text{shot budget ratio} = \left(\frac{0.0766}{0.0403}\right)^{2} = 3.62^{2} = \mathbf{13\times \text{fewer shots}} \]

Use pytket-qiskit to submit directly to IBM after TKET compilation.

(b) Teaching how compilers insert SWAPs → ProjectQ, or Qiskit with visualisation.

ProjectQ's engine pipeline is small enough to read end to end — a student can literally follow a command through each engine. Alternatively, Qiskit's transpile(..., optimization_level=0) with circuit.draw() before and after makes SWAP insertion visible. TKET is the wrong choice here: it is a C++ black box, excellent at its job but opaque.

(c) VQE inside Fortran MD code → XACC.

The only framework designed for this. C++ API, MPI-aware, links into existing HPC codes, and swaps backends without touching application code (Problem 4).

(d) Rapid QML prototyping → PennyLane.

Autodiff, PyTorch/JAX integration, extensive templates, excellent documentation. Compilation quality is irrelevant at prototype stage — you are running on a simulator where CNOT count does not affect correctness.

(e) Publishing a compiler benchmark → all of them, on a standard benchmark suite.

Use QASMBench or MQT Bench for the circuits, compile with Qiskit (levels 0–3), TKET (several pass sequences), Cirq and pytket-tket, and report:

  • two-qubit gate count,
  • circuit depth,
  • compilation wall-clock time,
  • and — critically — verified circuit equivalence (unitary comparison on small instances), since an "optimiser" that silently changes the circuit is worse than useless.

Report all four metrics. A compiler that halves the CNOT count but takes an hour to run is unusable for variational algorithms that recompile every iteration; a compiler that is fast but occasionally incorrect is unusable full stop.

The summary rule.

\[ \boxed{\ \textbf{SDK for building, TKET for compiling, XACC for HPC embedding, ProjectQ for understanding.}\ } \]

44.7 Practice Problems

  1. Compute the fidelity gain from reducing 500 CNOTs to 300 at \(\epsilon = 10^{-2}\). [Ans: 0.0066 → 0.0490, 7.4×]
  2. Why can any two-qubit unitary use at most 3 CNOTs?
  3. Which TKET pass suits a Trotterised chemistry circuit, and why? [Ans: PauliSimp]
  4. Write pytket code converting a Qiskit circuit, optimising it and converting back.
  5. What makes XACC suitable for HPC and Qiskit unsuitable?
  6. Explain ProjectQ's engine pipeline in three sentences.
  7. If CNOT count falls 40 %, by what factor does the shot budget fall at \(\epsilon = 10^{-2}\) and 300 initial CNOTs? [Ans: \(F: 0.0490 \to 0.1638\), shots fall \(11.2\times\)]

44.8 Summary

  • TKET/pytket is compiler-first and SDK-agnostic: import from Qiskit or Cirq, optimise, export anywhere. Its passes (FullPeepholeOptimise, CliffordSimp, PauliSimp, KAKDecomposition) typically cut two-qubit counts by 20–50 %.
  • A 50 % CNOT reduction cuts the required shot budget by ~13×, because signal attenuation enters the variance as \(F^{-2}\) — the compiler pays for itself in hardware cost immediately.
  • KAK decomposition: \(\dim SU(4) = 15\) and 3 CNOTs provide exactly 15 parameters, so any two-qubit unitary needs at most 3 CNOTs — and naive compilations routinely use 6–9.
  • XACC treats the QPU as an HPC accelerator: C++ API, MPI-aware, plugin architecture so backends swap without application changes, TNQVM for large tensor-network simulation. Built for national-laboratory workflows.
  • ProjectQ pioneered the compiler-engine pipeline later adopted by Qiskit's PassManager and TKET. Its value today is pedagogical — it is small enough to read.
  • The professional workflow is polyglot: SDK for building, TKET for compiling, XACC for HPC embedding, ProjectQ for understanding.

Next lesson: L45 — Comparative study, benchmarking and the capstone project.

Practise now: unit4-platforms-lab.html → Optimiser Lab: build a circuit, apply simulated optimisation passes, and watch CNOT count, depth, fidelity and shot budget update together.