AWS Builder Center
Does this CNOT spark joy? Teaching an RL agent to tidy quantum circuits ✨

Does this CNOT spark joy? Teaching an RL agent to tidy quantum circuits ✨

In which we train a small reinforcement learning agent to declutter quantum circuits, let Amazon Braket check every answer, lose to a random walk (briefly), and then run the tidied circuits on a real Rigetti QPU to see if any of it mattered (*physics joke alert*).

A cluttered circuit is a noisy circuit 🧹

If you're reading this, you probably know that you can rent a real quantum computer on AWS through Amazon Braket, program it in Python, and pay per run.
Braket and I go way back. My first-ever interaction with an Amazonian was Bill Vass sharing my  QHack recap  on PennyLane and Amazon Braket.
If you're not familiar, the quantum computing narrative goes something like this...
Where your laptop works with bits, a quantum computer works with qubits. A bit is always either 0 or 1, while a qubit can be in a blend of 0 and 1 at the same time (that's called superposition), and qubits can be linked so that their results are tied together (entanglement). When you read a qubit, you always get a plain 0 or 1, with odds that depend on the blend.
Source: QNu Labs (https://www.qnulabs.com/blog/quantum-101-qubit)

Its programs are called circuits: lists of instructions called gates, each of which does something small to one or two qubits (flip this one, link those two together, &c.). At the end, you read the qubits out as plain 0s and 1s.
Source: TU Delft (https://www.tudelft.nl/over-tu-delft/strategie/vision-teams/quantum-computing/what-is-quantum/quantum-circuits)

💡 Tip: If this sounds too complicated, I highly recommend reading  Quantum Computing as a High School Module  and playing with  Quirk: Quantum Circuit Simulator .
Today's quantum computers are noisy. Every gate you run adds a little error, and the errors pile up quickly. Gates that touch two qubits at once, like the  Controlled-NOT  (CNOT), are the worst. On the chips I used, they go wrong 2 to 3x more often than one-qubit gates.
When it comes to circuits, the rule of thumb is: fewer gates, fewer errors, better answers.
Circuits tend to collect junk, though. Two gates that undo each other. Two gates that could be one. Nobody writes that on purpose. It creeps in when you start gluing gate lego blocks together or let a tool generate the circuit for you (or when you're coding at 2AM 🙃).
Here's a real one from my test set, before and after the agent got its hands on it:

The quantum computer usually cleans some of it up before running your circuit. Unless you ask it not to: in verbatim mode, it runs exactly what you wrote, junk and all.
So I wanted to know if a small AI agent, trained by trial and error (i.e. reinforcement learning, or RL), could learn to tidy circuits on its own, and do it better than the obvious approaches.

The house rules 📏

To keep things small (and checkable), the agent plays in a tiny world:
  • 4 qubits in a row (0–1–2–3), like a small slice of a real chip
  • 6 kinds of gate: H, S, S†, X, Z and CNOT. They belong to a family called Clifford gates, which an ordinary computer can simulate exactly, so every answer can be checked
  • A price list: +1 point per one-qubit gate and +5 per CNOT, because CNOTs are the worst (on the real chip, each one also needs a few extra one-qubit gates around it)
The goal is to get the total down without changing what the circuit does.
Now, the agent can't just delete gates it doesn't like. It has 5 moves, and each one swaps a piece of the circuit for something that does exactly the same job:

Commute is a sneaky one. On its own, it saves nothing: it swaps two gates that don't get in each other's way, so their order doesn't matter. But it can slide a gate right next to its twin, and then a cancel removes both. An optimizer that only plays moves that pay off right away never commutes, so it gets stuck.
To make test circuits, we start with a random 12-gate circuit and stuff junk into it, 10x over. Some of the junk ends up inside other junk, so the order you clean up in matters:
def bloated(rng, m=12, k=10):
core = random_core(rng, m)
gates = core
for _ in range(k): # junk inside junk
gates = bloat_once(gates, rng)
return core, gates

Braket grades the homework ✅

It's easy to get a quantum circuit subtly wrong. Swap two gates that shouldn't be swapped and you've built something else. For our purposes, we'll assume that no answer counts until Braket agrees the tidied circuit does the same thing as the original.
The check compares the two circuits' unitaries. A unitary is the matrix that describes exactly what a circuit does to any input, and the Braket SDK will compute it for you:
def same_unitary(a, b, n=4):
"""Equal up to global phase."""
ua, ub = to_braket(a).to_unitary(), to_braket(b).to_unitary()
return abs(abs(np.trace(ua.conj().T @ ub)) - 2 ** n) < 1e-6
("Up to global phase" is just a way of saying that we ignore a difference no experiment could ever detect.)
I checked every move on 200 random circuits, then checked all 780 final answers in this post again at the end (130 test circuits × 6 methods). Mismatches: 0.

Time to meet the agent 🤖

The agent never looks at the whole circuit. For each move it could make, it gets a short description: which rule, which gates, and which gates sit next to them. All summed, that's 77 numbers per move. A tiny neural network gives each move a score, and the agent plays the best one (or stops):
class Policy(nn.Module):
def __init__(self):
super().__init__()
self.net = nn.Sequential(nn.Linear(77, 64), nn.Tanh(),
nn.Linear(64, 64), nn.Tanh(),
nn.Linear(64, 1)) # one score per possible move
Training works by trial and error. The agent tidies a circuit, earns points for every bit of cost it removes (minus a tiny fee per move, so it doesn't fiddle forever), and nudges its network towards the moves that paid off. The algorithm is called  REINFORCE . I gave it 4k practice circuits, which took 15 minutes on a laptop.
Because it only looks at a gate's neighbors, the same agent works on circuits of any length, including ones much bigger than anything it practiced on.
Here's the whole setup, for your viewing pleasure:


The contestants 🥊

A trained agent that loses to a  for -loop is just an expensive  for -loop. For comparison, every test circuit also went through simpler tidiers - the kind of stuff you'd try before reaching for ML - one of which is really just about searching harder:
Method
How it works
Greedy peephole
Looks at a few neighboring gates at a time (the "peephole") and plays whichever move saves the most immediately. Stops when no move saves anything. It never commutes, because a commute saves nothing right now.
Random walk
Plays random moves until it runs out of new ones. No move makes a circuit worse, so it can wander sideways but never uphill.
Beam search
Keeps a shortlist of the 32 cheapest circuits found so far, tries every move on each of them, and repeats
RL agent
Scores every move with its neural network and plays the best one, until it decides to stop. It gives the same answer every time

The results 📊

Lower is better everywhere below. As a reminder, cost uses the price list from earlier: +1 per one-qubit gate, +5 per CNOT.

On 100 test circuits like the ones it practiced on (~36 gates each):

Cost left
CNOTs left
Time
Bloated
63.6
7.0

Greedy peephole
42.8
6.2
0.00 s
Random walk, 1 try
27.6
4.1
0.01 s
Random walk, best of 16
24.1
3.7
0.19 s
Beam search
24.4
3.7
0.15 s
RL agent, 1 try
24.2
3.7
0.09 s
On 30 circuits 3× bigger than anything it practiced on (~114 gates each):

Cost left
CNOTs left
Time
Bloated
188.6
18.6

Greedy peephole
109.4
15.7
0.03 s
Random walk, 1 try
53.3
7.8
0.11 s
Random walk, best of 16
44.9
7.1
1.37 s
Beam search
49.6
7.7
1.68 s
RL agent, 1 try
42.8
7.0
0.72 s
Greedy barely touches the CNOTs. It halves the number of gates, but almost every CNOT saving needs a commute first, and greedy never commutes.
On circuits like the ones it practiced on, the agent ties beam search and the best of 16 random walks, in a single try.
On the big circuits it had never seen, it beats both, and it did at least as well as beam search on every one of the 30. My guess is that beam search gets short-sighted on long circuits. With only 32 slots and hundreds of possible moves, it keeps whatever looks cheapest right now and throws away the paths that commute first and pay off later.
As for the random walk, we'll come back to that 🎲
Note: a reader asked if mixing local and global search would help, something I hadn't originally tried. I ran the same beam search using the agent's move scores to pick which circuits survive instead of raw cost. Here are the results:
Big circuits (30)
Cost left
CNOTs left
Beam search, ranked by cost (width 32)
49.6
7.7
RL agent, 1 try
42.8
7.0
Beam search, ranked by agent (width 8)
42.0
6.9
Beam search, ranked by agent (width 32)
42.2
6.9
When the agent chooses which circuits beam search keeps, instead of just the cheapest ones, it does better on 20 of the 30 circuits and never worse, but it barely beats the agent on its own.

But does it matter on hardware? 🔬

Fewer gates should mean fewer errors, but I wanted to measure it. If I don't measure it, I can't trust it. The test is called a mirror circuit: run the circuit (U), then run it again backwards (U†). The second half undoes the first, so a perfect machine always ends up where it started:

I picked the 5 big circuits where the agent beat greedy by the widest margin, and ran three versions of each (bloated, greedy and agent):
  1. on the local simulator, with a noise model built from Rigetti Cepheus's published calibration data (free, and refreshed daily)
  1. on the real Rigetti Cepheus, 1k shots per circuit (a shot is one run, ending in one reading). All 15 circuits went in a single program set, which is one task and one task fee, for $6.68 in total
The score is P(0000): the fraction of shots that came back  0000 . 1.0 would be perfect.


Gates
CNOTs
P(0000), simulated
P(0000), real QPU
Bloated
~111
~22
0.486
0.101
Greedy peephole
~55
~20
0.582
0.066
RL agent
~14
~6
0.810
0.646
The real chip was much harsher than the simulator. Pick a random 4-bit string and you'll hit  0000  one time in 16 (0.0625). The bloated and greedy circuits scored 0.10 and 0.07, barely better than guessing.
The tidied circuits held up. At 0.646 on average, they kept 6x to 10x more signal than the other two. On one circuit, the agent's version scored 0.79 and the bloated original scored 0.04.
Now, you may be wondering: why was the simulator so optimistic? The circuits are long. Translated into the chip's own gates and mirrored, a bloated circuit is about 660 operations stacked 322 steps deep. The agent's version is about 110 operations and 61 steps. My noise model charges for every gate but not for waiting, and on a real chip qubits lose their quantum state just sitting there, on a timescale of about 20 µs (the T2 time, 19–27 µs on the qubits I used). A circuit 5x deeper spends about 5x longer waiting.
On real hardware, the short circuits gave answers, while the long ones gave something close to random noise 🎲

Things that bit me 🦈

1. My learning curve lied to me 📉

The first training run improved quickly, then slowly got worse for 3k episodes (an episode is one practice circuit):

This was a 2-in-1 problem.
First, the curve was measuring luck. Each point averaged 16 different random circuits, and some circuits simply have more junk to remove. A lucky batch looked exactly like a smarter agent.
Second, the training signal suffered from the same problem. On top of that, the learning rate (how big a step the network takes on each update) was 3e-3, with nothing capping those steps, so the agent drifted off.
The fix:
  • have the agent tidy the same circuit 4x, and judge each attempt against the other three (the same idea as GRPO)
  • lower the learning rate, and cap the size of each step (gradient clipping)
  • measure progress on a fixed set of 32 validation circuits, and keep the best version

2. The agent that commuted forever 🔁

Commuting two gates saves nothing. Commuting them back also saves nothing. An agent that always plays its top move can swap the same two gates back and forth until it hits the step limit.
The fix: an attempt can't return to a circuit it has already seen.
def fresh(gates, acts, visited):
return [a for a in acts if tuple(a[2]) not in visited]

3. The random walk was embarrassingly good 🎲

In my first evaluation, the best of 16 random walks tied up with beam search. Even on a 112-gate circuit, a single random walk found the same answer as beam search.
The reason: no move ever makes a circuit worse, so a random walk can't go uphill. It just wanders downhill until it runs out of moves.
So beating random isn't a given. The fair comparison is one agent try against one random try. There, the agent's circuits end up 12% cheaper on the practice-sized circuits and 20% cheaper on the big ones.

4. A good compiler would eat my experiment 🍽️

A mirror circuit does nothing, by design: again, the second half just undoes the first. A good compiler spots that and deletes the whole thing, and an empty circuit reads  0000  every single time.
The fix: translate everything into the chip's own gates (its native gates) myself, and wrap the result in a verbatim box so the chip runs it exactly as written:
def native(gates, phys):
"""Cepheus speaks rx(±π/2, π), rz(any) and cz. rz is a free frame change."""
c = Circuit()
h = lambda q: c.rz(q, pi / 2).rx(q, pi / 2).rz(q, pi / 2)
for g, qs in gates:
q = [phys[i] for i in qs]
if g == "h":
h(q[0])
elif g == "cnot":
h(q[1]); c.cz(q[0], q[1]); h(q[1])
... # x, z, s, s† are one rotation each
return c
circuit = Circuit().add_verbatim_box(native(mirror(gates), phys=[101, 100, 99, 90]))
Yes, I checked the translation against the unitaries too 🙃

5.  aws login  and the Braket SDK 🔑

The AWS CLI v2 works with  aws login  sessions out of the box. The Braket SDK (through boto3) needs one extra package:
MissingDependencyException: Missing Dependency: Using the login credential provider
requires an additional dependency. You will need to pip install "botocore[crt]"

6. The terms and conditions apply 📜

My first real QPU submission from a fresh account came back with:
AccessDeniedException: User agreement has not been accepted for <account-id>.
Quantum computers on Braket are run by other companies (Rigetti, IQM, &c.), and using them needs a one-time agreement in the console, under Permissions and settings:

So I accepted it, resubmitted, and got:
AccessDeniedException: AWSServiceRoleForAmazonBraket role doesn't exist.
Braket also needs a service-linked role, which lets it access AWS resources on your behalf. On a fresh account, the Execution roles tab looks like this:

One click on Create service-linked role later:

or skip the console and run one command:
aws iam create-service-linked-role --aws-service-name braket.amazonaws.com
Do both before the QPU's current execution window (the hours it accepts jobs) closes.

How much did it cost? 💸

Without a program set, you'd pay the $0.30 task fee 15x instead of once: $4.20 extra.

Things I learned 🧠

1. Write the simple baseline first. A random walk nearly tied my RL agent. If I'd only compared against greedy, I'd have written a much more exciting blog post... and it would have been wrong.
2. Measure training on a fixed set of problems. Otherwise a lucky batch looks like progress.
3. Looking locally scaled better. An agent that only looks at a gate's neighbors handled circuits 3x bigger than anything it practiced on. Beam search, which compares whole circuits, did worse as they grew. When the agent ranked the beam instead of raw cost, beam search caught up. So beam's ranking was the weak spot, not the lack of a global view, and search on top of the agent added almost nothing.
4. The simulator got the order right and the size wrong. The noise model built from calibration data ranked the three versions correctly, for free, in seconds. It also predicted 0.49 where the real chip said 0.10. Use it to choose between circuits, then use real hardware to find out how good the winner really is.

What's next? 🚀

  • Gates outside the Clifford family (like T, or rotations by any angle), where checking that two circuits match gets much harder
  • Letting the agent choose which physical qubits to use, based on the day's calibration
  • Taking on the provider's own compiler, with verbatim mode switched off
Until then, look at every CNOT in your circuit and ask: does this spark joy? If it doesn't, thank it, and let it go ✨

References 📚

Any opinions in this article are those of the individual author and may not reflect the opinions of AWS.
Enjoyed reading this content? Let the author know!

Your likes, comments, shares, and saves help creators reach more builders.

Loading recommendations

Loading article