# Reinforcement Learning Based Quantum Circuit Optimization via ZX-Calculus

rl-zx trains a PPO agent to pick ZX-diagram rewrites for quantum circuits

Jordi Riu, Jan Nogué, Gerard Vilaplana, Artur Garcia-Saez, Marta P. Estarellas · arXiv · 2023-12-18

- **Problem** Gate-level RL optimizers face a fast-growing action space of gate identities, so agents are slow to learn.
- **Method** rl-zx trains a PPO agent to pick ZX-diagram rewrites instead of inventing new rules. Graph neural networks score each feasible rewrite, and reward is the gate-count drop after extraction.
- **Results** On 80-qubit circuits, rl-zx improved on gflow-zx in above 80 % of cases, after training only on 5-qubit circuits.

## Why rule search gets stuck

Gate-level optimizers apply algebraic identities that permute and cancel gates in the original circuit. RL agents can work with this approach, but the action space grows quickly. Each gate identity type must be identified, and each type may involve multiple gates. The agent then has to explore and exploit from a large and diverse set of possible permutations and cancellations.

The authors respond by using ZX-Calculus, a graphical language for reasoning about quantum computation, as their framework. ZX-Calculus needs a smaller and simpler action space, because fewer types of rules can be applied to ZX-diagrams. ZX rules operate on spiders and wires while preserving the semantics of the computation.

The catch is in the last step, where the simplified diagram is transformed back into an equivalent circuit. This step can be very inefficient or even unfeasible in some cases, and it can output circuits more computationally expensive than the initial ones. Heuristic rules have been suggested, but no known optimal strategy tells which sequence of rule applications yields the maximally optimized circuit.

So the open question is which rules to apply and in what order, and this paper hands that selection to RL. The main focus is improving the rule selection process using RL, rather than discovering new rules to simplify the diagram.

## ZX-diagrams and the graph-like form

A ZX-diagram is a graph whose nodes are spiders and whose edges are wires. Z and X spiders can be read as tensors built from Pauli-Z and Pauli-X eigenstates, respectively. Each spider carries a phase α between 0 and 2π, and the spider has m inputs and n outputs. The wires come in two types, Simple and Hadamard, and the rules that keep the tensor representation let the diagram be simplified.

A Hadamard wire is a simple wire with a Hadamard gate, drawn as a dashed blue wire.

The agent works on the graph-like form, where every spider is a Z-spider and every connection is a Hadamard wire. The form also forbids parallel Hadamard edges and self-loops, so the diagram stays simple to reason about. Reaching this form takes repeated spider fusion and Hadamard rules, which the authors say can always be applied. Once the diagram is graph-like, graph-theoretic rules take over the simplification.

Converting back to a circuit is the costly step, since it can be very inefficient or even unfeasible. Extraction can also output circuits that are more expensive than the original ones. Heuristic rules exist, but no known optimal strategy picks the best sequence of rule applications. The agent therefore learns which rule to apply next, instead of inventing new rules for the diagram.

## Existing ZX optimizers and the flow conditions

Generalised flow, or gflow, is the property that makes circuit extraction possible from a ZX-diagram. Extraction treats the process as a black box, so the action space is limited to rules that satisfy the gflow condition. Rules that preserve gflow keep the guarantee that a circuit can be extracted, because the existence of gflow is guaranteed when the initial diagram has it.

gflow-zx follows the same action set and extraction procedure as the RL agent, so it gives a fair test of what the agent adds. It uses a greedy heuristic that selects local complementation and pivoting until termination. That stricter condition leaves less room for exploring complex ZX-diagrams, which is the trade-off the authors accept. The authors choose cflow-zx as the most competitive ZX-based optimizer for two-qubit gate reduction.

Basic optimization is a PyZX peephole optimizer that applies SWAP and gate cancellation identities back and forth. Full reduce applies local complementation, pivoting and gadget fusion rules to interior Clifford spiders until no transformation is left. Teleport reduce lowers the T-count and leaves the two-qubit gates unchanged, because it does not alter the structure of the circuit.

Both cflow-zx and gflow-zx run basic optimization and teleport reduce as pre-processing before the rule selection.

## Actor and critic built from GATv2 layers

The actor reads the ZX-diagram directly as a graph, so the network's connections copy the diagram's connections. Each green spider becomes a node, and each feasible rule becomes an extra action node inside the same graph. Each action node connects only to the spiders that define it and to the STOP node, and the STOP node links only to the other action nodes.

Figure 4 shows this layout, with green spiders drawn as silver nodes and action nodes drawn in orange. The authors chose this design because GNNs capture long-distance correlations in graph-like data of variable size.

![Figure 4: Schematic Overview of the Actor and Pol- icy Networks: The policy network, denoted by π(a\|s), is visualized with each green spider from the diagram c…](https://refivu.com/papers/9c8e6aa3-4291-4395-9813-828baebb2513/figures/figure-fb0b86ae5d680871df5ab4e90ad4f8cb.png?thumb=512)

**Figure 4** : Schematic Overview of the Actor and Pol- icy Networks: The policy network, denoted by π(a\|s), is visualized with each green spider from the diagram corresponding to a silver node, while the blue wires are depicted as purple connections. Action nodes are high- lighted in orange, with connections to silver nodes and node STOP, which provide a complete description of the actions. The critic network shares a similar architecture; however, the orange node, representing theV (s) output, is not part of the message passing layers. Instead, it is obtained after applying the global attention layer to the outputs of such layers. The self loops are not included for clarity.

[Original paper](https://arxiv.org/abs/2312.11597v4) · [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/) · Jordi Riu, Jan Nogué, Gerard Vilaplana, Artur Garcia-Saez, Marta P. Estarellas · Reinforcement Learning Based Quantum Circuit Optimization via ZX-Calculus · Original paper figure · Extracted the figure area from page 10 of the original PDF.

GATv2 layers update each node by a weighted sum of its own transformed features and its neighbours' features. The update reads x\_i^{t+1} = α\_{i,i} Θ\_s x\_i^t + sum over j in N(i) of α\_{i,j} Θ\_t x\_j^t, with Θ\_s and Θ\_t learnable. Attention scores pass through a LeakyReLU, and a softmax over the node and its neighbours turns them into coefficients that sum to 1.

Edge features enter the attention score through Θ\_e, and they stay unchanged during the calculation. After message passing, a softmax over each action node's feature gives π(a\_i\|s), where F(s) is the set of feasible actions.

Each node starts with a 16-dimensional feature vector in the actor. Eight binary flags encode the phase, three flags mark input, output or phase gadget, and five flags mark the rule type. The critic uses 11 features per node because it has no action nodes. Each edge carries a 6-dimensional one-hot vector that tells a wire from an action connection.

The critic's value output comes from a global attention layer after message passing, not from an action node.

## One episode, step by step: what happens between two actions

Each episode starts from a random Clifford+T circuit that is converted into graph-like form. Before the agent acts, the authors apply basic optimization and teleport reduce, which they call gate-based preprocessing. Basic optimization removes trivial gate identities, which leaves the agent less work to do.

At each step, the agent picks one action from the feasible choices, based on the state of the diagram. The chosen rewrite is applied to the ZX-diagram, and the circuit is then extracted from the modified diagram. The reward is set by the total number of gates in the extracted circuit, measured against the amount before the action. The reward is normalized by an expected compression factor, which is 30% of the expected initial number of 2-qubit gates.

Basic optimization runs before the reward is computed, because circuit extraction adds trivial single-qubit gates that would otherwise make the agent discard useful actions.

The action space holds local complementation (lc), pivoting (p, p1, p2, p3), gadget fusion (gf) and identity (id) rules. A STOP action lets the agent end the episode at any time. Neighbour unfusion is left out, because the authors' analysis is needed before it can be added without breaking gflow. Each feasible rule becomes an action node in the network, linked only to the nodes that define it and to STOP.

An episode ends when the agent selects STOP or when no action is available. The agent keeps the best circuit seen at any point, not only the final one. This choice costs an extraction after each step, which lowers the computational performance of rl-zx. The authors also report that, in some cases, the output is the circuit after basic optimization and teleport reduce, but they call this very unlikely.

## Reward and the single-shot term

The agent's reward is the drop in gate count caused by one action, measured on the graph-like diagram. Each reward is divided by an expected compression factor, set to 30% of the expected initial two-qubit gate count. Two reward versions exist: one targets the total number of gates, and the other counts only two-qubit gates.

Circuit extraction is inefficient, so it can add two-qubit gates and single-qubit gates that are trivial to simplify. That overhead would make the agent discard actions that give real simplifications. The authors therefore run basic optimization before the reward is computed, which keeps trivial gates out of the count. This step slows training, but for testing, extraction can run only at the end of the episode.

The single-shot reward arrives at the end of the episode and is proportional to the gate difference from cflow-zx on the same circuit. Without this term, the entropy coefficient alone couldn't balance exploration and exploitation, and the agent tended to converge to applying no actions. The authors also keep the best circuit seen at any point in the episode, not only the final one.

That choice costs extra extraction time after each step, which the authors treat as a trade-off.

## PPO training and the training circuits

The agent is trained with PPO, which updates the actor and the critic together by minimizing one combined loss. The total loss is L\_PPO(θ) = L\_Actor(θ) + c1 L\_Critic(θ) − c2 L\_Entropy(θ), so both networks share one optimization step. The actor term multiplies the probability ratio between the new and old policies by the Generalized Advantage Estimator At, and clips that ratio between 1−ϵ and 1+ϵ.

Because the clipping limits how far the policy moves at each step, PPO keeps training stable.

The entropy term is subtracted from the loss, so it pushes the policy toward higher uncertainty and more exploration.

Table 1 fixes the hyperparameters, including a learning rate of 2 × 10−4, a discount of 0.99, 8 epochs and minibatches of 512. Each network has five GATv2 message-passing layers with input and output channel dimension of 32, and the critic adds a global attention layer. Training runs on a single node with 8 CPUs and one GPU and takes ∼ 16 hours.

The extra gates and CNOT weight compensate for the smaller number of meaningful actions when the target is two-qubit gates.

The test circuits later range from 5 to 80 qubits, so the authors check whether agents trained on small circuits generalize. The largest test instances are 80 qubit circuits of 2100 random gates, giving an average depth of 80.

## Tests on random circuits up to 80 qubits

The authors test each trained policy on 1000 random circuits for each size, with 5, 10, 20, 40 and 80 qubits. Depths grow as d, 2d, 3d and 4d, so the test scales both qubit count and depth at once. The largest instances are 80-qubit circuits of 2100 random gates, which gives an average depth of 80. The gate probabilities of inclusion stay the same as in training, so only the size changes.

For the total-gate objective, the agent's reduction keeps rising with both the number of qubits and the depth. The authors read this consistent rise as a naive sign that the agent generalizes correctly. For the two-qubit objective, the reduction depends mostly on circuit depth rather than on qubit count. The number of actions per episode also grows with depth and qubits, up to a cap of 50 to 100 actions set by circuit size.

Local complementation has no real impact on two-qubit gate reduction, so the agent relies almost only on pivotings.

On the frequency test, the RL approach outperforms the other optimizers for circuits up to sixteen times the training qubit count and four times the training average depth. The training reference is 5 qubits at depth 20, as stated for the comparison in Figure 8. For the largest circuits, the rl-zx output improved on gflow-zx in above 80 % of cases.

The authors take this as evidence that the approach is useful for circuits in the regime of quantum advantage experiments.

The agent's gains are less clear on pivoting-heavy circuits, because the authors found it struggles to find beneficial pivotings as qubits grow. The authors attribute this to the black-box treatment of pivotings during circuit extraction. They didn't test added heuristic features in the observation, leaving that step as future work.

## Which rules the agent picks for each objective

The two objectives scale differently, so the authors compared which rule types the agent picks for each. For the two-qubit objective, the number of actions per episode grows until it hits a cap of 50 to 100, depending on circuit size. Local complementation barely changes the two-qubit count, so the agent picks pivotings almost exclusively for that objective.

The authors treat local complementation as a PASS action that neither helps nor hurts the agent immediately. Still, local complementation changes connectivity, which can open new pivotings on the next step.

Local complementation counts follow the same monotonic increase with both qubit count and depth. The agent, however, struggles to find beneficial pivotings as the number of qubits grows, as Figure 7b shows. Pivotings change the neighbourhood of two spiders, so they can drastically alter the diagram's connectivity once applied. The size of that change depends on how many wires a spider can have, which follows the dimension of the Hilbert space when gflow is preserved.

Modelling how a pivoting affects circuit extraction is hard, because the agent treats extraction as a black box. The authors suggest adding the heuristics from \[20\] as observation features, but they leave that to future work. The RL approach outperforms the competition for circuits up to sixteen times the training qubit count and four times the training depth.

## Combining gflow actions with cflow-zx on structured circuits

The workflow ends with cflow-zx on the final circuit once the agent selects STOP. The reward adds the gate difference between that cflow-zx result and cflow-zx applied to the initial circuit. This biases the agent toward fewer two-qubit gates under gflow rules, which can be detrimental for certain circuits. Hybrid workflows like this show that the gflow-based action selection can sit inside other pipelines.

The retrained agent learned on random circuits of 5 qubits and 70 gates. It is tested on structured circuits such as the quantum Fourier transform, with 1000 tries per circuit under its probabilistic policy. The authors benchmark it against NRSCM, cflow-zx, gflow-zx plus cflow-zx, and random-zx. A combination of the most advanced gflow-based heuristic with cflow-zx doesn't improve results in the majority of cases.

![Figure 11: Comparison of the two qubit gates distribution obtained for the for rl-zx + cflow-zx (orange) and the random-zx (in blue) for different circuits. In…](https://refivu.com/papers/9c8e6aa3-4291-4395-9813-828baebb2513/figures/figure-fe6bf84a780c8150691ae8be281bdc50.png?thumb=512)

**Figure 11** : Comparison of the two qubit gates distribution obtained for the for rl-zx + cflow-zx (orange) and the random-zx (in blue) for different circuits. In a dashed black line is depicted the two qubit gates obtained by the cflow-zx. a) First two columns. Circuits for which an execution of the random policy achieved the optimal result. (b) Last two columns. Circuits for which an execution of the rl-zx + cflow-zx achieved the optimal result.

[Original paper](https://arxiv.org/abs/2312.11597v4) · [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/)

rl-zx is a consistent enhancement over cflow-zx, but a fully random action selection still finds optimal circuits for several instances. For some of the largest circuits, the random algorithm didn't terminate within the 72h job limit. The authors expect rl-zx to improve if larger or more similar circuits are used for training.

In single-shot mode, rl-zx picks the action with the largest probability instead of sampling. It improves on cflow-zx in 13 of the 33 circuits tested, with more modest gains than the sampled policy. Figure 11 compares the two-qubit gate distributions of rl-zx plus cflow-zx and random-zx on circuits where each reached the optimum.

## Limits and open questions

The compression rl-zx reaches on random circuits stays consistently worse than cflow-zx, and the authors trace this to gflow-based extraction being very inefficient for two-qubit gates. The cflow formulation estimates the gates produced by extracting each spider, which the gflow-based route doesn't offer, so the decision process is simpler under cflow.

On the random circuits, the agent finds fewer beneficial pivotings as the number of qubits grows, and this accounts for the disparity in two-qubit gate reduction. Because the extraction is treated as a black box, the authors see modelling the effect of pivotings as particularly difficult. They leave adding heuristic features, such as those used in \[20\], to the observation as future work.

The unrefined rl-zx implementation runs about an order of magnitude slower than cflow-zx, but it keeps a similar subexponential scaling. The authors suggest shaping the reward for hardware properties, such as weighting each gate by its fidelity or accounting for qubit coherence times. They don't test that reward shaping in this work.

Giving the agent a cflow-based reward after every action proved highly detrimental to its generalization. Each such check forces the circuit to be extracted, converted back to graph-like form, and optimized again, which is computationally expensive. The optimization policy is probabilistic, so as the circuit grows, more possible actions compete with STOP.

A single wrong pivoting instead of stopping, on high-dimensional diagrams, can drastically change the number of two-qubit gates.

The authors expect rl-zx to improve when trained on more similar or larger circuits. They didn't test this expectation in the present work.

## Paper info

- **Authors**: Jordi Riu, Jan Nogué, Gerard Vilaplana, Artur Garcia-Saez, Marta P. Estarellas
- **Venue**: arXiv · Preprint
- **First published**: 2023-12-18
- **Added**: 2026-11-6
- **Updated**: 2025-5-22
- **Version**: v4
- **arXiv**: 2312.11597
- **DOI**: 10.22331/q-2025-05-28-1758
- **Category**: quant-ph
- **Original paper terms**: [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/)
- **What we show**: Paper info, commentary and permitted figures from the original paper

[Original paper ↗](https://arxiv.org/abs/2312.11597v4) · [PDF ↗](https://arxiv.org/pdf/2312.11597v4)

AI commentary is a separate explanation from the original paper and may contain errors. The original paper and figures follow each source's terms of use and any rights noted separately.

## Abstract

We propose a novel Reinforcement Learning (RL) method for optimizing quantum circuits using graph-theoretic simplification rules of ZX-diagrams. The agent, trained using the Proximal Policy Optimization (PPO) algorithm, employs Graph Neural Networks to approximate the policy and value functions. We demonstrate the capacity of our approach by comparing it against the best performing ZX-Calculus-based algorithm for the problem in hand. After training on small Clifford+T circuits of 5-qubits and few tenths of gates, the agent consistently improves the state-of-the-art for this type of circuits, for at least up to 80-qubit and 2100 gates, whilst remaining competitive in terms of computational performance. Additionally, we illustrate the versatility of the agent by incorporating additional optimization routines on the workflow during training, improving the two-qubit gate count state-of-the-art on multiple structured quantum circuits for relevant applications of much larger dimension and different gate distributions than the circuits the agent trains on. This conveys the potential of tailoring the reward function to the specific characteristics of each application and hardware backend. Our approach is a valuable tool for the implementation of quantum algorithms in the near-term intermediate-scale range (NISQ).

## Quote from the paper

Jordi Riu, Jan Nogué, Gerard Vilaplana, Artur Garcia-Saez, Marta P. Estarellas (2023). Reinforcement Learning Based Quantum Circuit Optimization via ZX-Calculus. arXiv:2312.11597v4. https://doi.org/10.22331/q-2025-05-28-1758

**BibTeX**

```
@article{riu2023reinforcement,
  title = {{Reinforcement Learning Based Quantum Circuit Optimization via ZX-Calculus}},
  author = {Jordi Riu and Jan Nogué and Gerard Vilaplana and Artur Garcia-Saez and Marta P. Estarellas},
  year = {2023},
  eprint = {2312.11597},
  archivePrefix = {arXiv},
  doi = {10.22331/q-2025-05-28-1758},
  url = {https://arxiv.org/abs/2312.11597v4}
}
```

## Other paper commentary

- [A Review of Off-Policy Evaluation in Reinforcement Learning](https://refivu.com/en/papers/e25e61dd-1c4f-4fca-aaa9-9c30003d2d85-a-review-of-off-policy-evaluation-in-reinforcement.md)
- [Identifying optimal cycles in quantum thermal machines with reinforcement-learning](https://refivu.com/en/papers/91ae4a4b-783d-4d4a-9036-c66652125ae6-identifying-optimal-cycles-in-quantum-thermal-machines-with.md)
- [Mastering the Game of Stratego with Model-Free Multiagent Reinforcement Learning](https://refivu.com/en/papers/c8ba1a5f-8040-4096-92b0-d848951ca124-mastering-the-game-of-stratego-with-model-free.md)
- [Revisiting Critic Estimation in Soft Actor-Critic Algorithms](https://refivu.com/en/papers/3b523ee0-ead6-4c46-a193-319c3c9a36b7-revisiting-critic-estimation-in-soft-actor-critic-algorithms.md)
- [Reinforcement Learning via Self-Distillation](https://refivu.com/en/papers/020d237b-90b6-4f93-9da6-e25bde98d4ec-reinforcement-learning-via-self-distillation.md)
- [Soft Actor-Critic: Off-Policy Maximum Entropy Deep Reinforcement Learning with a Stochastic Actor](https://refivu.com/en/papers/ea8ec555-d426-4464-bcf3-677288c80a9c-soft-actor-critic-off-policy-maximum-entropy-deep.md)
- [V3D: Video Diffusion Models are Effective 3D Generators](https://refivu.com/en/papers/7ac7016e-0685-4edf-a818-3baccf2777ee-v3d-video-diffusion-models-are-effective-3d-generators.md)
- [The no-free-lunch theorems of supervised learning](https://refivu.com/en/papers/e3085891-a4f1-4605-8cbb-a1c36168e267-the-no-free-lunch-theorems-of-supervised-learning.md)
- [Decision-Oriented Dialogue for Human-AI Collaboration](https://refivu.com/en/papers/1d9fad4b-76a3-40b2-b7c6-3b42b2a8ddc5-decision-oriented-dialogue-for-human-ai-collaboration.md)
- [Multimodal Spatial Language Maps for Robot Navigation and Manipulation](https://refivu.com/en/papers/4a0d9969-87c8-4cf7-9b1a-5f7c83b81e14-multimodal-spatial-language-maps-for-robot-navigation-and.md)
- [Multi-SimLex: A Large-Scale Evaluation of Multilingual and Cross-Lingual Lexical Semantic Similarity](https://refivu.com/en/papers/2e03a8c0-9df9-42e1-97d6-82e5f0f5ad03-multi-simlex-a-large-scale-evaluation-of-multilingual.md)
- [Deep Unsupervised Learning using Nonequilibrium Thermodynamics](https://refivu.com/en/papers/0a712ab6-ae49-4e62-8de7-48f3f793c53f-deep-unsupervised-learning-using-nonequilibrium.md)

## Terms in this paper

- [Proximal Policy Optimization](https://refivu.com/en/terms/59b59e5d0f9d-proximal-policy-optimization)
- [Graph Neural Networks](https://refivu.com/en/terms/0650d076a410-graph-neural-networks)
- [GATv2](https://refivu.com/en/terms/91a38a2e1069-gatv2)
- [Pivoting](https://refivu.com/en/terms/1ee61dcd67ff-pivoting)
- [Reward Function](https://refivu.com/en/terms/54f4a5f914c0-reward-function)

---

AI-written text can contain mistakes. [Refivu](https://refivu.com/en/papers/9c8e6aa3-4291-4395-9813-828baebb2513-reinforcement-learning-based-quantum-circuit-optimization)
