Variational Quantum Circuits and Training¶
Variational quantum circuits turn parameterised quantum gates into trainable machine learning models by pairing shallow quantum hardware with a classical optimiser. This section walks through the hybrid training loop, classical-to-quantum data encoding, ansatz architecture, exact hardware gradients via the parameter-shift rule, finite-shot noise, and Quantum Natural Gradient.
The Hybrid Quantum-Classical Training Loop¶
-
Imagine trying to tune an antique shortwave radio in an attic while your friend stands downstairs listening to the speaker and calling up "warmer" or "colder" after every tiny twist of the dial. That division of labour captures the exact spirit of near-term quantum machine learning.
-
Deep textbook algorithms like Shor's factoring or HHL (section 2) require millions of error-corrected physical qubits that remain years away. Today's Noisy Intermediate-Scale Quantum (NISQ) processors offer dozens to hundreds of noisy qubits whose delicate superpositions decohere after only a modest sequence of gates. To do useful machine learning on shallow, noisy circuits, researchers invented Variational Quantum Circuits (VQCs), also called Parameterised Quantum Circuits (PQCs) or Quantum Neural Networks (QNNs).
-
A VQC splits the workload cleanly across two processors. First, the quantum processor (QPU) encodes classical input data \(\mathbf{x}\) (if present), applies a shallow circuit \(U(\boldsymbol{\theta})\) whose rotation gate angles \(\boldsymbol{\theta} = (\theta_1, \dots, \theta_P)\) act as learnable weights, and estimates the expectation value of a task-specific Hermitian observable \(H\) across \(S\) repeated measurement shots.
- Second, a classical computer (CPU or GPU) reads that estimated scalar, computes the task loss \(L(\boldsymbol{\theta})\) and its gradient, and updates \(\boldsymbol{\theta}\) using an optimiser such as Adam, SPSA, or Quantum Natural Gradient before sending the refreshed angles back to the QPU. Because the circuit resets cleanly on every iteration, coherence only needs to survive one shallow forward pass at a time.
Encoding Classical Data Into Quantum States¶
-
Before a quantum circuit can classify images, predict molecular energies, or regress time series, classical numbers \(\mathbf{x} \in \mathbb{R}^d\) must be translated into a quantum state \(|\phi(\mathbf{x})\rangle = U_{\text{enc}}(\mathbf{x})|0\dots 0\rangle\). Think of this like packing a suitcase for a flight with strict carry-on rules. How you fold and arrange your belongings decides both how much fits inside and how painfully long unpacking takes.
-
Four main encoding strategies dominate quantum machine learning, each trading qubit count against circuit depth and expressivity.
- Basis encoding. Converts a discrete binary feature vector \(\mathbf{x} \in \{0, 1\}^n\) directly into the computational basis state \(|x_1 x_2 \dots x_n\rangle\) using Pauli-\(X\) gates on every
1bit. It is trivial in depth (\(O(1)\)) and natural for combinatorial logic, yet consumes one whole qubit per classical bit. - Angle encoding. Maps each continuous feature \(x_j\) (rescaled into \([-\pi, \pi]\)) onto the rotation angle of a dedicated qubit via \(R_y(x_j)\) or \(R_x(x_j)\). Angle encoding stays delightfully shallow (\(O(1)\) depth, hardware-friendly on NISQ chips) and uses \(n = d\) qubits, though without extra layers each feature enters only as a simple single-frequency cosine or sine.
- Amplitude encoding. Normalises a classical vector \(\mathbf{x} \in \mathbb{R}^{2^n}\) (\(\|\mathbf{x}\|_2 = 1\)) and packs all \(2^n\) numbers into the complex amplitudes of just \(n\) qubits (\(|\phi(\mathbf{x})\rangle = \sum_{j=0}^{2^n-1} x_j |j\rangle\)). While exponentially compact in qubit count, preparing an arbitrary dense amplitude vector generally demands an \(O(2^n)\)-depth state-preparation circuit!
- Data re-uploading. Inspired by how classical neural networks stack layers to gain nonlinear expressivity, data re-uploading (Pérez-Salinas and colleagues, 2020) repeatedly interleaves feature encoding blocks \(U_{\text{enc}}(\mathbf{x})\) with trainable parameter layers \(W(\boldsymbol{\theta}_\ell)\) across \(L\) layers. Even on a single qubit, re-uploading \(\mathbf{x}\) across \(L\) layers generates a truncated Fourier series containing frequencies up to \(\pm L\), turning a single qubit into a universal function approximator!
- Basis encoding. Converts a discrete binary feature vector \(\mathbf{x} \in \{0, 1\}^n\) directly into the computational basis state \(|x_1 x_2 \dots x_n\rangle\) using Pauli-\(X\) gates on every
-
Every serious practitioner must respect the data-loading bottleneck. Loading a huge classical dataset of size \(N\) from classical RAM onto a quantum chip still takes \(O(N)\) classical gate instructions unless the data arrives naturally as quantum states (for instance from quantum chemistry or quantum sensors) or has compact mathematical structure. Designing concise, problem-aligned feature maps therefore matters far more than chasing brute-force amplitude compression.
Ansatz Design, Expressibility, and Inductive Bias¶
-
Once data enters the quantum register, the trainable circuit architecture \(U(\boldsymbol{\theta})\) is called the ansatz (German for "educated starting guess"). Choosing an ansatz resembles picking between an adjustable all-purpose spanner and a custom key cut for one specific lock.
-
Hardware-efficient ansatzes alternate layers of native single-qubit rotations (such as \(R_y(\theta) R_z(\phi)\)) with fixed rings or chains of nearest-neighbour
CNOTorCZentangling gates matching the physical qubit wiring on a superconducting or trapped-ion chip. They compile cleanly with minimal noise overhead, yet they carry an important warning. Making a generic hardware-efficient circuit too deep turns it into a near-random unitary across the vast \(2^n\)-dimensional Hilbert space, causing gradients to shrink exponentially toward zero in a phenomenon known as a barren plateau (which we examine in depth in section 5). -
Problem-inspired ansatzes avoid blind random exploration by baking domain physics and symmetries directly into the circuit, giving the model strong inductive bias just like convolutions in computer vision (chapter 08) or message passing in graph neural networks (chapter 15).
- QAOA (Quantum Approximate Optimisation Algorithm). Built for discrete combinatorial problems such as Max-Cut on a graph, QAOA alternates layers of a problem cost unitary \(e^{-i\gamma_k H_C}\) (imprinting edge penalties into phases) and a mixer unitary \(e^{-i\beta_k H_M}\) (typically \(\prod_j R_x(2\beta_k)\), driving interference between candidate bitstrings). With just \(2p\) parameters across \(p\) layers, QAOA explores structured solution subspaces cleanly.
- UCCSD (Unitary Coupled Cluster Singles and Doubles). The gold-standard chemistry ansatz for the Variational Quantum Eigensolver (VQE), UCCSD parameterises single- and double-electron excitations \(e^{T(\boldsymbol{\theta}) - T^\dagger(\boldsymbol{\theta})}\) on top of a Hartree-Fock reference state. By construction, it conserves total electron count and spin, keeping every optimisation step inside physically valid molecular wave functions.
Computing Exact Gradients via the Parameter-Shift Rule¶
-
On a classical GPU, computing gradients across a billion neural weights takes one backward pass via reverse-mode automatic differentiation (backpropagation from chapter 03). Why can we not simply run backpropagation inside a physical quantum processor? Two physical laws we met in section 1 stand right in the way. The no-cloning theorem forbids copying intermediate quantum states into a tape, and measuring intermediate layers collapses the superposition and destroys the computation!
-
One naive workaround is classical finite differences, nudging a parameter by a tiny step \(\epsilon = 10^{-4}\) and computing \(\frac{f(\theta + \epsilon) - f(\theta - \epsilon)}{2\epsilon}\). On a real quantum chip, finite differences fail disastrously! Because every expectation estimate carries random measurement jitter (shot noise), subtracting two nearly identical noisy readings and dividing by \(2\epsilon = 2 \times 10^{-4}\) blows up the noise by five thousand times.
-
Remarkably, quantum mechanics offers a sleek, exact escape called the Parameter-Shift Rule (Mitarai et al., 2018; Schuld et al., 2019). Think of measuring the exact slope of a smooth sinusoidal hillside. For any pure sine wave \(f(\theta) = A\cos\theta + B\sin\theta + C\), you do not need an infinitesimal step at all! Stepping a wide quarter-wave forward (\(\theta + \pi/2\)) and a quarter-wave backward (\(\theta - \pi/2\)) gives the exact analytical derivative.
- Whenever a tunable gate takes the Pauli-rotation form \(G(\theta) = e^{-i\frac{\theta}{2}P}\) where \(P^2 = I\) (covering every \(R_x\), \(R_y\), \(R_z\), and multi-qubit Pauli rotation), the expectation value \(f(\theta) = \langle \psi(\theta) | H | \psi(\theta) \rangle\) is mathematically guaranteed to be a pure first-order trigonometric wave in \(\theta\)! Therefore, evaluating the exact same quantum circuit twice with \(\theta_j\) shifted by \(+\pi/2\) and \(-\pi/2\) yields the exact, unbiased analytical partial derivative directly on real quantum hardware.
- Because the shift \(\pi/2\) is macroscopic rather than infinitesimal, dividing by \(2\) never amplifies shot noise! The computational price is honest and clear. Computing the full gradient vector across \(P\) parameters requires \(2P\) separate circuit evaluations (each averaged over \(S\) shots), scaling linearly with parameter count rather than the constant-factor backward pass of classical backpropagation.
Shot Noise and Quantum Natural Gradient¶
-
Even with exact parameter-shift rules, real hardware estimates \(f(\boldsymbol{\theta})\) from a finite budget of \(S\) measurement shots. By the Central Limit Theorem (chapter 04), the standard error of a sampled expectation value decays only as \(\sigma \propto 1/\sqrt{S}\). Cutting estimation noise in half requires four times as many shots! Practical VQC training therefore blends Adam (to smooth noisy gradient moments), SPSA (Simultaneous Perturbation Stochastic Approximation, which estimates a noisy gradient along a random direction in just \(2\) circuit evaluations regardless of \(P\)), and adaptive shot budgets that start coarse and sharpen near convergence.
-
There is an even deeper geometric upgrade borrowed from information geometry (chapter 06). Standard gradient descent assumes that moving \(\theta_1\) by \(0.1\) radians and moving \(\theta_2\) by \(0.1\) radians change the quantum state by equal amounts. On a curved multi-qubit state manifold, that assumption is rarely true! For example, rotating \(R_z(\phi)\) when a qubit sits near the north pole \(|0\rangle\) barely moves the physical state at all, whereas rotating \(R_y(\theta)\) swings it briskly across the Bloch sphere.
-
Quantum Natural Gradient (QNG) (Stokes et al., 2020) corrects this coordinate distortion by measuring step sizes in the true geometric distance between quantum states, governed by the Fubini-Study metric tensor \(g(\boldsymbol{\theta})\) (also known as one quarter of the Quantum Fisher Information Matrix).
- Preconditioning the Euclidean gradient with the regularised inverse metric tensor \(g(\boldsymbol{\theta})\) steers updates along the steepest descent direction in actual Hilbert space.
- Just as classical Natural Gradient escapes narrow ravines far faster than vanilla SGD, Quantum Natural Gradient navigates flat or ill-conditioned regions of variational circuits in a fraction of the iterations, with block-diagonal approximations keeping the extra QPU measurement overhead modest on real hardware.
Take-Home¶
- Variational quantum circuits keep circuits shallow enough for noisy hardware by evaluating expectation values \(\langle \psi(\boldsymbol{\theta}) | H | \psi(\boldsymbol{\theta}) \rangle\) on a QPU while delegating parameter updates to a classical optimiser.
- Classical data enters quantum registers via basis, angle, amplitude, or data re-uploading encodings, where data re-uploading turns even small qubit counts into expressive Fourier models while reminding us to respect the classical data-loading bottleneck.
- Ansatz design balances hardware-efficient simplicity against problem-inspired inductive bias such as QAOA for combinatorial graphs and UCCSD for molecular chemistry.
- Because no-cloning and measurement collapse prevent classical backpropagation inside quantum memory, the parameter-shift rule computes exact unbiased analytical gradients using wide \(\pm \pi/2\) shifts that resist shot noise at a cost of \(2P\) circuit runs per step.
- Finite-shot uncertainty scales as \(1/\sqrt{S}\), and Quantum Natural Gradient accelerates variational convergence by preconditioning updates with the Fubini-Study metric tensor of the quantum state manifold.
Coding Tasks (use CoLab or notebook)¶
-
Verify the Parameter-Shift Rule against
jax.gradon a two-qubit variational circuit measuring \(\langle Z_0 Z_1 \rangle\), then add realistic finite-shot sampling noise (\(S = 400\) shots) and compare the gradient error of parameter-shift against tiny-step numerical finite differences (\(\epsilon = 10^{-3}\)).import jax import jax.numpy as jnp import matplotlib.pyplot as plt I2 = jnp.eye(2, dtype=jnp.complex64) Z = jnp.array([[1.0, 0.0], [0.0, -1.0]], dtype=jnp.complex64) ZZ = jnp.kron(Z, Z) CNOT = jnp.array([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]], dtype=jnp.complex64) ket00 = jnp.array([1.0, 0.0, 0.0, 0.0], dtype=jnp.complex64) def ry(a): c, s = jnp.cos(a / 2.0), jnp.sin(a / 2.0) return jnp.array([[c, -s], [s, c]], dtype=jnp.complex64) def rz(a): return jnp.array([[jnp.exp(-0.5j * a), 0.0], [0.0, jnp.exp(0.5j * a)]], dtype=jnp.complex64) def circuit_state(theta): u1 = jnp.kron(ry(theta[0]), ry(theta[1])) u2 = jnp.kron(rz(theta[2]), ry(theta[3])) return jnp.dot(u2, jnp.dot(CNOT, jnp.dot(u1, ket00))) def exact_expval(theta): psi = circuit_state(theta) return jnp.real(jnp.vdot(psi, jnp.dot(ZZ, psi))) def noisy_expval(theta, key, n_shots=400): psi = circuit_state(theta) probs = jnp.abs(psi) ** 2 eigvals = jnp.array([1.0, -1.0, -1.0, 1.0]) cdf = jnp.cumsum(probs) u = jax.random.uniform(key, (n_shots,)) samples = jnp.where(u < cdf[0], eigvals[0], jnp.where(u < cdf[1], eigvals[1], jnp.where(u < cdf[2], eigvals[2], eigvals[3]))) return jnp.mean(samples) theta0 = jnp.array([0.7, 1.2, -0.4, 0.9]) g_autodiff = jax.grad(exact_expval)(theta0) # Exact parameter-shift gradient shifts = jnp.eye(4) * (jnp.pi / 2.0) g_ps_exact = jnp.array([0.5 * (exact_expval(theta0 + shifts[i]) - exact_expval(theta0 - shifts[i])) for i in range(4)]) print(f"Max |jax.grad - exact param-shift|: {float(jnp.max(jnp.abs(g_autodiff - g_ps_exact))):.2e}") # Compare shot-noise resilience across 60 trials key = jax.random.PRNGKey(7) ps_errs, fd_errs = [], [] eps = 1e-3 for _ in range(60): key, k1, k2, k3, k4 = jax.random.split(key, 5) g_ps = 0.5 * (noisy_expval(theta0 + shifts[0], k1) - noisy_expval(theta0 - shifts[0], k2)) g_fd = (noisy_expval(theta0 + jnp.eye(4)[0] * eps, k3) - noisy_expval(theta0 - jnp.eye(4)[0] * eps, k4)) / (2.0 * eps) ps_errs.append(float(jnp.abs(g_ps - g_autodiff[0]))) fd_errs.append(float(jnp.abs(g_fd - g_autodiff[0]))) print(f"Mean noisy grad error -> Parameter-Shift: {float(jnp.mean(jnp.array(ps_errs))):.4f}, Finite-Diff (eps=1e-3): {float(jnp.mean(jnp.array(fd_errs))):.2f}") plt.figure(figsize=(7.2, 3.8)) plt.bar(["Parameter-Shift\n(s = pi/2)", "Finite-Diff\n(eps = 1e-3)"], [float(jnp.mean(jnp.array(ps_errs))), float(jnp.mean(jnp.array(fd_errs)))], color=["#27ae60", "#e74c3c"], width=0.45) plt.yscale("log") plt.title("Gradient Error Under 400 Measurement Shots (Log Scale)") plt.ylabel("Mean absolute gradient error") plt.tight_layout(); plt.show() -
Train a single-qubit data re-uploading model using pure parameter-shift gradients to fit the multi-frequency target function \(y(x) = 0.55\sin(2x) + 0.30\cos(3x)\) over \(x \in [-\pi, \pi]\). Compare \(L = 1\) encoding layer against \(L = 4\) re-uploading layers to see Fourier expressivity emerge directly on one qubit.
import jax import jax.numpy as jnp import matplotlib.pyplot as plt Z = jnp.array([[1.0, 0.0], [0.0, -1.0]], dtype=jnp.complex64) ket0 = jnp.array([1.0, 0.0], dtype=jnp.complex64) def rx(a): c, s = jnp.cos(a / 2.0), jnp.sin(a / 2.0) return jnp.array([[c, -1j * s], [-1j * s, c]], dtype=jnp.complex64) def ry(a): c, s = jnp.cos(a / 2.0), jnp.sin(a / 2.0) return jnp.array([[c, -s], [s, c]], dtype=jnp.complex64) def rz(a): return jnp.array([[jnp.exp(-0.5j * a), 0.0], [0.0, jnp.exp(0.5j * a)]], dtype=jnp.complex64) def reupload_pred(params, x, n_layers): psi = ket0 for l in range(n_layers): psi = jnp.dot(rx(x), psi) psi = jnp.dot(rz(params[3 * l + 2]), jnp.dot(ry(params[3 * l + 1]), jnp.dot(rz(params[3 * l]), psi))) return jnp.real(jnp.vdot(psi, jnp.dot(Z, psi))) xs = jnp.linspace(-jnp.pi, jnp.pi, 36) ys = 0.55 * jnp.sin(2.0 * xs) + 0.30 * jnp.cos(3.0 * xs) def fit_reupload(n_layers, seed, steps=90, lr=0.15): params = 0.5 * jax.random.normal(jax.random.PRNGKey(seed), (3 * n_layers,)) eye_p = jnp.eye(3 * n_layers) * (jnp.pi / 2.0) def mse_loss(p): preds = jnp.array([reupload_pred(p, x, n_layers) for x in xs]) return jnp.mean((preds - ys) ** 2) for _ in range(steps): # Analytical parameter-shift chain rule over the batch preds = jnp.array([reupload_pred(params, x, n_layers) for x in xs]) dL_dpred = 2.0 * (preds - ys) / len(xs) grads = [] for j in range(3 * n_layers): p_plus = jnp.array([reupload_pred(params + eye_p[j], x, n_layers) for x in xs]) p_minus = jnp.array([reupload_pred(params - eye_p[j], x, n_layers) for x in xs]) grads.append(jnp.sum(dL_dpred * 0.5 * (p_plus - p_minus))) params = params - lr * jnp.array(grads) final_preds = jnp.array([reupload_pred(params, x, n_layers) for x in xs]) return final_preds, float(mse_loss(params)) pred_L1, mse_L1 = fit_reupload(1, seed=11) pred_L4, mse_L4 = fit_reupload(4, seed=11) print(f"Final MSE -> L=1 layer: {mse_L1:.4f}, L=4 re-uploading layers: {mse_L4:.4f}") plt.figure(figsize=(7.6, 4.0)) plt.plot(xs, ys, color="#333", lw=2.5, label="True wave 0.55 sin(2x) + 0.30 cos(3x)") plt.plot(xs, pred_L1, color="#e74c3c", lw=1.8, ls="--", label=f"1-qubit L=1 (MSE={mse_L1:.3f})") plt.plot(xs, pred_L4, color="#27ae60", lw=2.2, label=f"1-qubit L=4 re-uploading (MSE={mse_L4:.3f})") plt.title("Single-Qubit Data Re-Uploading Expressivity Trained via Parameter Shift") plt.xlabel("Input x"); plt.ylabel("<Z>"); plt.legend(); plt.tight_layout(); plt.show() -
Compare standard gradient descent against Quantum Natural Gradient (QNG) using the Fubini-Study metric tensor \(g_{ij}(\boldsymbol{\theta})\) on a two-qubit VQE ground-state problem for Hamiltonian \(H = Z_0 + 0.5 Z_1 + 0.8 X_0 X_1\). Watch QNG precondition the curved state manifold and converge toward the exact ground-state eigenvalue in far fewer steps!
import jax import jax.numpy as jnp import matplotlib.pyplot as plt I2 = jnp.eye(2, dtype=jnp.complex64) X = jnp.array([[0.0, 1.0], [1.0, 0.0]], dtype=jnp.complex64) Z = jnp.array([[1.0, 0.0], [0.0, -1.0]], dtype=jnp.complex64) CNOT = jnp.array([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]], dtype=jnp.complex64) ket00 = jnp.array([1.0, 0.0, 0.0, 0.0], dtype=jnp.complex64) H_mol = jnp.kron(Z, I2) + 0.5 * jnp.kron(I2, Z) + 0.8 * jnp.kron(X, X) exact_ground = float(jnp.min(jnp.real(jnp.linalg.eigvalsh(H_mol)))) def ry(a): c, s = jnp.cos(a / 2.0), jnp.sin(a / 2.0) return jnp.array([[c, -s], [s, c]], dtype=jnp.complex64) def rz(a): return jnp.array([[jnp.exp(-0.5j * a), 0.0], [0.0, jnp.exp(0.5j * a)]], dtype=jnp.complex64) def ansatz(theta): psi = jnp.dot(jnp.kron(ry(theta[0]), ry(theta[1])), ket00) psi = jnp.dot(CNOT, psi) psi = jnp.dot(jnp.kron(rz(theta[2]), ry(theta[3])), psi) return psi def energy(theta): psi = ansatz(theta) return jnp.real(jnp.vdot(psi, jnp.dot(H_mol, psi))) def fubini_study_metric(theta): psi = ansatz(theta) dpsi_re = jnp.stack([jax.grad(lambda t, k=k: jnp.real(ansatz(t))[k])(theta) for k in range(4)], axis=0) dpsi_im = jnp.stack([jax.grad(lambda t, k=k: jnp.imag(ansatz(t))[k])(theta) for k in range(4)], axis=0) dpsi = dpsi_re + 1j * dpsi_im # shape (4, n_params) # Overlap <dpsi_i | dpsi_j> and <dpsi_i | psi> gram = jnp.dot(jnp.conj(dpsi.T), dpsi) proj = jnp.dot(jnp.conj(dpsi.T), psi) return jnp.real(gram - jnp.outer(proj, jnp.conj(proj))) grad_fn = jax.grad(energy) theta_init = jnp.array([0.18, 0.25, 0.6, 0.2]) # Near pole where coordinates warp! t_gd, t_qng = theta_init, theta_init hist_gd, hist_qng = [float(energy(t_gd))], [float(energy(t_qng))] lr = 0.08 for _ in range(55): t_gd = t_gd - lr * grad_fn(t_gd) g_mat = fubini_study_metric(t_qng) + 0.02 * jnp.eye(4) nat_step = jnp.linalg.solve(g_mat, grad_fn(t_qng)) t_qng = t_qng - lr * nat_step hist_gd.append(float(energy(t_gd))) hist_qng.append(float(energy(t_qng))) print(f"Exact ground energy: {exact_ground:.4f} | After 55 steps -> GD: {hist_gd[-1]:.4f}, QNG: {hist_qng[-1]:.4f}") plt.figure(figsize=(7.5, 4.0)) plt.plot(hist_gd, color="#e74c3c", lw=2.1, ls="--", label="Vanilla Gradient Descent") plt.plot(hist_qng, color="#27ae60", lw=2.4, label="Quantum Natural Gradient (Fubini-Study)") plt.axhline(exact_ground, color="#333", lw=1.2, ls=":", label=f"Exact ground energy ({exact_ground:.3f})") plt.title("VQE Convergence Comparing Euclidean GD vs Quantum Natural Gradient") plt.xlabel("Optimisation step"); plt.ylabel("Energy expectation <H>") plt.legend(); plt.tight_layout(); plt.show()