Skip to content

Quantum Kernels, Neural Networks and Generative Models

Once classical data is encoded into quantum states and parameterised gates become differentiable, a quantum processor can act as a high-dimensional feature map, a neural network layer, a native probability sampler, or a molecular energy solver. This section explores quantum kernels, quantum convolutional networks, quantum generative models, and the Variational Quantum Eigensolver, connecting Hilbert-space geometry directly to classical machine learning and molecule design.

Quantum Feature Maps and the Hilbert Space Lift

  • Imagine scattering red and blue marbles across a flat wooden tabletop so that the red marbles form a tight cluster in the centre while the blue marbles surround them in a ring. No matter how you slide a straight wooden ruler across the table, you can never separate the two colours with a single straight cut. Yet if you gently lift the red marbles a few centimetres into the air above the table, a flat sheet of cardboard slips straight between the two groups effortlessly.

  • In chapter 06 (Machine Learning), you saw how Support Vector Machines (SVMs) automate that exact lifting trick using classical kernels, mapping inputs into a higher-dimensional feature space where tangled classes pull apart cleanly. Quantum machine learning pushes this geometric idea to its physical extreme by encoding each classical data vector \(\mathbf{x} \in \mathbb{R}^d\) into a quantum state living inside an exponentially vast complex Hilbert space.

  • A quantum feature map is a data-dependent unitary circuit \(U_\phi(\mathbf{x})\) applied to \(n\) qubits initialised in the ground state \(|0\rangle^{\otimes n}\), producing the quantum state \(|\phi(\mathbf{x})\rangle = U_\phi(\mathbf{x})|0\rangle^{\otimes n} \in \mathbb{C}^{2^n}\). Because global phase carries no physical meaning, the true feature representation is the rank-one density matrix \(\rho(\mathbf{x}) = |\phi(\mathbf{x})\rangle\langle\phi(\mathbf{x})|\), living in a real vector space of dimension \(4^n - 1\).

  • To create rich non-linear interactions between input features, practitioners rarely stop at single-qubit angle rotations alone. A celebrated construction is the ZZ-feature map, which alternates Hadamard layers, single-qubit phase rotations \(e^{-i x_j Z_j}\), and two-qubit entangling gates \(e^{-i (\pi - x_j)(\pi - x_k) Z_j Z_k}\). Even with a handful of qubits, repeated layers weave high-order trigonometric products across features that become rapidly harder to simulate classically as circuit depth and entanglement grow.

Quantum feature maps lifting classical data into Hilbert space and estimating quantum kernel overlaps via compute-uncompute fidelity circuits

Quantum Kernels, Fidelity Circuits and Kernel Concentration

  • Once two inputs \(\mathbf{x}\) and \(\mathbf{x}'\) live as quantum states \(|\phi(\mathbf{x})\rangle\) and \(|\phi(\mathbf{x}')\rangle\), measuring how similar they are in Hilbert space could not be more natural. You simply take the squared magnitude of their inner product, which defines the fidelity quantum kernel
\[K(\mathbf{x}, \mathbf{x}') = \bigl|\langle \phi(\mathbf{x}) | \phi(\mathbf{x}') \rangle\bigr|^2 = \operatorname{Tr}\!\bigl(\rho(\mathbf{x})\,\rho(\mathbf{x}')\bigr)\]
  • Because \(K(\mathbf{x}, \mathbf{x}')\) is symmetric and positive semidefinite, it satisfies Mercer's theorem from chapter 06. That means you do not even need a quantum processor to perform classification! You simply estimate the pairwise Gram matrix \(K_{ij} = K(\mathbf{x}_i, \mathbf{x}_j)\) on quantum hardware and hand that \(N \times N\) matrix straight to a classical SVM solver. Because SVM training solves a strictly convex quadratic programme, it guarantees a global optimum with zero risk of getting trapped in local valleys during classifier optimisation.

  • Quantum hardware estimates each overlap \(K(\mathbf{x}, \mathbf{x}')\) through one of two compact interference circuits.

    • Compute-uncompute (inversion) test. Starting from \(|0\rangle^{\otimes n}\), run the encoding circuit \(U_\phi(\mathbf{x})\) forward, immediately follow it with the exact adjoint circuit \(U_\phi^\dagger(\mathbf{x}')\) in reverse, and measure all \(n\) qubits in the computational basis. If \(\mathbf{x} = \mathbf{x}'\), the inverse cancels the forward pass perfectly and every shot returns the all-zero bitstring \(00\dots 0\). In general, the probability of observing \(00\dots 0\) equals \(|\langle 0|^{\otimes n} U_\phi^\dagger(\mathbf{x}') U_\phi(\mathbf{x}) |0\rangle^{\otimes n}|^2 = K(\mathbf{x}, \mathbf{x}')\), requiring only \(n\) qubits.
    • Swap test. Prepare \(|\phi(\mathbf{x})\rangle\) and \(|\phi(\mathbf{x}')\rangle\) side by side on two \(n\)-qubit registers alongside one extra ancilla qubit in \(|0\rangle\). Apply a Hadamard gate to the ancilla, run controlled-SWAP gates conditioned on the ancilla to exchange matching wires between the two registers, and apply a second Hadamard to the ancilla. Measuring the ancilla yields \(0\) with probability \(P(0) = \frac{1}{2}\bigl(1 + |\langle\phi(\mathbf{x})|\phi(\mathbf{x}')\rangle|^2\bigr)\). While the swap test needs \(2n + 1\) qubits, it works even when the two states come directly from physical quantum sensors with no known preparation circuit \(U_\phi^\dagger\).
  • At first glance, a \(2^n\)-dimensional feature space sounds like a magic wand for every dataset on Earth. In reality, an overly expressive feature map runs headlong into kernel concentration. Imagine scattering a hundred travellers uniformly at random across a planet ten times the size of Jupiter. Almost every pair of travellers lands absurdly far apart, so nobody looks like anyone else's neighbour.

  • In a \(2^n\)-dimensional Hilbert space, deeply scrambled feature circuits push almost every distinct pair of quantum states nearly orthogonal, causing off-diagonal kernel entries to collapse exponentially toward zero with variance \(\operatorname{Var}(K(\mathbf{x}, \mathbf{x}')) \in \mathcal{O}(2^{-n})\) while the diagonal stays fixed at \(K(\mathbf{x}_i, \mathbf{x}_i) = 1\). The estimated Gram matrix turns into the identity matrix \(I\) plus shot noise! An SVM handed the identity matrix memorises every training label effortlessly yet predicts pure noise on unseen test data.

  • Researchers tame kernel concentration through three practical safeguards. Bandwidth scaling multiplies classical inputs by a tunable factor \(\alpha \in (0, 1)\) before encoding so states stay clustered inside a useful region of Hilbert space. Projected quantum kernels measure local single-qubit reduced density matrices \(\rho_k(\mathbf{x})\) instead of full global fidelity, comparing local shadows via a classical RBF kernel. Finally, kernel alignment tunes a handful of circuit parameters so the quantum Gram matrix matches the target label similarity matrix \(y y^\top\).

Quantum Neural Networks and Quantum Convolutional Neural Networks

  • Rather than fixing the feature map and letting a classical SVM draw the boundary, a Quantum Neural Network (QNN) places trainable rotation angles \(\boldsymbol{\theta}\) directly inside the quantum circuit. A typical QNN prepares a state \(|\psi(\mathbf{x}, \boldsymbol{\theta})\rangle = W(\boldsymbol{\theta}) U_\phi(\mathbf{x}) |0\rangle^{\otimes n}\) and outputs the expectation value of a Hermitian observable \(O\)
\[f_{\boldsymbol{\theta}}(\mathbf{x}) = \langle 0|^{\otimes n} U_\phi^\dagger(\mathbf{x}) W^\dagger(\boldsymbol{\theta}) \, O \, W(\boldsymbol{\theta}) U_\phi(\mathbf{x}) |0\rangle^{\otimes n}\]
  • Pause and notice a striking structural difference from the classical deep networks we built in chapter 06. In a classical multilayer perceptron, every hidden layer applies a point-wise non-linear activation such as ReLU or GELU. Inside a quantum computer, however, every gate is a strictly linear unitary matrix! Non-linearity enters only through the trigonometric encoding map \(U_\phi(\mathbf{x})\) and the quadratic Born-rule measurement.

  • Because a single encoding layer limits the range of frequencies a QNN can represent, modern designs use data re-uploading, interleaving copies of the data encoding \(U_\phi(\mathbf{x})\) with trainable variational blocks \(W_\ell(\boldsymbol{\theta}_\ell)\) across \(L\) layers. Mathematically, a re-uploading QNN behaves like a truncated Fourier series \(f_{\boldsymbol{\theta}}(\mathbf{x}) = \sum_{\boldsymbol{\omega}} c_{\boldsymbol{\omega}}(\boldsymbol{\theta}) e^{i \boldsymbol{\omega} \cdot \mathbf{x}}\) whose accessible frequency spectrum grows linearly with the number of re-uploading layers, granting universal function approximation even on very small qubit counts.

  • As qubit counts scale up, naive flat QNNs suffer from vanishing gradients (the barren plateau problem we will dissect in section 05). Drawing direct inspiration from classical convolutional neural networks (chapter 08) and the Multiscale Entanglement Renormalisation Ansatz (MERA) from condensed-matter physics, Quantum Convolutional Neural Networks (QCNNs) solve this scaling bottleneck through hierarchical compression.

  • Think of how a stadium crowd can pass a collective verdict upward without shouting all at once. Neighbouring spectators pair off, chat briefly, and choose one spokesperson from each pair to move forward; those spokespeople pair off again until a single representative announces the final answer. A QCNN follows that exact multiscale rhythm across qubits.

    • Quantum convolutional layer. Applies an identical, parameter-shared two-qubit unitary gate across neighbouring pairs of qubits, extracting local translationally invariant quantum correlations with only a tiny handful of trainable parameters.
    • Quantum pooling layer. Measures half of the qubits and uses each classical measurement outcome to trigger a small conditioned rotation on its surviving neighbour (or simply traces out half the wires), halving the active qubit count at every stage from \(n\) down to \(n/2\), \(n/4\), and eventually a single readout qubit.
  • Because a QCNN halves its register width at every step, its total circuit depth scales only logarithmically as \(\mathcal{O}(\log n)\) and its final observable stays strictly local. Remarkably, Pesah and colleagues proved mathematically that QCNNs avoid barren plateaus altogether, making them one of the cleanest trainable quantum architectures for classifying quantum phases of matter and structured quantum data.

Quantum Generative Models

  • Discriminative models draw boundaries between classes, whereas generative models learn to synthesise brand-new examples from an underlying probability distribution \(p_{\text{data}}(\mathbf{x})\). In classical machine learning, sampling from complex multimodal distributions often demands slow Markov chains, autoregressive loops, or dozens of iterative denoising steps in diffusion models.

  • A quantum processor, by contrast, is a native probabilistic sampler forged by nature itself. Imagine crafting a weighted multi-sided die out of interfering ripples in a shallow pool. Rather than enumerating every face explicitly, simply looking at the water surface triggers Born's rule and drops out a fresh bitstring sample in one physical shot.

Quantum Circuit Born Machines

  • A Quantum Circuit Born Machine (QCBM) prepares a parameterised state \(|\psi(\boldsymbol{\theta})\rangle = U(\boldsymbol{\theta})|0\rangle^{\otimes n}\) and reads out computational-basis bitstrings \(\mathbf{x} \in \{0, 1\}^n\) directly with probability
\[p_{\boldsymbol{\theta}}(\mathbf{x}) = \bigl|\langle \mathbf{x} | \psi(\boldsymbol{\theta}) \rangle\bigr|^2\]
  • Notice the beauty of this formulation. The distribution \(p_{\boldsymbol{\theta}}(\mathbf{x})\) is automatically normalised to sum to \(1\) because \(U(\boldsymbol{\theta})\) is unitary, so you never have to wrestle with an intractable partition function \(Z(\boldsymbol{\theta})\). Generating a fresh sample takes one circuit execution, and quantum interference allows QCBMs to represent correlations tied to classically hard sampling problems.

  • That implicit structure brings one subtle training wrinkle. For large \(n\), you can draw samples \(\mathbf{x} \sim p_{\boldsymbol{\theta}}\) effortlessly, yet you cannot query the exact numerical value \(p_{\boldsymbol{\theta}}(\mathbf{x})\) for an arbitrary bitstring, which makes classical cross-entropy or KL-divergence gradients impractical. Instead, QCBMs are commonly trained by minimising Maximum Mean Discrepancy (MMD), a kernel-based two-sample distance comparing generated bitstrings against real training data through a classical similarity kernel \(k(\mathbf{x}, \mathbf{y})\) (often a mixture of Gaussian RBF kernels at multiple bandwidths)

\[\mathcal{L}_{\text{MMD}}^2(\boldsymbol{\theta}) = \mathbb{E}_{\mathbf{x}, \mathbf{x}' \sim p_{\boldsymbol{\theta}}}\bigl[k(\mathbf{x}, \mathbf{x}')\bigr] - 2\,\mathbb{E}_{\mathbf{x} \sim p_{\boldsymbol{\theta}},\, \mathbf{y} \sim p_{\text{data}}}\bigl[k(\mathbf{x}, \mathbf{y})\bigr] + \mathbb{E}_{\mathbf{y}, \mathbf{y}' \sim p_{\text{data}}}\bigl[k(\mathbf{y}, \mathbf{y}')\bigr]\]
  • Remarkably, because every expectation over \(p_{\boldsymbol{\theta}}\) depends linearly on circuit probabilities, the parameter-shift rule computes exact unbiased gradients \(\partial_{\theta_j} \mathcal{L}_{\text{MMD}}^2\) purely from hardware samples drawn at shifted gate angles \(\theta_j \pm \frac{\pi}{2}\).

Quantum Circuit Born Machine sampling bitstrings via Born rule and updating circuit angles with Maximum Mean Discrepancy loss

Quantum Boltzmann Machines

  • Before diffusion models and transformers, classical Boltzmann Machines modelled distributions via a diagonal Ising energy function \(E_{\boldsymbol{\theta}}(\mathbf{z}) = -\sum_i b_i z_i - \sum_{i < j} w_{ij} z_i z_j\), assigning Boltzmann probability \(p(\mathbf{z}) \propto e^{-E_{\boldsymbol{\theta}}(\mathbf{z})}\). A Quantum Boltzmann Machine (QBM) upgrades that classical energy into a full quantum Hamiltonian \(H_{\boldsymbol{\theta}}\) by adding non-commuting transverse fields \(\Gamma_i \sigma_x^{(i)}\) alongside diagonal couplings \(\sigma_z^{(i)} \sigma_z^{(j)}\).

  • At thermal equilibrium, the QBM settles into the quantum Gibbs state

\[\rho_{\boldsymbol{\theta}} = \frac{e^{-H_{\boldsymbol{\theta}}}}{\operatorname{Tr}\!\bigl(e^{-H_{\boldsymbol{\theta}}}\bigr)}\]
  • Because \(\sigma_x\) and \(\sigma_z\) do not commute, \(\rho_{\boldsymbol{\theta}}\) can encode off-diagonal quantum coherences and entanglement that no classical Boltzmann machine can match. That extra richness comes at a computational price, because non-commuting operators prevent the neat derivative identity used in classical log-likelihood training, forcing QBM algorithms to rely on variational relative-entropy bounds (via the Golden-Thompson inequality) or dedicated quantum thermal-state preparation subroutines.

Variational Quantum Eigensolver for Molecular Energies

  • In chapter 23 (Molecule Design), we saw how geometric graph neural networks and generative models accelerate drug discovery and catalyst screening. Yet every supervised molecular property predictor is only as trustworthy as the quantum-chemistry reference energies it learns from! Computing the true electronic ground-state energy \(E_0\) of a strongly correlated molecule (such as the iron-molybdenum cofactor that bacteria use to turn atmospheric nitrogen into fertiliser at room temperature) pushes classical supercomputers to their knees, because tracking \(M\) interacting electrons across spin-orbitals spans an exponentially large Hilbert space.

  • The Variational Quantum Eigensolver (VQE) turns one of the oldest theorems in quantum physics into a practical hybrid machine-learning loop. Think of lowering a weighted plumb line from a drifting boat into a dark underwater canyon. No matter where you drop the weight, the depth you measure is guaranteed to lie at or above the deepest point on the canyon floor.

  • Mathematically, the Rayleigh-Ritz variational principle states that for any molecular Hamiltonian \(H\) with true ground-state energy \(E_0\) and any normalised trial wavefunction \(|\psi(\boldsymbol{\theta})\rangle\), the expected energy always upper-bounds the true ground state

\[E(\boldsymbol{\theta}) = \langle \psi(\boldsymbol{\theta}) | H | \psi(\boldsymbol{\theta}) \rangle \ge E_0\]
  • Running VQE connects quantum chemistry and variational optimisation in four tidy steps.

    • Fermion-to-qubit mapping. Electrons obey the Pauli exclusion principle (fermionic antisymmetry), whereas qubits are distinguishable two-level spins. Encodings such as Jordan-Wigner or Bravyi-Kitaev translate the second-quantised molecular Hamiltonian into a weighted sum of Pauli tensor products \(H = \sum_{m=1}^M c_m P_m\), where each \(P_m \in \{I, X, Y, Z\}^{\otimes n}\).
    • Chemistry-inspired ansatz. A parameterised circuit prepares \(|\psi(\boldsymbol{\theta})\rangle = U(\boldsymbol{\theta})|\psi_{\text{HF}}\rangle\) starting from the classical Hartree-Fock reference state. The gold-standard Unitary Coupled Cluster (UCCSD) ansatz applies single and double electron-excitation gates that conserve electron count and spin automatically, while shallower hardware-efficient ansätze trade chemical structure for lower gate depth on noisy processors.
    • Term-by-term measurement. Rather than measuring the full Hamiltonian in one impossibly complex basis, the quantum processor prepares \(|\psi(\boldsymbol{\theta})\rangle\) repeatedly, rotates into the eigenbasis of commuting groups of Pauli strings \(P_m\), and estimates each expectation \(\langle P_m \rangle\) from measurement shots.
    • Classical energy summation and update. A classical computer sums \(E(\boldsymbol{\theta}) = \sum_m c_m \langle P_m \rangle\) and updates \(\boldsymbol{\theta}\) (via gradient descent, SPSA, or BFGS) until the energy converges to \(E_0\).
  • By repeating VQE across different interatomic bond distances \(R\), chemists trace full potential energy surfaces, unlocking equilibrium geometries, dissociation energies, and reaction barriers that feed directly back into the classical molecular force fields and drug-design pipelines of chapter 23.

Take-Home

  • Quantum feature maps lift classical inputs \(\mathbf{x}\) into \(2^n\)-dimensional Hilbert space states \(|\phi(\mathbf{x})\rangle\), letting a classical SVM find globally optimal decision boundaries from hardware-estimated fidelity kernels \(K(\mathbf{x}, \mathbf{x}') = |\langle\phi(\mathbf{x})|\phi(\mathbf{x}')\rangle|^2\) via compute-uncompute or swap-test circuits.
  • Overly expressive quantum embeddings suffer from kernel concentration, pushing distinct states almost completely orthogonal so off-diagonal overlaps vanish toward \(2^{-n}\) unless tamed by bandwidth scaling or projected local kernels.
  • Quantum Neural Networks achieve non-linearity through data re-uploading and measurement rather than hidden activation functions, while Quantum Convolutional Neural Networks halve qubits hierarchically to reach \(\mathcal{O}(\log n)\) depth and avoid barren plateaus.
  • Quantum Circuit Born Machines sample discrete bitstrings natively through Born's rule with no partition function and train cleanly via kernel-based MMD loss, whereas Quantum Boltzmann Machines extend classical Ising models with non-commuting transverse quantum fields.
  • The Variational Quantum Eigensolver combines fermion-to-qubit mappings, chemistry-aware circuits, and the Rayleigh-Ritz principle to approximate molecular ground-state energies directly, bridging quantum hardware to the molecular design workflows of chapter 23.

Coding Tasks (use CoLab or notebook)

  1. Build a 2-qubit ZZ-entangling quantum feature map in JAX, compute the exact fidelity quantum kernel matrix \(K(\mathbf{x}_i, \mathbf{x}_j) = |\langle\phi(\mathbf{x}_i)|\phi(\mathbf{x}_j)\rangle|^2\) on a non-linearly separable concentric-circle dataset, and train a classical kernel SVM with soft-margin hinge loss using jax.grad. Compare well-scaled bandwidth (\(\alpha = 1.0\)) against an over-stretched high-bandwidth embedding (\(\alpha = 6.0\)) to witness kernel concentration turning the Gram matrix nearly diagonal.

    import jax
    import jax.numpy as jnp
    import matplotlib.pyplot as plt
    
    key = jax.random.PRNGKey(42)
    n_pts = 80
    angles = jnp.linspace(0.0, 2.0 * jnp.pi, n_pts // 2, endpoint=False)
    k1, k2 = jax.random.split(key)
    r_inner = 0.35 + 0.08 * jax.random.normal(k1, (n_pts // 2,))
    r_outer = 1.05 + 0.08 * jax.random.normal(k2, (n_pts // 2,))
    X_inner = jnp.stack([r_inner * jnp.cos(angles), r_inner * jnp.sin(angles)], axis=1)
    X_outer = jnp.stack([r_outer * jnp.cos(angles), r_outer * jnp.sin(angles)], axis=1)
    X = jnp.concatenate([X_inner, X_outer], axis=0)
    y = jnp.concatenate([-jnp.ones(n_pts // 2), jnp.ones(n_pts // 2)], axis=0)
    
    # 2-qubit ZZ-feature map state |phi(x)> = U_ZZ(x) H^{\otimes 2} |00>
    def quantum_state(x, scale):
        sx = x * scale
        # Basis order: |00>, |01>, |10>, |11> with eigenvalues z0, z1 in {+1, -1}
        z0 = jnp.array([1.0, 1.0, -1.0, -1.0])
        z1 = jnp.array([1.0, -1.0, 1.0, -1.0])
        phase1 = sx[0] * z0 + sx[1] * z1 + (jnp.pi - sx[0]) * (jnp.pi - sx[1]) * (z0 * z1)
        # Apply H^{\otimes 2} mixing layer followed by a second ZZ encoding layer
        psi = 0.5 * jnp.exp(-1j * phase1)
        H2 = 0.5 * jnp.array([[1, 1, 1, 1], [1, -1, 1, -1], [1, 1, -1, -1], [1, -1, -1, 1]], dtype=jnp.complex64)
        psi = jnp.dot(H2, psi)
        psi = psi * jnp.exp(-1j * phase1)
        return psi
    
    def compute_kernel(X_data, scale):
        states = jnp.stack([quantum_state(X_data[i], scale) for i in range(X_data.shape[0])], axis=0)
        overlaps = jnp.dot(jnp.conj(states), states.T)
        return jnp.real(overlaps * jnp.conj(overlaps))
    
    K_good = compute_kernel(X, scale=1.0)
    K_conc = compute_kernel(X, scale=6.0)
    
    # Train kernel SVM via soft-margin hinge loss in dual/representer form
    def train_kernel_svm(K, y_lbl, steps=250, lr=0.08, reg=0.01):
        def loss_fn(alpha, b):
            scores = jnp.dot(K, alpha) + b[0]
            hinge = jnp.mean(jnp.maximum(0.0, 1.0 - y_lbl * scores))
            rkhs_reg = 0.5 * reg * jnp.dot(alpha, jnp.dot(K, alpha))
            return hinge + rkhs_reg
        alpha = jnp.zeros(K.shape[0])
        b = jnp.array([0.0])
        grad_fn = jax.grad(loss_fn, argnums=(0, 1))
        for _ in range(steps):
            g_a, g_b = grad_fn(alpha, b)
            alpha = alpha - lr * g_a
            b = b - lr * g_b
        preds = jnp.sign(jnp.dot(K, alpha) + b[0])
        return (alpha, b[0]), float(jnp.mean(preds == y_lbl))
    
    _, acc_good = train_kernel_svm(K_good, y)
    _, acc_conc = train_kernel_svm(K_conc, y)
    off_mask = 1.0 - jnp.eye(n_pts)
    var_good = float(jnp.var(K_good[off_mask > 0]))
    var_conc = float(jnp.var(K_conc[off_mask > 0]))
    print(f"Scale 1.0 -> Accuracy: {acc_good:.3f}, Off-diag kernel var: {var_good:.4f}")
    print(f"Scale 6.0 -> Accuracy: {acc_conc:.3f}, Off-diag kernel var: {var_conc:.4f}")
    
    fig, axes = plt.subplots(1, 3, figsize=(12, 3.6))
    axes[0].scatter(X_inner[:, 0], X_inner[:, 1], color="#e74c3c", label="Inner (-1)")
    axes[0].scatter(X_outer[:, 0], X_outer[:, 1], color="#3498db", label="Outer (+1)")
    axes[0].set_title("Concentric Data (Non-Linear)"); axes[0].legend()
    axes[1].imshow(K_good, cmap="viridis", vmin=0.0, vmax=1.0)
    axes[1].set_title(f"Well-Scaled Kernel (Acc={acc_good:.2f})")
    axes[2].imshow(K_conc, cmap="viridis", vmin=0.0, vmax=1.0)
    axes[2].set_title(f"Concentrated Kernel (Var={var_conc:.3f})")
    plt.tight_layout(); plt.show()
    

  2. Implement a 3-qubit Quantum Circuit Born Machine (QCBM) trained with Maximum Mean Discrepancy (MMD) loss. Construct a hardware-efficient circuit of Ry rotations and ring CNOT entanglers, train its angles with jax.grad to reproduce a multimodal 3-bit target distribution (concentrated on bitstrings 000, 011, 101, and 110), and plot the learned Born probabilities against the target distribution.

    import jax
    import jax.numpy as jnp
    import matplotlib.pyplot as plt
    
    # 3-qubit basis gates (8x8 real matrices)
    I2 = jnp.eye(2)
    CNOT_2q = jnp.array([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]], dtype=jnp.float32)
    CNOT_01 = jnp.kron(CNOT_2q, I2)
    CNOT_12 = jnp.kron(I2, CNOT_2q)
    # CNOT from qubit 2 (LSB) to qubit 0 (MSB)
    P0 = jnp.array([[1, 0], [0, 0]], dtype=jnp.float32)
    P1 = jnp.array([[0, 0], [0, 1]], dtype=jnp.float32)
    X2 = jnp.array([[0, 1], [1, 0]], dtype=jnp.float32)
    CNOT_20 = jnp.kron(jnp.kron(I2, I2), P0) + jnp.kron(jnp.kron(X2, I2), P1)
    ENTANGLE = jnp.dot(CNOT_20, jnp.dot(CNOT_12, CNOT_01))
    
    def ry(theta):
        c, s = jnp.cos(theta / 2.0), jnp.sin(theta / 2.0)
        return jnp.array([[c, -s], [s, c]])
    
    def qcbm_probs(params):
        psi = jnp.array([1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0])
        n_layers = params.shape[0]
        for l in range(n_layers):
            U_rot = jnp.kron(jnp.kron(ry(params[l, 0]), ry(params[l, 1])), ry(params[l, 2]))
            psi = jnp.dot(U_rot, psi)
            if l < n_layers - 1:
                psi = jnp.dot(ENTANGLE, psi)
        return psi ** 2
    
    # Target even-parity distribution over 3-bit strings: 000, 011, 101, 110
    p_target = jnp.array([0.30, 0.0, 0.0, 0.25, 0.0, 0.20, 0.25, 0.0])
    bit_idx = jnp.arange(8, dtype=jnp.float32)
    diff_sq = (bit_idx[:, None] - bit_idx[None, :]) ** 2
    K_mmd = 0.5 * jnp.exp(-diff_sq / 0.5) + 0.5 * jnp.exp(-diff_sq / 4.0)
    
    def mmd_loss(params):
        p = qcbm_probs(params)
        diff = p - p_target
        return jnp.dot(diff, jnp.dot(K_mmd, diff))
    
    key = jax.random.PRNGKey(7)
    params = jax.random.uniform(key, (4, 3), minval=-jnp.pi, maxval=jnp.pi)
    grad_fn = jax.grad(mmd_loss)
    losses = []
    for step in range(300):
        losses.append(float(mmd_loss(params)))
        params = params - 0.6 * grad_fn(params)
    
    p_learned = qcbm_probs(params)
    tv_dist = float(0.5 * jnp.sum(jnp.abs(p_learned - p_target)))
    print(f"Final MMD^2: {losses[-1]:.6f}, Total Variation Distance: {tv_dist:.4f}")
    
    labels = [f"{i:03b}" for i in range(8)]
    x_pos = jnp.arange(8)
    fig, axes = plt.subplots(1, 2, figsize=(11, 3.8))
    axes[0].bar(x_pos - 0.18, p_target, width=0.35, color="#3498db", label="Target p_data")
    axes[0].bar(x_pos + 0.18, p_learned, width=0.35, color="#27ae60", label="QCBM p_theta")
    axes[0].set_xticks(range(8)); axes[0].set_xticklabels(labels)
    axes[0].set_title("QCBM Learned vs Target Bitstring Distribution"); axes[0].set_ylabel("Probability"); axes[0].legend()
    axes[1].plot(losses, color="#9b59b6", lw=2.0)
    axes[1].set_title("MMD^2 Training Loss Curve"); axes[1].set_xlabel("Optimisation Step"); axes[1].set_ylabel("MMD^2")
    plt.tight_layout(); plt.show()
    

  3. Build a Variational Quantum Eigensolver (VQE) for the dihydrogen molecule (\(\text{H}_2\)) across bond lengths \(R \in [0.4, 2.4]\,\text{\AA}\). Using the 2-qubit parity-reduced molecular Hamiltonian \(H(R) = g_0 I + g_1 Z_0 + g_2 Z_1 + g_3 Z_0 Z_1 + g_4 X_0 X_1 + g_5 Y_0 Y_1\), minimise \(\langle\psi(\theta)|H(R)|\psi(\theta)\rangle\) with jax.grad and verify that VQE matches exact matrix diagonalisation along the entire molecular dissociation curve.

    import jax
    import jax.numpy as jnp
    import matplotlib.pyplot as plt
    
    # Pauli matrices and 2-qubit tensor products
    I2 = jnp.eye(2)
    X = jnp.array([[0.0, 1.0], [1.0, 0.0]])
    Y_YY = jnp.array([[0, 0, 0, -1], [0, 0, 1, 0], [0, 1, 0, 0], [-1, 0, 0, 0]], dtype=jnp.float32)  # Y \otimes Y is purely real!
    Z = jnp.array([[1.0, 0.0], [0.0, -1.0]])
    II, ZI, IZ, ZZ, XX = jnp.kron(I2, I2), jnp.kron(Z, I2), jnp.kron(I2, Z), jnp.kron(Z, Z), jnp.kron(X, X)
    
    # STO-3G Bravyi-Kitaev 2-qubit H2 Hamiltonian coefficients (Hartree) at bond lengths (Angstrom)
    bond_lengths = [0.40, 0.55, 0.74, 0.95, 1.20, 1.50, 1.90, 2.40]
    coeffs = [
        (0.4808,  0.6888, -0.6888, 0.0112, 0.0823, 0.0823),
        (0.0050,  0.5205, -0.5205, 0.0112, 0.0861, 0.0861),
        (-0.3100, 0.3979, -0.3979, 0.0112, 0.0905, 0.0905),
        (-0.4860, 0.2896, -0.2896, 0.0112, 0.0956, 0.0956),
        (-0.5860, 0.1995, -0.1995, 0.0112, 0.1021, 0.1021),
        (-0.6420, 0.1291, -0.1291, 0.0112, 0.1098, 0.1098),
        (-0.6720, 0.0680, -0.0680, 0.0112, 0.1189, 0.1189),
        (-0.6800, 0.0250, -0.0250, 0.0112, 0.1255, 0.1255),
    ]
    
    # Chemistry-preserving double-excitation ansatz: |psi(theta)> = cos(t/2)|01> - sin(t/2)|10>
    def vqe_state(theta):
        return jnp.array([0.0, jnp.cos(theta / 2.0), -jnp.sin(theta / 2.0), 0.0])
    
    exact_energies, vqe_energies = [], []
    for R, (g0, g1, g2, g3, g4, g5) in zip(bond_lengths, coeffs):
        H = g0 * II + g1 * ZI + g2 * IZ + g3 * ZZ + g4 * XX + g5 * Y_YY
        e_exact = float(jnp.linalg.eigh(H)[0][0])
    
        def energy_fn(theta):
            psi = vqe_state(theta)
            return jnp.dot(psi, jnp.dot(H, psi))
    
        theta = jnp.array(0.1)
        grad_e = jax.grad(energy_fn)
        for _ in range(120):
            theta = theta - 0.5 * grad_e(theta)
        e_vqe = float(energy_fn(theta))
        exact_energies.append(e_exact)
        vqe_energies.append(e_vqe)
    
    min_idx = int(jnp.argmin(jnp.array(vqe_energies)))
    max_err = max(abs(a - b) for a, b in zip(exact_energies, vqe_energies))
    print(f"Equilibrium bond length: {bond_lengths[min_idx]:.2f} A, Ground energy: {vqe_energies[min_idx]:.4f} Ha")
    print(f"Max VQE vs Exact error across curve: {max_err:.2e} Ha (chemical accuracy is 1.6e-3 Ha)")
    
    plt.figure(figsize=(7.2, 4.2))
    plt.plot(bond_lengths, exact_energies, color="#333", lw=2.2, label="Exact Diagonalisation")
    plt.scatter(bond_lengths, vqe_energies, color="#e74c3c", s=55, zorder=5, label="VQE Ground Energy")
    plt.axvline(0.74, color="#27ae60", ls="--", lw=1.2, label="Equilibrium R = 0.74 A")
    plt.title("H2 Molecular Potential Energy Dissociation Curve via VQE")
    plt.xlabel("Interatomic Bond Length R (Angstrom)"); plt.ylabel("Ground-State Energy (Hartree)")
    plt.legend(); plt.tight_layout(); plt.show()