Barren Plateaus, Noise and Quantum Advantage¶
Building expressive quantum circuits is only half the story, because training them at scale collides with vanishing gradients, relentless hardware decoherence, and surprisingly strong classical baselines. Closing chapter 25, this section examines the barren plateau phenomenon, NISQ noise channels, error mitigation versus fault-tolerant error correction, dequantisation, and an honest engineering verdict on where quantum machine learning will genuinely outperform classical GPUs.
The Barren Plateau Phenomenon¶
-
Imagine being dropped blindfolded onto a perfectly flat salt flat the size of Australia and asked to walk downhill into a single thimble-sized pothole hidden somewhere on the plain. You pull out a carpenter's spirit level, check north, south, east, and west, and every direction reads completely dead level. Without a slope to follow, gradient descent wanders aimlessly forever.
-
In 2018, McClean and colleagues discovered that deep, randomly initialised parameterised quantum circuits suffer from this exact geometric curse, known as a barren plateau. As the number of qubits \(n\) increases, a typical circuit's cost landscape turns exponentially flat almost everywhere except inside tiny, needle-thin gorges around the solution.
-
Mathematically, when a parameterised circuit \(U(\boldsymbol{\theta})\) is deep and unstructured enough to approximate a unitary 2-design (meaning its first and second statistical moments match uniform Haar-random unitaries over \(SU(2^n)\)), the average gradient is zero and the variance of every partial derivative decays exponentially in the qubit count \(n\)
-
Why does this collapse happen? The culprit is concentration of measure (Levy's lemma) in high-dimensional Hilbert spaces, the very same geometric phenomenon that caused kernel concentration in section 04! On a hypersphere of dimension \(2^n\), almost all volume hugs the equator, so random quantum states look practically indistinguishable under a fixed observable.
-
In a classical neural network, vanishing gradients can still be nudged gently using 64-bit floating-point arithmetic. On a quantum computer, however, you never read an exact expectation value. You estimate it by averaging \(N_{\text{shots}}\) discrete measurement runs, whose statistical shot noise scales as \(\mathcal{O}(1 / \sqrt{N_{\text{shots}}})\). To distinguish a true gradient of magnitude \(\sim 2^{-n/2}\) from random measurement noise, you must spend \(\mathcal{O}(2^n)\) measurement shots per gradient step, wiping out any hope of a polynomial quantum speedup!
-
Three structural forces govern whether a circuit falls onto a barren plateau or stays trainable.
- The expressibility versus trainability tradeoff. A highly expressive circuit that can reach every corner of \(SU(2^n)\) pays for that universality with exponentially tiny gradient variance. Adding unstructured layers without inductive bias actively harms optimisation.
- Global versus local cost functions. Cerezo and colleagues proved a sharp distinction depending on what you measure at the end of the circuit. A global cost that compares all \(n\) qubits simultaneously (such as measuring the projector \(|0\rangle\langle 0|^{\otimes n}\)) exhibits barren plateaus even at constant depth \(\mathcal{O}(1)\)! By contrast, a local cost summing single-qubit or two-qubit observables keeps gradient variance polynomially large (\(\Omega(1/\operatorname{poly}(n))\)) up to logarithmic depth \(\mathcal{O}(\log n)\).
- Symmetry-preserving Geometric QML. Just as convolutional layers build translation equivariance into classical vision models (chapter 08) and graph networks respect node permutation symmetry (chapter 15), Geometric QML restricts gate generators to operators that commute with the problem's physical symmetry group (such as spin conservation or permutation symmetry). Confining the circuit to a polynomially sized invariant subspace keeps the Hilbert space compact and protects trainability, alongside hierarchical pooling (QCNNs) and small-angle identity-block initialisations.
Hardware Noise in the NISQ Era¶
-
Even if you craft a mathematically spotless, symmetry-preserving quantum circuit, running it on real hardware confronts a stubborn physical adversary. Picture trying to keep a finely machined brass spinning top balanced on the open deck of a wooden fishing boat rolling through choppy waves. Every wave and gust of wind steadily steals spin and tilts the axis until the top collapses onto the planks.
-
Today's quantum processors inhabit the NISQ (Noisy Intermediate-Scale Quantum) era, holding roughly \(50\) to \(1{,}000\) physical qubits without active error correction. Because physical qubits couple subtly to stray microwave photons, material defects, and control imperfections, a real quantum device no longer evolves as a clean state vector \(|\psi\rangle\). Instead, it evolves as a mixed density matrix \(\rho\) transformed by completely positive trace-preserving (CPTP) noise channels \(\mathcal{E}(\rho) = \sum_k K_k \rho K_k^\dagger\), where \(K_k\) are Kraus operators obeying \(\sum_k K_k^\dagger K_k = I\).
-
Four physical noise channels dominate modern superconducting, trapped-ion, and neutral-atom hardware.
- Amplitude damping (\(T_1\) relaxation). An excited qubit \(|1\rangle\) spontaneously leaks energy into its colder surroundings and relaxes down to the ground state \(|0\rangle\) with probability \(1 - e^{-t/T_1}\), destroying stored information over the energy-relaxation timescale \(T_1\).
- Pure dephasing (\(T_2\) decoherence). Tiny random fluctuations in local magnetic or electric fields scramble the delicate relative phase \(\phi\) inside a superposition \(\alpha|0\rangle + \beta e^{i\phi}|1\rangle\) without flipping populations, decaying off-diagonal coherence terms as \(e^{-t/T_2}\) (always bounded by \(T_2 \le 2T_1\)).
- Depolarising noise and gate infidelity. Imperfect microwave or laser control pulses introduce residual errors on every gate, typically around \(0.1\%\) to \(1\%\) for two-qubit entangling gates. Averaged over random circuits, these flaws are often modelled by a depolarising channel \(\mathcal{E}_p(\rho) = (1 - p)\rho + \frac{p}{2^n} I\) that steadily mixes the quantum state toward the maximally mixed uniform state \(I / 2^n\).
- Readout (SPAM) errors. Imperfect state preparation and noisy measurement amplifiers occasionally misclassify a true \(|1\rangle\) as \(0\) or vice versa, blurring empirical outcome histograms even if the gates ran cleanly.
-
Crucially, hardware noise creates its own optimisation trap called noise-induced barren plateaus (NIBPs). As Wang and colleagues proved, applying local depolarising noise after each of \(L\) circuit layers contracts every Pauli observable exponentially toward zero regardless of how clever your ansatz or local cost function is, bounding gradient variance by \(\operatorname{Var}(\partial_\theta C) \le \mathcal{O}(q^{2L})\) for a noise survival factor \(q < 1\). Once circuit depth outruns the coherence budget, the entire quantum processor dissolves into featureless white noise.
Error Mitigation versus Fault-Tolerant Error Correction¶
- Faced with noisy qubits, quantum engineers deploy two fundamentally different defences. Confusing near-term Quantum Error Mitigation (QEM) with true Fault-Tolerant Quantum Error Correction (QEC) is one of the commonest mistakes in popular quantum computing coverage, so it pays to separate them sharply.
Quantum Error Mitigation for Near-Term Processors¶
-
Error mitigation requires zero extra logical-encoding qubits. Instead, it runs larger ensembles of noisy circuits on NISQ hardware and uses classical statistical post-processing to extrapolate or cancel bias in expectation values \(\langle O \rangle\).
- Zero-Noise Extrapolation (ZNE). Suppose you cannot turn hardware noise down, yet you can deliberately turn it up by controlled scale factors \(c = 1, 3, 5\). A clever hardware trick called unitary gate folding replaces a gate layer \(U\) with \(U U^\dagger U\), which is mathematically identical to \(U\) yet triples physical gate execution time and noise! By measuring the degraded expectation values \(\langle O \rangle(1), \langle O \rangle(3), \langle O \rangle(5)\) and fitting a Richardson polynomial or exponential decay curve backward to \(c = 0\), ZNE estimates what a noiseless processor would have returned.
- Probabilistic Error Cancellation (PEC). If you carefully characterise a gate's noise channel \(\mathcal{E}\), you can write its exact mathematical inverse as a linear combination of implementable noisy operations \(\mathcal{E}^{-1} = \sum_i \alpha_i \mathcal{O}_i\), where some coefficients \(\alpha_i\) are negative (a quasi-probability distribution). Sampling circuits randomly according to \(|\alpha_i| / \gamma\) (where \(\gamma = \sum_i |\alpha_i| > 1\)) and reweighting each measured outcome by \(\gamma \operatorname{sgn}(\alpha_i)\) yields an exact unbiased estimator.
-
Every error-mitigation scheme shares one unforgiving mathematical ceiling. Reducing bias inflates estimator variance by a factor \(\gamma^{2V}\) that grows exponentially with circuit volume \(V\) (qubits times depth). Mitigation is therefore invaluable software triage for pushing near-term experiments slightly deeper, yet it can never scale to deep algorithms on thousands of qubits.
Fault-Tolerant Quantum Error Correction¶
-
Truly scalable quantum computation demands Quantum Error Correction (QEC), which actively detects and repairs errors mid-flight before they accumulate. Classical computers protect bits simply by copying \(0 \mapsto 000\) and taking a majority vote. Quantum computers cannot do that directly because the no-cloning theorem forbids copying an unknown quantum state \(|\psi\rangle\), and measuring a data qubit directly would collapse its superposition!
-
QEC solves both dilemmas simultaneously by entangling one logical qubit across a patch of many physical qubits inside a carefully chosen code subspace. The leading architecture for 2D chip layouts is the surface code. Picture a checkerboard grid where data qubits sit on the vertices and dedicated ancilla qubits sit in the centre of alternating squares.
-
In every clock cycle, ancilla qubits measure four-qubit parity stabilisers (\(X^{\otimes 4}\) around one colour of square, \(Z^{\otimes 4}\) around the other). Because these parity checks commute with the encoded logical operators, they reveal where a bit-flip (\(X\)) or phase-flip (\(Z\)) error struck without ever learning what quantum state is stored! A fast classical decoder (often running minimum-weight perfect matching or a neural decoder) converts those parity syndromes into corrective frame updates in real time.
-
The celebrated threshold theorem promises that once physical two-qubit gate error rates drop below the surface-code threshold (roughly \(1\%\)), expanding the checkerboard code distance \(d\) suppresses logical error rates exponentially toward \(10^{-12}\) or better. The engineering price is a steep physical-to-logical qubit overhead, typically \(100\) to \(1{,}000\) physical qubits per reliable logical qubit, plus specialised magic-state distillation factories to execute non-Clifford gates fault-tolerantly.
-
Landmark hardware demonstrations have now crossed the threshold from theory into experimental reality across two complementary physical platforms.
- Below-threshold superconducting surface codes (Google Willow, Nature, December 2024). On the \(105\)-qubit Willow processor, scaling a surface-code logical memory across distances \(d = 3\), \(d = 5\), and \(d = 7\) (using \(101\) physical qubits at \(d = 7\)) suppressed the logical error rate by a factor of \(\Lambda = 2.14 \pm 0.02\) at every step up in code distance, reaching \(0.143\% \pm 0.003\%\) per error-correction cycle and outliving the chip's best individual physical qubit by a factor of \(2.4 \pm 0.3\) (alongside real-time decoding at distance \(5\)).
- Programmable neutral-atom logical processors (Harvard, MIT, and QuEra, Bluvstein et al., Nature, 2024). Using reconfigurable optical-tweezer arrays that physically shuttle entangled neutral atoms across a chip, researchers executed fault-tolerant logical circuits spanning up to \(48\) logical qubits, showcasing flexible long-range connectivity as an alternative path toward lower-overhead quantum codes.
Quantum-Inspired Classical Algorithms and Dequantisation¶
-
Suppose a stage magician pulls a sparkling white rabbit out of a silk top hat and claims the trick requires supernatural physics. Then an observant teenager walks onto the stage, inspects the hidden pocket stitched inside the hat, and shows how anyone can perform the exact same illusion with everyday cardboard. That is essentially what happened to early quantum linear-algebra claims in 2018.
-
During the 2010s, a wave of influential QML proposals promised exponential speedups for classical recommendation systems, principal component analysis (PCA), support vector machines, and linear regression. Almost all of them relied quietly on a hypothetical hardware component called QRAM (Quantum Random-Access Memory) capable of loading massive classical matrices into quantum amplitude superpositions in logarithmic time.
-
In 2018, eighteen-year-old undergraduate Ewin Tang stunned the field by dequantising the flagship quantum recommendation algorithm, showing that a randomised classical algorithm matches it up to a polynomial factor. Her central insight was disarmingly fair. QRAM implicitly grants the quantum algorithm \(l_2\)-norm sample-and-query access to the input matrix, meaning you can sample row index \(i\) with probability proportional to its squared norm \(\|\mathbf{a}_i\|_2^2 / \|A\|_F^2\) and query individual matrix entries in \(\mathcal{O}(\log N)\) time.
-
When you give a classical laptop that exact same data structure (easily maintained online in a simple binary sum-tree), classical importance sampling and sketching approximates low-rank matrix products and singular value decompositions in time independent of the matrix dimension! Subsequent breakthroughs dequantised quantum PCA, quantum clustering, and low-rank linear solvers whenever matrices are classical and low-rank.
-
Dequantisation taught quantum machine learning two healthy, lasting lessons. First, data loading matters enormously, because streaming \(N\) unstructured classical numbers into a quantum circuit already costs \(\mathcal{O}(N)\) gate operations, erasing any logarithmic speedup unless the data has compact mathematical structure. Second, genuine quantum advantage must always be benchmarked against the sharpest modern randomised classical algorithms, not against naive textbook loops.
An Honest Engineering Verdict on Quantum Advantage¶
-
Stepping back across all five sections of chapter 25, we now have the clarity to cut through both breathless hype and reflexive dismissal. Quantum computers are not magic drop-in accelerators that make every neural network run exponentially faster. They are specialised physics co-processors governed by unitary interference and entanglement.
-
Where classical GPUs win decisively. For everyday classical big data, including web-scale language modelling, computer vision, audio synthesis, recommendation tables, and reinforcement learning across chapters 06 through 20, modern silicon GPUs and TPUs (chapter 19) remain overwhelming champions. Classical hardware enjoys staggering memory bandwidth, trivial data loading, exact floating-point gradients free of shot noise, and decades of software optimisation. Trying to push terabytes of internet text through a narrow quantum gate interface is like using a Formula One car to haul gravel.
-
Where quantum ML is genuinely likely to matter. The strongest theoretical and scientific case for quantum advantage appears wherever the problem itself is natively quantum mechanical or high-dimensional in a structured unitary way.
- Native quantum data and quantum sensing. When inputs arrive directly as fragile quantum states from atomic clocks, quantum telescopes, or superconducting processors, a quantum learner can store and jointly measure multiple entangled copies in quantum memory. Huang and colleagues proved experimentally and theoretically that such quantum-enhanced experiments achieve an exponential reduction in sample complexity compared with any classical agent forced to measure copies one by one.
- Quantum chemistry and drug discovery. Reconnecting directly to chapter 23 (Molecule Design), fault-tolerant quantum algorithms such as quantum phase estimation and refined variational solvers target strongly correlated molecular active sites, catalytic nitrogen fixation, and carbon-capture chemistry where classical density functional theory loses accuracy. Rather than replacing classical AI, quantum processors will act as high-precision physics oracles generating gold-standard ground-state energies to train classical neural force fields!
- Condensed-matter physics and materials simulation. Designing high-temperature superconductors, solid-state battery electrolytes, and exotic topological phases involves simulating interacting quantum many-body dynamics directly, the exact problem Richard Feynman originally envisioned quantum computers to solve.
-
Seen through this grounded lens, quantum computing and classical artificial intelligence are not rivals competing for the same throne. Classical deep learning excels at discovering statistical patterns across vast macroscopic human datasets, while quantum processors speak the native mathematical language of the microscopic physical world. Together, they form a remarkably complementary partnership for the next century of science and engineering.
Take-Home¶
- Deep unstructured quantum circuits suffer from barren plateaus, where concentration of measure drives gradient variance down as \(\mathcal{O}(2^{-n})\) until signals vanish beneath finite measurement shot noise.
- Trainable QML architectures escape barren plateaus by trading excessive expressibility for strong inductive bias through local observables, logarithmic-depth QCNN pooling, and symmetry-preserving geometric gates.
- Real NISQ processors experience amplitude damping (\(T_1\)), dephasing (\(T_2\)), depolarising gate errors, and readout bias, which induce noise-driven barren plateaus beyond shallow circuit depths.
- Near-term error mitigation (ZNE and PEC) reduces expectation bias at an exponential sampling cost, whereas true fault-tolerant scalability requires quantum error correction operating below threshold, demonstrated experimentally by Google Willow's distance-\(3\) to \(7\) surface codes (\(\Lambda \approx 2.14\)) and Harvard/QuEra's \(48\)-logical-qubit neutral-atom processor.
- Ewin Tang's dequantisation results show that classical GPUs and randomised sketching decisively dominate large classical datasets, leaving quantum ML's brightest advantage in native quantum sensing data, quantum chemistry, and materials simulation.
Coding Tasks (use CoLab or notebook)¶
-
Empirically observe the barren plateau phenomenon in JAX across qubit counts \(n = 2, 3, 4, 5, 6, 7\). Simulate random layered hardware-efficient circuits with
RyandCZgates, compute exact gradients \(\partial C / \partial \theta_0\) viajax.gradover 40 random initialisations for both a global projector cost \(1 - |\langle 0\dots 0|\psi\rangle|^2\) and a local single-qubit cost \(\frac{1}{2}(1 - \langle Z_0 \rangle)\), and plot \(\log_{10}\operatorname{Var}(\partial_{\theta_0} C)\) against \(n\).import jax import jax.numpy as jnp import matplotlib.pyplot as plt def apply_ry_qubit(psi, theta, q, n): shape = (2 ** q, 2, 2 ** (n - q - 1)) t = psi.reshape(shape) c, s = jnp.cos(theta / 2.0), jnp.sin(theta / 2.0) out0 = c * t[:, 0, :] - s * t[:, 1, :] out1 = s * t[:, 0, :] + c * t[:, 1, :] return jnp.stack([out0, out1], axis=1).reshape(-1) def apply_cz_adjacent(psi, q, n): shape = (2 ** q, 4, 2 ** (n - q - 2)) t = psi.reshape(shape) signs = jnp.array([1.0, 1.0, 1.0, -1.0])[None, :, None] return (t * signs).reshape(-1) def run_circuit(params, n): psi = jnp.concatenate([jnp.ones(1), jnp.zeros(2 ** n - 1)]) n_layers = params.shape[0] for l in range(n_layers): for q in range(n): psi = apply_ry_qubit(psi, params[l, q], q, n) for q in range(n - 1): psi = apply_cz_adjacent(psi, q, n) return psi def global_cost(params, n): psi = run_circuit(params, n) return 1.0 - psi[0] ** 2 def local_cost(params, n): psi = run_circuit(params, n) probs = (psi ** 2).reshape(2, -1) p_zero_q0 = jnp.sum(probs[0]) return 1.0 - p_zero_q0 qubit_counts = [2, 3, 4, 5, 6, 7] var_global, var_local = [], [] key = jax.random.PRNGKey(123) n_samples = 40 for n in qubit_counts: # Deep circuit (depth = 2*n) for global cost vs shallow circuit (depth = 2) for local cost g_global_fn = jax.grad(lambda p: global_cost(p, n)) g_local_fn = jax.grad(lambda p: local_cost(p, n)) key, k1, k2 = jax.random.split(key, 3) p_deep = jax.random.uniform(k1, (n_samples, 2 * n, n), minval=-jnp.pi, maxval=jnp.pi) p_shal = jax.random.uniform(k2, (n_samples, 2, n), minval=-jnp.pi, maxval=jnp.pi) grads_g = jnp.array([g_global_fn(p_deep[i])[0, 0] for i in range(n_samples)]) grads_l = jnp.array([g_local_fn(p_shal[i])[0, 0] for i in range(n_samples)]) var_global.append(float(jnp.var(grads_g))) var_local.append(float(jnp.var(grads_l))) print(f"n={n} qubits -> Var(global deep): {var_global[-1]:.2e}, Var(local shallow): {var_local[-1]:.2e}") plt.figure(figsize=(7.2, 4.2)) plt.semilogy(qubit_counts, var_global, "o-", color="#e74c3c", lw=2.2, label="Global Cost + Deep Circuit") plt.semilogy(qubit_counts, var_local, "s-", color="#27ae60", lw=2.2, label="Local Cost + Shallow Circuit") plt.title("Barren Plateau Gradient Variance vs Qubit Count") plt.xlabel("Number of Qubits (n)"); plt.ylabel("Gradient Variance (log scale)") plt.grid(True, alpha=0.3); plt.legend(); plt.tight_layout(); plt.show() -
Simulate NISQ density-matrix noise (combining \(T_1\) amplitude damping and depolarising noise via Kraus operators) on a single-qubit rotation circuit, then apply Zero-Noise Extrapolation (ZNE) using unitary gate folding at scale factors \(c \in \{1, 3, 5\}\). Compare the unmitigated noisy expectation value, quadratic Richardson ZNE estimate, and exact noiseless ground truth across rotation angles.
import jax import jax.numpy as jnp import matplotlib.pyplot as plt Z = jnp.array([[1.0, 0.0], [0.0, -1.0]]) def ry(theta): c, s = jnp.cos(theta / 2.0), jnp.sin(theta / 2.0) return jnp.array([[c, -s], [s, c]]) def apply_noise(rho, gamma_t1, p_depol): # Amplitude damping Kraus operators K0, K1 K0 = jnp.array([[1.0, 0.0], [0.0, jnp.sqrt(1.0 - gamma_t1)]]) K1 = jnp.array([[0.0, jnp.sqrt(gamma_t1)], [0.0, 0.0]]) rho_ad = jnp.dot(jnp.dot(K0, rho), K0.T) + jnp.dot(jnp.dot(K1, rho), K1.T) # Depolarising channel: (1 - p) rho + (p / 2) I return (1.0 - p_depol) * rho_ad + 0.5 * p_depol * jnp.eye(2) def run_folded_circuit(theta, n_layers, fold_c, gamma_t1=0.015, p_depol=0.02): rho = jnp.array([[1.0, 0.0], [0.0, 0.0]]) U = ry(theta / n_layers) U_dag = U.T for _ in range(n_layers): # Forward gate + noise rho = apply_noise(jnp.dot(jnp.dot(U, rho), U.T), gamma_t1, p_depol) # Gate folding (U^\dagger U) repeated (fold_c - 1) // 2 times to amplify noise cleanly for _ in range((fold_c - 1) // 2): rho = apply_noise(jnp.dot(jnp.dot(U_dag, rho), U_dag.T), gamma_t1, p_depol) rho = apply_noise(jnp.dot(jnp.dot(U, rho), U.T), gamma_t1, p_depol) return float(jnp.trace(jnp.dot(Z, rho))) # Richardson extrapolation weights for c = [1, 3, 5] targeting c = 0 # Solving w1 + w3 + w5 = 1, 1*w1 + 3*w3 + 5*w5 = 0, 1*w1 + 9*w3 + 25*w5 = 0 w_zne = jnp.array([15.0 / 8.0, -5.0 / 4.0, 3.0 / 8.0]) thetas = jnp.linspace(0.0, jnp.pi, 17) exact_vals, noisy_vals, zne_vals = [], [], [] for th in thetas: exact_vals.append(float(jnp.cos(th))) e1 = run_folded_circuit(float(th), n_layers=6, fold_c=1) e3 = run_folded_circuit(float(th), n_layers=6, fold_c=3) e5 = run_folded_circuit(float(th), n_layers=6, fold_c=5) noisy_vals.append(e1) zne_vals.append(float(w_zne[0] * e1 + w_zne[1] * e3 + w_zne[2] * e5)) mae_noisy = float(jnp.mean(jnp.abs(jnp.array(noisy_vals) - jnp.array(exact_vals)))) mae_zne = float(jnp.mean(jnp.abs(jnp.array(zne_vals) - jnp.array(exact_vals)))) print(f"Mean Absolute Error -> Noisy (c=1): {mae_noisy:.4f}, ZNE Mitigated: {mae_zne:.4f}") plt.figure(figsize=(7.2, 4.2)) plt.plot(thetas, exact_vals, color="#333", lw=2.2, label="Exact Noiseless <Z>") plt.plot(thetas, noisy_vals, "o--", color="#e74c3c", lw=1.6, label=f"Noisy NISQ (MAE={mae_noisy:.3f})") plt.plot(thetas, zne_vals, "s-", color="#27ae60", lw=2.0, label=f"ZNE Mitigated (MAE={mae_zne:.3f})") plt.title("Zero-Noise Extrapolation (ZNE) Under T1 Damping and Depolarising Noise") plt.xlabel("Total Rotation Angle theta (rad)"); plt.ylabel("Expectation Value <Z>") plt.legend(); plt.tight_layout(); plt.show() -
Implement Ewin Tang's core quantum-inspired importance sampling (dequantisation sketching) trick in JAX. Given a large low-rank matrix \(A \in \mathbb{R}^{4000 \times 16}\) and vector \(\mathbf{b} \in \mathbb{R}^{4000}\), estimate the inner product \(A^\top \mathbf{b}\) using \(l_2\)-row-norm sampling (\(p_i = \|\mathbf{a}_i\|_2^2 / \|A\|_F^2\)) versus naive uniform row sampling across sample budgets \(s \in [20, 400]\), showing how classical sample-and-query access rapidly tracks exact matrix multiplication without reading every row.
import jax import jax.numpy as jnp import matplotlib.pyplot as plt key = jax.random.PRNGKey(99) N, d, rank = 4000, 16, 3 key, k_u, k_v, k_b, k_heavy = jax.random.split(key, 5) # Construct a skewed low-rank matrix (realistic user-item recommendation structure) row_weights = jnp.exp(1.6 * jax.random.normal(k_heavy, (N, 1))) U = row_weights * jax.random.normal(k_u, (N, rank)) V = jax.random.normal(k_v, (rank, d)) A = jnp.dot(U, V) b = row_weights[:, 0] * jax.random.normal(k_b, (N,)) exact_prod = jnp.dot(A.T, b) exact_norm = float(jnp.linalg.norm(exact_prod)) # l2-norm importance distribution (classical analogue of QRAM state preparation) row_sq_norms = jnp.sum(A ** 2, axis=1) frob_sq = jnp.sum(row_sq_norms) probs_l2 = row_sq_norms / frob_sq cdf_l2 = jnp.cumsum(probs_l2) sample_sizes = [20, 50, 100, 200, 400] err_l2, err_unif = [], [] for s in sample_sizes: errs_a, errs_u = [], [] for trial in range(25): key, ku1, ku2 = jax.random.split(key, 3) # Inverse-CDF importance sampling (pure JAX, no .at needed) u_vals = jax.random.uniform(ku1, (s,)) idx_l2 = jnp.searchsorted(cdf_l2, u_vals) idx_l2 = jnp.minimum(idx_l2, N - 1) est_l2 = jnp.mean((A[idx_l2] * b[idx_l2, None]) / probs_l2[idx_l2, None], axis=0) errs_a.append(float(jnp.linalg.norm(est_l2 - exact_prod)) / exact_norm) # Uniform row sampling baseline idx_u = jax.random.randint(ku2, (s,), 0, N) est_u = N * jnp.mean(A[idx_u] * b[idx_u, None], axis=0) errs_u.append(float(jnp.linalg.norm(est_u - exact_prod)) / exact_norm) err_l2.append(float(jnp.mean(jnp.array(errs_a)))) err_unif.append(float(jnp.mean(jnp.array(errs_u)))) print(f"Samples s={s:3d} ({100*s/N:.1f}% rows) -> l2-Importance RelErr: {err_l2[-1]:.3f}, Uniform RelErr: {err_unif[-1]:.3f}") plt.figure(figsize=(7.2, 4.2)) plt.plot(sample_sizes, err_unif, "o--", color="#e74c3c", lw=1.8, label="Uniform Row Sampling") plt.plot(sample_sizes, err_l2, "s-", color="#3498db", lw=2.2, label="l2-Norm Importance Sampling (Tang)") plt.title("Quantum-Inspired Sketching Error on 4000-Row Matrix Product") plt.xlabel("Number of Sampled Rows (s)"); plt.ylabel("Relative Estimation Error") plt.grid(True, alpha=0.3); plt.legend(); plt.tight_layout(); plt.show()