Level 6 · Practitioner's Corner

Cirq and PennyLane: An Introduction for Qiskit Users, With Gradients Worked Out by Hand

About 4,988 words · roughly 23 minute read · sources checked December 2026

Most beginners learn quantum programming with Qiskit, and that is a sensible start. But the quantum software world has several widely used frameworks, and sooner or later you will meet code written in one of the others. Two of the most important are Cirq, developed by Google Quantum AI, and PennyLane, developed by Xanadu. They are not copies of Qiskit with different names. Each was built around a different idea of what a quantum program is for, and learning those ideas makes you a better quantum programmer in any framework.

Cirq is built around the physical circuit: gates placed on qubits in time slices called moments, with a strong emphasis on how a real device constrains what you can run. PennyLane is built around differentiable programming: a quantum circuit is a function that you can take the gradient of, so that quantum circuits can be trained like neural networks. This lesson explains both ideas, works through a gradient calculation by hand that you can check with a calculator, and gives you a concept map so that you can translate between the three frameworks.

An honest note about evidence. Neither Cirq nor PennyLane is installed in the environment where I prepared this lesson, so none of the Cirq or PennyLane code below was run by me. The code follows examples and descriptions on the official pages I opened, and I mark each listing as not run. The numbers in the lesson, such as the gradient and the training run, are my own calculations with NumPy and are exact for the formulas stated.

What you will learn

  • What Cirq and PennyLane are for, from their official descriptions
  • How a Cirq circuit is organised: qubits, operations, moments, simulators, devices
  • What a QNode is, and how PennyLane differentiates a quantum circuit
  • The parameter-shift rule, derived and checked numerically
  • A concept map between Qiskit, Cirq and PennyLane, including the bit-order trap
  • How to choose a framework for a given task

Helpful first: Your First Qiskit Circuit, Choosing Your First Quantum Framework, Variational Quantum Eigensolver.

Why there is more than one framework

A quantum programming framework does three jobs. It lets you describe a circuit, it sends the circuit to something that runs it (a simulator or a device), and it helps you handle the results. Frameworks differ in what they make easy. A framework that comes from a hardware company tends to make that company's devices convenient to use. A framework that comes from a research group may emphasise a particular style of algorithm. The choice of a framework is therefore partly a choice about what kind of work you want to do.

FrameworkDeveloped byCentral idea (from official descriptions)
QiskitIBMCircuits and tooling around IBM quantum hardware and simulators; covered in the earlier lessons of this course
CirqGoogle Quantum AIWriting, manipulating and optimising circuits for NISQ hardware, where device details strongly affect results
PennyLaneXanaduCross-platform quantum computing, quantum machine learning and quantum chemistry, with automatic differentiation of circuits

Three widely used frameworks and their stated focus. The Qiskit entry reflects the earlier lessons; the Cirq and PennyLane entries come from their official pages.

The Cirq page that I opened describes it as a Python library for writing, manipulating and optimising quantum circuits and then running them on quantum computers or simulators, aimed at noisy intermediate-scale quantum (NISQ) hardware, where device details strongly affect the results. The PennyLane page describes it as a cross-platform Python library for quantum computing, quantum machine learning and quantum chemistry, open source under the Apache 2.0 licence and developed by Xanadu. Those two sentences already tell you what each is for.

You do not have to choose forever

Frameworks overlap more than their marketing suggests. PennyLane has plugins that let a PennyLane program run on devices from other frameworks, and the PennyLane paper lists plugins for Qiskit and Cirq among others. Knowing a second framework mainly gives you a second way of thinking.

Cirq: the circuit, as a physical object

The objects

In Cirq you work with a small number of objects. A qubit is an object you create, for example a GridQubit at row 0 and column 0, which says where the qubit sits on a two-dimensional chip. A gate is an operation such as X or H, and applying a gate to a qubit gives an operation. A Circuit is an ordered collection of operations. Operations are grouped into Moments, which are layers of operations that happen at the same time and so cannot share a qubit. The official page highlights this point: you have control over how operations are placed into moments, and that matters on hardware, where the depth of the circuit (the number of moments) determines how long the qubits must survive.

The page lists these main features. Circuit construction with control of moments. Device definitions, which encode hardware constraints so that you can check whether a circuit is practical for a given device. Simulation, with built-in wave function and density matrix simulators, including noisy channels, and compatibility with qsim, a high-performance wave function simulator. A Quantum Virtual Machine, which runs circuits on simulated hardware that mimics a device's constraints and noise. And the use of Cirq to run experiments on Google's quantum processors. The README adds that Cirq installs with pip and requires a recent Python (the version I read states Python 3.11 or later) on Linux, macOS and Windows, and also works in Google Colab.

The first program

The official page's example creates one qubit, applies a square-root-of-NOT gate (written as X raised to the power 0.5), measures the qubit with a key named m, and runs the circuit 20 times on a built-in simulator. The README says the sample output begins with m=11000111111011001000. I count 11 ones and 9 zeros in those 20 characters (my count). Is that consistent with a fair 50-50 outcome? The square root of NOT takes |0⟩ to an equal superposition up to phase, so the exact probability of 1 is 0.5.

Observed ones out of 20Probability under p = 0.5 (my calculation)
Exactly 100.1762
Between 8 and 12 inclusive0.7368
6 or fewer, or 14 or more0.1153

Binomial probabilities for 20 fair shots. A result of 11 ones is entirely ordinary. The standard error of the observed fraction with 20 shots is √(0.25/20) ≈ 0.112, which is large.

The lesson from that table is the same as in the simulator problems lesson: with only 20 shots you cannot tell 50-50 from 40-60. The official example uses 20 repetitions because it is a demonstration, not a measurement.

A Bell state in Cirq (not run)

The following program builds the same Bell state that you built in Qiskit. I did not run it; it uses standard Cirq functions that follow the style of the official examples.

import cirq

q0, q1 = cirq.LineQubit.range(2)
circuit = cirq.Circuit(
    cirq.H(q0),
    cirq.CNOT(q0, q1),
    cirq.measure(q0, q1, key='m'),
)
print(circuit)

result = cirq.Simulator().run(circuit, repetitions=100)
print(result.histogram(key='m'))
# expected: about half 0 (00) and half 3 (11); no 1 or 2 in an ideal simulation
A Bell-state program in Cirq. Not run in this project; the expected pattern follows from the physics and my own simulation of the circuit.

Check the bit order before you compare

In my understanding, Cirq's histogram of a multi-qubit measurement treats the first qubit as the most significant bit, the opposite of Qiskit's printed strings, where qubit 0 is the rightmost character. I am stating this from general knowledge, not from a page I opened, so check the documentation for your version. For a Bell state the answer is symmetric, so the difference does not show up; for X on one qubit it does. Use the single-X test from the simulator problems lesson on any new framework.

PennyLane: the circuit as a differentiable function

PennyLane starts from a different question. Suppose a circuit has adjustable angles, as in the variational algorithms of the VQE and QAOA lessons. To tune them you need to know how the output changes when an angle changes, that is, the gradient. Machine learning frameworks compute gradients automatically for classical functions. The PennyLane paper, whose abstract and main text I opened (arXiv 1811.04968), explains how to extend this idea to quantum circuits: a quantum circuit evaluated on a device is treated as a black box inside a larger computation, and the framework computes its gradient directly by running the circuit, so that gradients flow through hybrid quantum-classical computations.

The objects

Three objects are enough to start. A device is a simulator or hardware backend; the paper lists built-in devices such as default.qubit and plugins for other frameworks and hardware. A QNode is a quantum node: a Python function that applies gates and returns a measurement result, bound to a device. And an optimizer takes steps that change the parameters to reduce a cost. The paper's first code example defines a single-qubit QNode that applies a rotation about X and a rotation about Y and returns the expectation value of the Pauli Z operator, and then takes a gradient-descent step.

import pennylane as qml

dev = qml.device('default.qubit', wires=1)

@qml.qnode(dev)
def circuit(params):
    qml.RX(params[0], wires=0)
    qml.RY(params[1], wires=0)
    return qml.expval(qml.PauliZ(0))

print(circuit([0.54, 0.12]))
# expected: cos(0.54) * cos(0.12) = 0.8515
A one-qubit QNode in the style of the PennyLane paper's first example (not run). The expected value is my own calculation.

The expected value in the last line follows from the physics: RX(a) then RY(b) on |0⟩ gives ⟨Z⟩ = cos a · cos b, and with a = 0.54 and b = 0.12 that is 0.8515 by my calculation. A useful habit is to check a QNode against such a closed-form value before trusting it on a harder problem.

A note on names

The PennyLane paper and older tutorials write qml for the module name and qml.qnode for the decorator. The current documentation pages I opened for gradients use a different short name, qp, in their examples. The functions are the same idea, but the alias differs between versions and pages, so copy the import line from the documentation of the version you have installed.

The parameter-shift rule, derived and checked

How does PennyLane get a gradient from a device that can only return expectation values? On hardware you cannot run backpropagation through the quantum state. The paper describes the parameter-shift rule: evaluate the circuit at two shifted values of the parameter and combine the results. It is exact for gates whose generator has two distinct eigenvalues, which includes the standard rotations. Here is the simplest case, which you can verify by hand.

Take Ry(θ) on |0⟩. The expectation value of Z is f(θ) = cos θ. The exact derivative is f′(θ) = −sin θ. The parameter-shift rule says f′(θ) = [f(θ + π/2) − f(θ − π/2)]/2. Check: f(θ + π/2) = cos(θ + π/2) = −sin θ, and f(θ − π/2) = cos(θ − π/2) = sin θ. The difference is −sin θ − sin θ = −2 sin θ, and half of that is −sin θ, as required. The rule uses only values of the function itself, not of its slope.

Method at θ = 0.7Value of f′(θ) (my calculation)Error compared with exact −0.644218
Exact: −sin(0.7)−0.6442180
Parameter shift with shifts of π/2−0.6442180 (exact to floating-point precision)
Finite difference, step 0.1−0.681355about 0.037
Finite difference, step 0.001−0.644600about 0.0004
Finite difference, step 10^-6−0.644218about 4 × 10^-7 on an ideal simulator

Derivative of cos θ at θ = 0.7 by several methods. On real hardware, finite differences with a tiny step fail because shot noise swamps the small difference; the parameter-shift rule uses large shifts, which keeps the signal well above the noise.

That last remark is the practical reason for the rule. On a real device each expectation value is estimated from shots and has an error of about 1/√N. A finite difference with a step of 10^-6 divides a tiny difference by a tiny number, and the noise is amplified by a million. The parameter-shift rule evaluates the circuit at points π/2 away, where the values differ substantially, so the noise is not amplified. The cost is two circuit evaluations per parameter: for a circuit with 100 trainable parameters, one gradient needs about 200 circuit runs (my arithmetic), each with its own shots, which is why training on hardware is expensive.

Training a circuit: a run you can check

To see the machinery in action, use the one-parameter circuit above and minimise the cost f(θ) = ⟨Z⟩ = cos θ. The minimum is −1, at θ = π, where the qubit is in |1⟩. Gradient descent updates θ ← θ − η f′(θ). With the exact gradient −sin θ, a learning rate η = 0.25 and a start at θ = 0.5, my NumPy calculation gives the following.

Stepθ⟨Z⟩ = cos θGradient −sin θ
00.50000.8776−0.4794
10.61990.8140−0.5809
20.76510.7213−0.6926
30.93820.5912−0.8065
51.36700.2024−0.9793
102.5004−0.8014−0.5982
152.9816−0.9872−0.1593
203.1035−0.9993−0.0381

Gradient descent on cos θ with learning rate 0.25 from θ = 0.5. The cost approaches its minimum of −1 as θ approaches π ≈ 3.1416. Computed with the exact gradient on an ideal simulator.

Notice the shape: the gradient is small at the start (the cost is flat near θ = 0), grows to nearly −1 around θ = 1.4, and shrinks again near the minimum. The progress is slow at both ends. Real variational problems have many parameters, noisy gradients and a much more complicated landscape, which is why the lessons on VQE and QAOA discuss barren plateaus and optimiser choice. But the mechanism you just followed is the one that every PennyLane training loop uses.

Choosing a differentiation method

PennyLane offers several ways to obtain gradients. The gradients page that I opened lists them, and the choice depends on whether you are using a simulator or hardware and whether you use shots.

MethodWorks onNotes from the documentation page
backpropStatevector simulators onlyStandard backpropagation; does not work with finite-shot estimation
adjointStatevector simulators onlyReverses through the circuit with inverse gates; much less memory than backprop; raises an error when shots are used, since it is analytic only
parameter-shiftSimulators and hardwareThe analytic shift rule, with finite differences as a fallback
finite-diffSimulators and hardwareNumerical differences
deviceDevice-specificUses a gradient computed by the device itself
best (default)AutomaticChooses in the order device, backprop, parameter-shift, finite differences

Differentiation methods in PennyLane, as summarised from the gradients documentation. Support varies with the interface, return type and shot count; check the current page for your version.

The page also lists the supported interfaces: NumPy, PyTorch and JAX (TensorFlow is described as no longer maintained as of version 0.44, which is another reminder that framework details change). You choose one with the interface argument on the QNode. In a hybrid model the QNode sits inside a classical network: a PyTorch layer feeds numbers to the circuit as parameters, the circuit returns expectation values, and the gradient flows back through both.

Noise, density matrices and the real cost of training

Why Cirq offers a density-matrix simulator

The Cirq page lists both wave function and density matrix simulators, including noisy channels. The reason for two kinds is that noise turns a pure state into a mixed one. A state vector can describe only a pure state. A mixed state, a statistical mixture of possibilities, needs a density matrix, a table with 2^n by 2^n entries, which is covered in the density matrices lesson of this course. The alternative is the Monte Carlo approach the page also mentions: run the wave function simulation many times, inserting random errors in each run, and average the results.

A concrete example you can check. A depolarizing channel with probability p replaces the state ρ by (1 − p)ρ + (p/3)(XρX + YρY + ZρZ). Applied to |0⟩, the expectation value of Z becomes 1 − 4p/3. I verified this with a NumPy density-matrix calculation (my own code, using the standard definition of the channel above).

Error probability p⟨Z⟩ after the channel (my calculation)Formula 1 − 4p/3
0.010.986670.98667
0.050.933330.93333
0.100.866670.86667

Expectation value of Z for |0⟩ after a single-qubit depolarizing channel. The channel pulls the expectation value toward zero, which is the value for a completely mixed qubit.

The price of the density-matrix method is memory. The matrix has 4^n entries, each 16 bytes, so n qubits need 4^n × 16 bytes (my arithmetic).

QubitsState vector (16 × 2^n bytes)Density matrix (16 × 4^n bytes)
1016 KiB16 MiB
1264 KiB256 MiB
14256 KiB4 GiB
15512 KiB16 GiB
161 MiB64 GiB

Memory for exact noisy simulation compared with ideal simulation. A density matrix doubles the exponent: 15 qubits already fill a 16 GiB machine.

That is why noisy simulations of 20 or more qubits use sampling methods instead, and why the choice of simulator in a framework is a real design decision and not a detail.

What a training run costs

Return to PennyLane and the parameter-shift rule. Imagine a small variational circuit with 4 qubits and 3 layers, with one trainable angle per qubit per layer, so 12 parameters. One gradient needs 2 × 12 = 24 circuit evaluations. If training takes 100 steps and each evaluation uses 1,000 shots, the total is 24 × 100 = 2,400 evaluations and 2,400,000 shots (my arithmetic). Suppose, only as an assumption for illustration, that a device processes 1,000 shots per second, a figure that is not from any source. Then the run needs 2,400 seconds, about 40 minutes, of pure device time, without queues, calibration or the extra evaluations needed to estimate several observables. With 120 parameters instead of 12, the time grows tenfold.

Why simulators come first

On a simulator with exact gradients (backprop or adjoint) the same 100 steps cost a few thousand cheap calculations. This is why every serious workflow first debugs the circuit and optimiser on a simulator, then moves to shots, then to noise, and only then to hardware.

Reading someone else's code in an unfamiliar framework

You will often meet a notebook in a framework that is not your own. A short routine makes this manageable. Treat it as a reading checklist, not a rule.

  1. Find the circuit. In Cirq, look for Circuit and the operations inside it. In PennyLane, look for the function decorated as a QNode. In Qiskit, look for QuantumCircuit.
  2. Find the qubit order. Is the register defined by indices, by named qubit objects or by wire labels? Which is the first?
  3. Find the output. Is it a sampled histogram, an exact probability vector or an expectation value? Each needs a different check.
  4. Find the number of shots. If there is none, the result is probably exact; if there is, expect sampling error of about 1/√N.
  5. Find the optimiser, if any, and the gradient method. For PennyLane, check the diff_method, and whether the combination with shots is supported.
  6. Reproduce one number by hand. Pick the smallest circuit or the first step and check it against a closed form, as done in this lesson for ⟨Z⟩ = cos a cos b.

Following these steps takes a few minutes and prevents most misunderstandings. In particular, step 6 builds the habit of trusting a framework only after you have seen it reproduce a number you computed yourself.

A complete worked example: a one-qubit energy problem

To bring the ideas together, here is a tiny version of the variational method. The task is to find the lowest energy of the one-qubit Hamiltonian H = Z + 0.5 X, where Z and X are the Pauli matrices. Written as a matrix, H = [[1, 0.5], [0.5, −1]]. Its eigenvalues are plus and minus the square root of 1.25, that is ±1.11803, so the true ground-state energy is −1.11803. I confirmed this with NumPy's eigenvalue routine (my calculation).

The variational method guesses the state with a rotation, |ψ(θ)⟩ = Ry(θ)|0⟩, and measures the energy. For this state ⟨Z⟩ = cos θ and ⟨X⟩ = sin θ, so the energy is E(θ) = cos θ + 0.5 sin θ. A circuit cannot measure Z and X at the same time, since they do not commute. So each term needs its own measurement setting: one set of shots in the Z basis and another set in the X basis (that is, with a Hadamard before measuring). This is a basic fact about measuring a Hamiltonian made of non-commuting terms, and it is the reason variational algorithms need many circuit runs.

import pennylane as qml

dev = qml.device('default.qubit', wires=1)

@qml.qnode(dev)
def z_term(theta):
    qml.RY(theta, wires=0)
    return qml.expval(qml.PauliZ(0))

@qml.qnode(dev)
def x_term(theta):
    qml.RY(theta, wires=0)
    return qml.expval(qml.PauliX(0))

def energy(theta):
    return z_term(theta) + 0.5 * x_term(theta)
# expected at theta = 0.5: cos(0.5) + 0.5*sin(0.5) = 1.1173
The energy of H = Z + 0.5 X as two QNodes (not run). The expected value is my own calculation.

Now minimise E(θ) with gradient descent using the parameter-shift rule, a learning rate of 0.4 and a start at θ = 0.5. The exact minimum is at θ = π + arctan(0.5) = 3.6052, where E = −√1.25. My NumPy run of the descent, with shifted evaluations of E itself, gives the following.

StepθE(θ)Gradient
00.50001.11730−0.0406
10.51631.11649−0.0588
30.57381.11126−0.1229
50.69391.08854−0.2551
81.14760.86659−0.7064
101.79810.26175−1.0870
153.4194−1.09877−0.2066
203.5956−1.11798−0.0108
303.6052−1.118030.0000

Gradient descent on E(θ) = cos θ + 0.5 sin θ with exact parameter-shift gradients. The run reaches the true ground-state energy −1.11803.

Two features of the table are worth noticing. First, the start at θ = 0.5 is very close to the top of the energy landscape, where E is nearly at its maximum of +1.118 and the gradient is almost zero. The descent takes a few steps to get going, and then accelerates, a small version of the flat-start problem that makes training hard in large circuits. Second, the final energy matches the exact eigenvalue to five decimals, which is the check that a variational method must pass on a problem small enough to solve exactly. On a hardware run with shots, each of the 30 steps would need four evaluations (two shifted values for each of the two terms), a total of 120 evaluations, each with its own sampling noise.

The general lesson

A variational algorithm is a loop of three parts: a circuit with parameters, a measurement procedure that estimates the cost, and a classical optimiser. Frameworks differ in how they package these parts, and PennyLane packages them around differentiation. The example above contains all three in thirty lines of algebra.

A concept map between Qiskit, Cirq and PennyLane

If you know one framework, the fastest way to learn another is a translation table. Below, the Cirq and PennyLane entries follow the official pages I opened; the Qiskit entries are the names used in the earlier lessons of this course. Check function names against your installed version, because all three change between releases.

TaskQiskitCirqPennyLane
Basic object for a programQuantumCircuitCircuit (made of Moments of operations)A QNode: a Python function bound to a device
A qubitIndex in a registerA qubit object, such as GridQubit or LineQubitA wire label on the device
Apply a gateqc.h(0)cirq.H(q)qml.Hadamard(wires=0)
Simulate exactlyStatevector or a simulatorBuilt-in wave function simulatordefault.qubit device
Sample with shotsRun on a sampler or backendsimulator.run(circuit, repetitions=n)Set shots on the device
Expectation valueEstimator or quantum_info toolsObservables and simulator toolsqml.expval(...) returned from the QNode
NoiseNoise models in the simulatorNoisy channels in wave function and density matrix simulatorsNoise channels on supported devices
Real hardwareIBM devicesGoogle's processors (per the official page)Via plugins for other frameworks and cloud services
GradientsAvailable through additional toolsNot the central focusBuilt in; central to the design

A concept map. The Qiskit column reflects the earlier lessons of this course; the Cirq column reflects the official Cirq page; the PennyLane column reflects the official PennyLane page and paper. Function names are indicative only and were not run.

The bit-order trap, again

The single most common error when translating a program is bit order. In the simulator problems lesson, the convention is that qubit 0 is the rightmost character of a printed string. Cirq, in my understanding, numbers measured bits so that the first listed qubit is the most significant, and PennyLane's probability arrays follow the order of the wires you ask for; I did not verify either from a page I opened. The safe method is a test: run X on a single qubit of a three-qubit register in each framework and see which position the 1 lands in. Do it once and write the answer in your notes.

Porting a circuit between frameworks: a worked checklist

Suppose you have a three-qubit circuit that applies X to the first qubit (qubit 0 in a Qiskit-style numbering) and nothing else, and you want to reproduce it in another framework. The physics is trivial: one qubit is 1 and two are 0. The difficulty is only in how each tool reports it. The table shows the two conventions, using the state-vector index as an integer, which is how many tools report results.

ConventionWhich bit is most significantPrinted string for X on the first qubitInteger index
Qubit 0 on the right (used in this course, and in Qiskit)The last qubit0011
First qubit most significant (my understanding of Cirq's histogram keys; unverified here)The first qubit1004

The same physical state reported in the two conventions. The integer is the binary string read as a number. If your ported program gives 4 where the original gave 1, bit order is the cause, not a bug in the physics.

The checklist for a port is therefore: first, write the closed-form answer for a simple circuit (as above); second, run that simple circuit in both frameworks and compare the raw output; third, write a small function that converts between the two orderings (reverse the string, or reverse the order of the wires you ask for); fourth, check the conversion on the GHZ state, which is symmetric and so should look identical, and on the single-X circuit, which is not and so exposes any error. Only then port the real circuit.

A final caution about gates, not only bit order. Some frameworks define a rotation gate by an angle in half-turns or by a global phase different from the one you expect. Two circuits that differ only by a global phase give the same probabilities (problem B4 in the simulator lesson), but a controlled version of a gate with a different global phase does not, because the phase becomes relative. When porting controlled rotations, check the exact matrix in the documentation of each framework, instead of assuming that two gates with the same name are identical.

Which one should you use?

There is no universally best choice, and the sources I opened do not claim one. A reasonable decision rule follows from what each framework emphasises.

If you want to...A natural choiceReason (from the official descriptions)
Run on IBM quantum computers and follow most beginner coursesQiskitClosest match to the courses and learning material that this site and IBM provide
Study how circuit layout and device constraints affect resultsCirqMoments, device definitions and the Quantum Virtual Machine are central
Experiment with Google hardware workflowsCirqThe official page says Cirq is used to run experiments on Google's processors
Train circuits by gradient descent, or build hybrid models with PyTorch or JAXPennyLaneBuilt-in differentiation and interfaces for NumPy, PyTorch and JAX
Try the same algorithm on several back endsPennyLanePlugins connect it to other frameworks and services
Do a first course in quantum computingQiskit (or any one framework)Learn the concepts once; they transfer

A decision table. The reasons come from the official descriptions; the recommendations are my own judgement.

Learn concepts, not syntax

Gate definitions, circuit identities, algorithms and error models are the same in every framework. If you change framework, you relearn function names, not physics. The most valuable thing you can do is to write the same small program in two frameworks and check that the exact probabilities agree.

A cross-framework exercise

Here is a short exercise that builds real understanding. Take the three-qubit GHZ circuit (H on q0, then CNOT from q0 to q1, then CNOT from q1 to q2). Write it in Qiskit, Cirq and PennyLane. Compute exact probabilities in each: they should all be 0.5 for the all-zeros string and 0.5 for the all-ones string, with every other outcome exactly zero. Now change the circuit to apply X to the first qubit only before everything else and see which string appears in each framework. The two programs will agree on the physics and may disagree on the printed string, and finding out why is the real lesson.

Pitfalls and version warnings

  • Versions move quickly. The gradients page I opened says TensorFlow is no longer maintained as of PennyLane version 0.44, and it uses a different short alias in its examples than older material. Copy code from the documentation that matches your installed version.
  • Python version. The Cirq README I read states a requirement of Python 3.11 or later. Check the current requirement before installing.
  • Shots against exact. In PennyLane, adjoint differentiation raises an error with finite shots, and backprop does not work with finite-shot estimation, per the gradients page. If you switch a notebook from exact to sampled mode and the gradient method breaks, this is the reason.
  • Hardware gradients are costly. Two circuit evaluations per parameter, each with many shots, is a lot of runs. Test on a simulator first.
  • Different measurement conventions. Probabilities, samples and expectation values are returned in different shapes and orders in different frameworks. Test with a known circuit.
  • Unverified code. None of the code in this lesson was run by me. Always run a known circuit first and compare with the closed-form answers shown here.

Mini projects

  1. Reproduce the training table above in PennyLane. Define the one-qubit circuit with RY, return the expectation value of Z, use gradient descent with learning rate 0.25 from θ = 0.5, and compare each step with the table. If your numbers differ, find out why.
  2. Write the Bell state in Cirq and Qiskit, compare the exact probabilities, then compare the sampled counts using the standard-error method from the simulator problems lesson.
  3. Take one variational circuit with two parameters and compute its gradient three ways: parameter shift, finite differences with a large step and finite differences with a tiny step, using sampled shots. Observe how shot noise destroys the tiny-step result.

Check your understanding

Check yourself

What is a Moment in Cirq and why does it matter?

A Moment is a layer of operations that happen at the same time and so cannot share a qubit. The number of moments is the circuit depth, which determines how long qubits must survive on real hardware, so controlling moment placement matters.

What is a QNode in PennyLane?

A Python function that applies gates and returns a measurement result, bound to a device. It is treated as a black box whose gradient can be obtained by running the circuit.

Verify the parameter-shift rule for f(θ) = cos θ.

[cos(θ + π/2) − cos(θ − π/2)]/2 = [−sin θ − sin θ]/2 = −sin θ, which equals the exact derivative.

A circuit has 60 trainable parameters, and the parameter-shift rule uses 2 evaluations per parameter. How many circuit evaluations does one gradient need?

2 × 60 = 120 evaluations, each of which is usually run with many shots.

Why can finite differences with a tiny step fail on real hardware?

Shot noise of about 1/√N on each evaluation gets divided by the tiny step, so the noise in the gradient is amplified enormously. The parameter-shift rule uses large shifts and avoids this.

Which differentiation methods in PennyLane work on hardware, according to the gradients page?

Parameter-shift and finite differences (and device-provided gradients). Backprop and adjoint work only on statevector simulators.

References and further reading

Descriptions come from the official Cirq and PennyLane pages and the PennyLane paper, opened in December 2026. No Cirq or PennyLane code was run; all computed numbers are my own NumPy calculations.

  1. Cirq (official page) (Google Quantum AI) Opened. Description, features (moments, devices, simulators, Quantum Virtual Machine, hardware experiments), the one-qubit example and the list of guides.
  2. Cirq README (GitHub, quantumlib/Cirq) Opened. Install with pip; Python 3.11 or later; qsim integration; the 'Hello Qubit' example with 20 repetitions.
  3. PennyLane: automatic differentiation of hybrid quantum-classical computations (arXiv (Bergholm et al.)) Opened. Differentiating quantum circuits, parameter-shift rule, hybrid computation, devices and plugins, first code example.
  4. PennyLane documentation: introduction (Xanadu) Opened. Cross-platform library for quantum computing, quantum machine learning and quantum chemistry; Apache 2.0; interfaces and plugins.
  5. PennyLane documentation: gradients and training (Xanadu) Opened. Interfaces (NumPy, PyTorch, JAX), differentiation methods and their limits, and the default selection order.