Skip to content

Lesson 39: Google Cirq

39.1 Learning Outcomes

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

  1. Build circuits in Cirq using qubits, moments and operations.
  2. Explain Cirq's explicit hardware model and how it differs from Qiskit's.
  3. Use cirq.Simulator for statevector and sampled simulation.
  4. Work with device constraints, native gate sets and Google's Sycamore architecture.
  5. Choose between Cirq and Qiskit for a given task.

39.2 Cirq's Design Philosophy

Google built Cirq around one principle: the programmer should see the hardware. Where Qiskit abstracts the device away and lets the transpiler sort it out, Cirq makes qubit identity, gate scheduling and device constraints explicit in the source code.

Concept Qiskit Cirq
Qubit index into a register (0, 1, …) a named object (LineQubit(0), GridQubit(1,2))
Circuit ordered list of instructions ordered list of Moments
Timing implicit; transpiler schedules explicit in the moment structure
Device applied at transpile time a first-class object that validates as you build
Philosophy abstract away the hardware expose the hardware

39.3 Qubits, Moments and Circuits

Qubit types

import cirq

q0, q1, q2 = cirq.LineQubit.range(3)         # a 1-D chain: q(0), q(1), q(2)
g = cirq.GridQubit(2, 3)                     # 2-D grid position (row 2, col 3)
n = cirq.NamedQubit('alice')                 # arbitrary label

grid = cirq.GridQubit.rect(3, 3)             # a 3x3 grid of 9 qubits

Why named qubits matter. GridQubit(1,2) and GridQubit(1,3) are adjacent by construction, so Cirq can validate connectivity as you write the circuit rather than discovering the problem at transpile time.

Moments — the key abstraction

A Moment is a set of operations that execute simultaneously on disjoint qubits. A circuit is an ordered list of moments.

circuit = cirq.Circuit([
    cirq.Moment([cirq.H(q0), cirq.H(q1)]),        # both Hadamards run in parallel
    cirq.Moment([cirq.CNOT(q0, q1)]),
    cirq.Moment([cirq.measure(q0, q1, key='m')]),
])
print(circuit)
0: ───H───@───M('m')───
          │   │
1: ───H───X───M────────

Moment count = circuit depth, directly and visibly. In Qiskit you call .depth() and hope the transpiler did what you wanted; in Cirq the depth is the structure of your source code.

Insert strategies

When you append without specifying moments, Cirq chooses how to pack the operations:

circuit = cirq.Circuit()
circuit.append([cirq.H(q0), cirq.H(q1)], strategy=cirq.InsertStrategy.EARLIEST)
Strategy Behaviour
EARLIEST pack into the earliest moment with free qubits (default, minimises depth)
NEW every operation gets its own moment (maximum depth)
INLINE insert into the previous moment if possible
NEW_THEN_INLINE new moment first, then inline the rest

39.4 Gates

# single-qubit
cirq.X(q0), cirq.Y(q0), cirq.Z(q0), cirq.H(q0), cirq.S(q0), cirq.T(q0)
cirq.rx(theta)(q0), cirq.ry(theta)(q0), cirq.rz(theta)(q0)

# powers -- Cirq's distinctive feature
cirq.X**0.5      # sqrt(X)
cirq.Z**0.25     # T gate
cirq.X**t        # continuously parameterised

# two-qubit
cirq.CNOT(q0, q1), cirq.CZ(q0, q1), cirq.SWAP(q0, q1)
cirq.ISWAP(q0, q1)
cirq.CZ**0.5

# three-qubit
cirq.TOFFOLI(q0, q1, q2), cirq.FREDKIN(q0, q1, q2)

# Google hardware-native
cirq.FSimGate(theta, phi)(q0, q1)
cirq.SQRT_ISWAP(q0, q1)

The ** operator is Cirq's signature. Any gate can be raised to a real power: \(G^{t} = \exp(i\pi t\,\log G/(i\pi))\). This makes continuously parameterised gates natural — \(X^{0.5}\) is the "half-NOT", and \(Z^{0.25} = T\).

39.5 Simulation

Statevector

sim = cirq.Simulator()

circuit = cirq.Circuit([cirq.H(q0), cirq.CNOT(q0, q1)])
result = sim.simulate(circuit)

print(result.final_state_vector)
# [0.70710677+0.j  0.+0.j  0.+0.j  0.70710677+0.j]

print(cirq.dirac_notation(result.final_state_vector))
# 0.71|00⟩ + 0.71|11⟩

Sampling

circuit.append(cirq.measure(q0, q1, key='result'))
samples = sim.run(circuit, repetitions=1000)

print(samples.histogram(key='result'))
# Counter({0: 508, 3: 492})       -- integers, not bitstrings!

Cirq reports outcomes as integers, not bitstrings: 0 = 00, 3 = 11. Convert with format(k, '02b'). Cirq is big-endian — the first qubit in the measure call is the most significant bit — which is the opposite of Qiskit and matches this course's textbook convention.

Step-by-step simulation

for i, step in enumerate(sim.simulate_moment_steps(circuit)):
    print(f"moment {i}: {cirq.dirac_notation(step.state_vector())}")

Excellent for teaching — it prints the state after every moment, letting students watch superposition and entanglement appear.

Density matrix and noise

noisy = circuit.with_noise(cirq.depolarize(p=0.01))
dm_sim = cirq.DensityMatrixSimulator()
result = dm_sim.simulate(noisy)
print(result.final_density_matrix)

Cirq's noise channels: cirq.depolarize, cirq.amplitude_damp, cirq.phase_damp, cirq.bit_flip, cirq.phase_flip, cirq.asymmetric_depolarize.

Parameter sweeps — a Cirq strength

import sympy

theta = sympy.Symbol('theta')
circuit = cirq.Circuit([cirq.ry(theta)(q0), cirq.measure(q0, key='m')])

sweep = cirq.Linspace(key='theta', start=0, stop=np.pi, length=20)
results = sim.run_sweep(circuit, params=sweep, repetitions=1000)

for r in results:
    print(r.params['theta'], r.histogram(key='m'))

One symbolic circuit, many parameter values, one call. This is how variational algorithms are written in Cirq, and it is cleaner than Qiskit's assign_parameters loop.

39.6 Devices and Hardware Constraints

Validation as you build

import cirq_google

device = cirq_google.Sycamore
print(device.metadata.qubit_set)          # which GridQubits exist
print(device.metadata.gateset)            # which gates are native

# Cirq REFUSES an invalid circuit immediately:
q_a = cirq.GridQubit(3, 3)
q_b = cirq.GridQubit(6, 6)                # far apart -- not connected
bad = cirq.Circuit([cirq.CZ(q_a, q_b)])
device.validate_circuit(bad)
# ValueError: Qubits (3,3) and (6,6) are not adjacent

Compare with Qiskit, which accepts the circuit and silently inserts a long chain of SWAPs. Cirq's approach forces the programmer to confront the topology — more work, but no surprises.

Sycamore's native gates

Gate Form Notes
SYC \(\mathrm{FSim}(\pi/2, \pi/6)\) the native two-qubit gate
SQRT_ISWAP \(\mathrm{FSim}(\pi/4, 0)\) the newer calibrated gate
PhasedXZGate arbitrary single-qubit one physical pulse
Z virtual free — implemented by shifting the phase reference

Virtual Z gates are a genuinely important optimisation. A \(Z\) rotation on superconducting hardware needs no pulse at all — it is a bookkeeping change to the phase of subsequent pulses. So \(R_z\) gates are error-free and take zero time, which is why the standard basis is \(\{R_z, \sqrt X, \text{CZ}\}\): put all the angles into free \(R_z\)s.

Transpiling for a device

converted = cirq.optimize_for_target_gateset(
    circuit, gateset=cirq_google.SycamoreTargetGateset())

router = cirq.RouteCQC(device.metadata.nx_graph)
routed = router(circuit)

39.7 Solved Problems

Problem 1 — Building the same Bell state in Cirq and Qiskit

Write the Bell-state circuit in both frameworks and compare the outputs, being explicit about endianness.

Solution.

Cirq.

import cirq

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

result = cirq.Simulator().run(circuit, repetitions=1000)
print(result.histogram(key='m'))
# Counter({0: 508, 3: 492})

Qiskit.

from qiskit import QuantumCircuit
from qiskit_aer.primitives import SamplerV2 as Sampler

qc = QuantumCircuit(2, 2)
qc.h(0); qc.cx(0, 1); qc.measure([0,1],[0,1])
print(Sampler().run([qc], shots=1000).result()[0].data.c.get_counts())
# {'00': 495, '11': 505}

Comparison.

Cirq Qiskit
Output format Counter({0: 508, 3: 492}) {'00': 495, '11': 505}
Encoding integers bitstrings
Endianness big-endian (first measured qubit = MSB) little-endian (qubit 0 = LSB)

Converting Cirq's integers. 0 → '00', 3 → '11':

counts = {format(k, '02b'): v for k, v in result.histogram(key='m').items()}
# {'00': 508, '11': 492}

For the Bell state the two agree because 00 and 11 are palindromes. They will disagree on any asymmetric state.

Asymmetric test. Apply \(X\) to qubit 0 only:

Framework Reported Meaning
Cirq 2 = '10' \(q_0 = 1\), \(q_1 = 0\) ✓ (big-endian)
Qiskit '01' \(q_0 = 1\), \(q_1 = 0\) ✓ (little-endian)

Both are correct; they simply print the bits in opposite orders. Always run this test when porting code between frameworks.

Problem 2 — Moments and circuit depth

Build a 4-qubit circuit applying \(H\) to all qubits, then CNOTs (0,1) and (2,3), then CNOT(1,2). Count moments under the EARLIEST and NEW strategies.

Solution.

import cirq
qs = cirq.LineQubit.range(4)

circuit = cirq.Circuit([
    cirq.H.on_each(*qs),
    cirq.CNOT(qs[0], qs[1]), cirq.CNOT(qs[2], qs[3]),
    cirq.CNOT(qs[1], qs[2]),
])
print(circuit)
print("moments (depth):", len(circuit))

Output.

0: ───H───@───────
          │
1: ───H───X───@───
              │
2: ───H───@───X───
          │
3: ───H───X───────

moments (depth): 3

Moment analysis (EARLIEST, the default).

Moment Operations Qubits used
0 \(H, H, H, H\) all 4 — fully parallel
1 CNOT(0,1), CNOT(2,3) 0,1,2,3 — disjoint, so parallel
2 CNOT(1,2) 1,2 — must wait for moment 1
\[ \text{depth} = \mathbf{3} \]

Under NEW. Every operation gets its own moment:

\[ 4\ (\text{Hadamards}) + 3\ (\text{CNOTs}) = \mathbf{7\ \text{moments}} \]

Why this matters physically. Depth 3 versus depth 7 means the circuit occupies the hardware for 3 gate-times instead of 7. With \(T_2 = 100\ \mu\)s and \(t_{\text{CX}} = 300\) ns, decoherence per circuit falls proportionally:

\[ F_{\text{depth }3} \approx e^{-3\times0.3/100} = 0.991, \qquad F_{\text{depth }7} \approx e^{-7\times0.3/100} = 0.979 \]

Cirq makes this trade-off visible in the source code; in Qiskit it is buried in the transpiler's scheduling pass.

Problem 3 — QAOA in Cirq with a parameter sweep

Implement \(p=1\) QAOA for a 3-vertex path graph (edges 0-1, 1-2) in Cirq, sweeping \((\gamma,\beta)\) to find the optimum.

Solution.

import cirq, sympy, numpy as np

qs = cirq.LineQubit.range(3)
edges = [(0, 1), (1, 2)]
gamma, beta = sympy.Symbol('g'), sympy.Symbol('b')

circuit = cirq.Circuit()
circuit.append(cirq.H.on_each(*qs))                       # |+++>

# cost unitary: exp(-i gamma Z_i Z_j / 2) per edge
for i, j in edges:
    circuit.append([cirq.CNOT(qs[i], qs[j]),
                    cirq.rz(gamma)(qs[j]),
                    cirq.CNOT(qs[i], qs[j])])

# mixer
circuit.append(cirq.rx(2 * beta).on_each(*qs))
circuit.append(cirq.measure(*qs, key='m'))

def cut_value(bits):
    return sum(1 for i, j in edges if bits[i] != bits[j])

sim = cirq.Simulator()
sweep = (cirq.Linspace('g', 0, np.pi, 15) *
         cirq.Linspace('b', 0, np.pi/2, 15))
results = sim.run_sweep(circuit, params=sweep, repetitions=1000)

best = max(results, key=lambda r: np.mean([cut_value(row) for row in r.measurements['m']]))
print("best params:", best.params)
print("mean cut   :", np.mean([cut_value(r) for r in best.measurements['m']]))

Expected output.

best params: {'g': 1.795, 'b': 0.673}
mean cut   : 1.87

Analysis.

  • Maximum cut. The path \(0-1-2\) is bipartite: colour \(\{0,2\}\) one way and \(\{1\}\) the other, so \(C_{\max} = \mathbf{2}\) (both edges cut).
  • Random baseline. Each edge is cut with probability \(\frac12\), so \(\langle C\rangle_{\text{random}} = \mathbf{1.0}\).
  • QAOA \(p=1\) result: \(\langle C\rangle = 1.87\).
\[ \text{approximation ratio} = \frac{1.87}{2} = \mathbf{0.935} \]

Very good for \(p=1\) — better than the 0.6924 worst-case guarantee (L34), because the path graph is easy: it is bipartite, tree-like, and has no odd cycles to frustrate the optimisation.

The Cirq advantage on display. run_sweep with the product of two Linspace objects evaluates \(15\times15 = 225\) parameter combinations in one call, with the symbolic circuit compiled once. The equivalent Qiskit code requires an explicit loop over assign_parameters.

Problem 4 — Device validation and routing cost

A circuit needs CZ between GridQubit(0,0) and GridQubit(2,2) on Sycamore. Show that validation fails, compute the routing cost, and give two fixes.

Solution.

Validation.

q_a, q_b = cirq.GridQubit(0, 0), cirq.GridQubit(2, 2)
circuit = cirq.Circuit([cirq.CZ(q_a, q_b)])
cirq_google.Sycamore.validate_circuit(circuit)
# ValueError: Qubit pair ((0,0), (2,2)) is not valid on this device

Distance. Sycamore's grid allows only horizontal and vertical neighbours, so the Manhattan distance applies:

\[ d = |2-0| + |2-0| = \mathbf{4\ \text{hops}} \]

Routing cost. Bringing the qubits adjacent needs \(d - 1 = 3\) SWAPs:

\[ 3\ \text{SWAPs}\times3\ \text{CZ-equivalents} + 1\ \text{CZ} = \mathbf{10\ \text{two-qubit gates}} \]

Fidelity at Sycamore's two-qubit error of \(\approx 6\times10^{-3}\):

\[ F = (1 - 0.006)^{10} = 0.994^{10} = \mathbf{0.9416} \]

One logical gate costs 5.8 % of the circuit fidelity.

Fix 1 — automatic routing.

router = cirq.RouteCQC(cirq_google.Sycamore.metadata.nx_graph)
routed = router(circuit)
print(len([op for m in routed for op in m if len(op.qubits) == 2]))   # ~10

Correct but expensive — it just does the SWAP insertion for you.

Fix 2 — redesign the qubit assignment. Choose logical-to-physical mappings so that interacting qubits are physically adjacent:

q_a, q_b = cirq.GridQubit(0, 0), cirq.GridQubit(0, 1)     # adjacent!
# cost: 1 CZ, fidelity 0.994
\[ \text{Fidelity improves from } 0.942 \text{ to } 0.994 \text{ — a } \mathbf{9.7\times} \text{ reduction in error.} \]

The design principle. For an algorithm with a known interaction graph — QAOA on a lattice, a 1-D chemistry chain, a surface code — map the problem graph onto the hardware graph by hand. Automatic routing is a fallback, not a strategy. This is exactly the discipline Cirq's validate-as-you-build design is meant to enforce.

Problem 5 — Choosing between Cirq and Qiskit

Recommend Cirq or Qiskit for each project, with reasoning.

(a) A first-year course introducing quantum computing. (b) Research on gate calibration for a 2-D superconducting array. (c) Running a VQE on IBM hardware. (d) Simulating a 1-D spin chain with nearest-neighbour gates. (e) Benchmarking a circuit across five hardware vendors.

Solution.

(a) Course introduction → Qiskit. Far more textbooks, tutorials, videos and Stack Overflow answers exist. IBM's free hardware access is generous and requires no institutional agreement. The Qiskit Textbook is a complete course resource. Cirq's explicit device model, though pedagogically honest, adds friction for beginners who should first grasp gates and measurement.

(b) Gate calibration research on a 2-D array → Cirq. GridQubit matches the physical layout exactly; FSimGate(theta, phi) parameterises the actual physical interaction, so calibration means fitting \(\theta\) and \(\phi\) per qubit pair — which Cirq expresses natively. cirq.experiments contains ready-made cross-entropy benchmarking and Floquet calibration routines. This is Cirq's home territory.

(c) VQE on IBM hardware → Qiskit. Only Qiskit talks to IBM Runtime. EstimatorV2 with resilience_level=2 gives zero-noise extrapolation and readout mitigation as configuration options rather than code you must write. Qiskit Nature supplies the chemistry Hamiltonians. Using Cirq here would mean exporting to OpenQASM and re-importing — possible, but pointless friction.

(d) 1-D spin chain → Cirq. LineQubit is the physical model. Moments make the Trotter-step structure explicit: each moment is one layer of the Trotter decomposition, so circuit depth equals the number of Trotter steps by construction. cirq.Linspace sweeps the evolution time in one call.

(e) Cross-vendor benchmarking → neither; use Amazon Braket. Braket provides one SDK and one account for IonQ, Rigetti, IQM and QuEra. Writing this in Cirq or Qiskit means maintaining separate provider integrations. (Braket does accept Cirq circuits via a plugin, so a reasonable hybrid is: write in Cirq, submit via Braket.)

Summary table.

Criterion Cirq Qiskit
Learning resources good excellent
Hardware transparency excellent good
Hardware access Google (restricted) IBM (open)
Parameter sweeps excellent (run_sweep) good
Error mitigation built in manual excellent (Runtime)
Chemistry / ML libraries OpenFermion, TFQ Qiskit Nature, ML, Optimization
Endianness big-endian (textbook) little-endian

They interoperate. cirq.qasm(circuit) and qiskit.qasm3.loads(...) move circuits between frameworks, so the professional answer is to use each where it is strongest.

39.8 Practice Problems

  1. Write a Cirq circuit for a 3-qubit GHZ state and print its Dirac notation.
  2. What does Cirq's histogram return for the state \(|101\rangle\) on 3 qubits? [Ans: {5: N}]
  3. Build a circuit with depth 2 using 4 qubits and 2 CNOTs.
  4. Compute the Manhattan routing cost for GridQubit(1,1) to GridQubit(4,3). [Ans: 5 hops, 4 SWAPs, 13 two-qubit gates]
  5. Express \(T\) using Cirq's power notation. [Ans: cirq.Z**0.25]
  6. Why are virtual \(Z\) gates free on superconducting hardware?
  7. Convert a Cirq histogram key 6 on 3 qubits to a bitstring. [Ans: '110']

39.9 Summary

  • Cirq's philosophy is hardware transparency: named qubits (LineQubit, GridQubit), explicit Moments (depth is visible in the source), and devices that validate circuits as you build them.
  • Moments are sets of simultaneous operations; len(circuit) is the depth, and InsertStrategy controls packing.
  • Gates support the ** power syntax: cirq.X**0.5, cirq.Z**0.25 == T.
  • cirq.Simulator gives statevectors, samples and moment-by-moment stepping (excellent for teaching); DensityMatrixSimulator handles noise.
  • run_sweep with symbolic parameters evaluates hundreds of parameter settings in one call — Cirq's standout feature for variational algorithms.
  • Cirq is big-endian and reports integers; Qiskit is little-endian and reports bitstrings. Always test with an asymmetric state when porting.
  • Virtual \(Z\) gates are free on superconducting hardware, which is why the native basis is \(\{R_z, \sqrt X, \text{CZ}\}\).
  • Choose Cirq for hardware-aware research and lattice-structured problems; Qiskit for teaching, IBM hardware and built-in error mitigation. They interoperate via OpenQASM.

Next lesson: L40 — PennyLane and differentiable quantum programming.

Practise now: unit4-platforms-lab.html → Circuit Builder: build a circuit and toggle between Qiskit, Cirq, PennyLane and Q# code emission, watching the moment structure and endianness change.