Lecture 8 - Quantum Artificial Intelligence

Lecture 8 - Quantum Artificial Intelligence

Updated 27 Nov 2026

Chapter map

  • 1. Variational Quantum Algorithms (slides 3–13): ML recap, VQA loop, quantum embedding, ansatz, basic/strong entanglers, expressivity vs trainability, HEA/TEN/ALT
  • 2. Hybrid Classical-Quantum Machine Learning (slides 14–28): prediction loss, SGD, projection-based loss, MSE/NLL/hinge, parameter shift rule
  • 3. Quantum Kernel Methods (slides 29–36): kernels, SVM, quantum SVM — cancelled from the final ("you can cancel out the support vector machine")
  • 4. Quantum Neural Networks (slides 37–51): classical vs quantum perceptron, QMLP, QDNN, backprop, XOR, hybrid deep models, barren plateau
  • 5. Conclusion (slides 52–54)
  • Exam: Final Q7 — Quantum Machine Learning: slides 4–5, 7–9, 14–15, 21–24, 37–41. Instructor: "not going to be involved with math… it's going to be why questions." → see Final - Instructor Hints
  • Instructor: Dr. Prachya Boonkwan (P' Arm), version Nov 17, 2026 (last class)

Final Q7 — Quantum Machine Learning

  • Slides 4–5 (VQA loop, quantum embedding), 7–9 (ansatz, basic & strong entanglers), 14–15 (prediction loss, SGD), 21–24 (hybrid model, parameter shift rule, gradients of losses), 37–41 (perceptron → quantum perceptron → QMLP → QDNN → backprop)
  • Expect "why" questions (no heavy math): why choose this embedding, why basic over strong entangler, why the parameter shift rule, why no activation function in a quantum perceptron, why train classically.
  • Related: Final - Instructor Hints

1. Variational Quantum Algorithms

Machine Learning

  • Machine learning = a class of algorithms and statistical models that make a prediction on an unseen input from the patterns observed in the training dataset
  • Supervised learning = an ML technique that classifies an unseen item with respect to the criteria, a.k.a. model, constructed from the observed patterns
  • The model consists of adjustable parameters, so that it performs accurate classification
  • Figure 1 (Supervised learning): labeled examples (apple, lime, apple, lime) → Extract patterns → Model (classification criteria: "What is apple?" shape + color; "What is lime?" shape + color) → Classify → unseen object = Lime (85%)
    • The model here has two parameters: shape and color
    • "85%" = confidence score

🎙️ In class (Nov 17, 16:12–19:33): Classification = vectorize the unseen object (find its vector representation), then decide its class from that vector. The model = classification criteria described by features (shape, color). Output comes with a confidence score (e.g. 85% lime). To make it accurate you adjust the model's parameters.

🎙️ In class (Nov 17, 19:33): The point of today: (1) the model can be quantum, and (2) when it is quantum, you can adjust parameters "in the quantum way", i.e. many parameters at the same time.

💡 Analogy: A fruit seller at Talad Thai who has seen thousands of limes and apples. Her "model" is two rules in her head (shape + colour). Show her a new fruit and she says "lime, 85% sure". Training = adjusting how much she trusts shape vs colour.

Variational Quantum Algorithm {Exam Q7}

  • A class of hybrid quantum algorithms that find approximate solutions to problems with both classical and quantum computing
    • We convert classical data items to equivalent quantum states
    • A parameterized quantum circuit computes a temporary solution
    • We measure the distance between this temporary solution and the gold standard
    • We optimize the parameters to minimize the distance
    • After some iterations, we obtain the optimal solution (parameters) to the problem
  • Diagram (the VQA loop):
    • Quantum part: Classical data → Quantum state ∣ψ⟩|\psi\rangle → Parameterized quantum circuit Ψ(Θ)\Psi(\Theta) → Measurement
    • Classical part: Measurement → Loss function LL (compared with the Gold standard) → Parameter Optimization → feeds new Θ\Theta back into Ψ(Θ)\Psi(\Theta)

data→∣ψ⟩→Ψ(Θ)→measure→L(Θ)→update Θ→repeat\boxed{\text{data} \to |\psi\rangle \to \Psi(\Theta) \to \text{measure} \to L(\Theta) \to \text{update } \Theta \to \text{repeat}}

📝 Instructor's annotation: Next to the quantum part he wrote: "We will use quantum algorithms as non-linear activation functions."

🎙️ In class (Nov 17, 20:07–21:49): It looks almost like traditional ML — the only difference is the quantum part. Instead of converting an object into a real-valued vector, we convert it into a quantum state (can be complex), then feed it to a parameterized quantum circuit (circuit with adjustable parameters). Spoiler: "you will use the quantum algorithm as non-linear activation function… especially in neural networks."

🎙️ In class (Nov 17, 22:24–24:04): Model parameters → prediction (state measurement) → compare with gold standard → loss → readjust parameters with stochastic gradient descent (SGD). "This goes on and on as a loop."

🎙️ In class (Nov 10, 52:20): "Variational means you can adjust parameters inside a quantum algorithm. Rotation — you can adjust the angle of the rotation and it changes the behavior of your quantum algorithm." He called it a "configurable sausage machine".

❓ Why "variational"? Because the circuit contains rotation gates whose angles θ\theta are free parameters. Varying θ\theta varies the output state, so the circuit's behaviour can be tuned (learned) instead of designed by hand.

❓ Why hybrid (why is the optimization done on a classical computer)? (Asked in class, Nov 17, 06:07–06:36) Current quantum computers have few qubits and are noisy (NISQ) — not reliable for the iterative parameter-training loop. So the quantum chip only does what it is good at (preparing/measuring a high-dimensional state), and the classical computer does the bookkeeping: computing the loss and updating Θ\Theta.

❓ Why use a quantum circuit at all? Rotations + entanglement give a non-linear, highly expressive mapping over an exponentially large state space with few parameters — it acts like a learnable non-linear activation function.

💡 Analogy: Tuning a guitar. The guitar (quantum circuit) makes the sound; your ear + tuner app (classical computer) measures how far it is from the right note (loss) and tells you which peg (parameter θ\theta) to turn and by how much. Repeat until in tune.

Quantum Embedding {Exam Q7}

  • The first step of a VQA is to convert a data item into an equivalent quantum state
  • Three approaches: basis (direct) embedding, angular encoding, and amplitude encoding
  • Basis embedding: convert a set of bitstrings into a mixed state by the uniform state preparation algorithm (CH4):

{x1,…,xM}  ↦  1M∑k=1M∣xk⟩\boxed{\{\mathbf{x}_1,\dots,\mathbf{x}_M\} \;\mapsto\; \frac{1}{\sqrt{M}}\sum_{k=1}^{M}|\mathbf{x}_k\rangle}

  • Use this method when the input is a set of binary features
  • Angular embedding: convert a list of real-valued features into a quantum state by phase rotation:

{x1,…,xN}  ↦  (∏k=1NRY(xk))∣0⟩⊗N\boxed{\{x_1,\dots,x_N\} \;\mapsto\; \left(\prod_{k=1}^{N}\mathbf{RY}(x_k)\right)|0\rangle^{\otimes N}}

  • One qubit per feature (NN features → NN qubits); each RY(xk)\mathbf{RY}(x_k) acts on qubit kk
  • Amplitude embedding: convert a time series of real-valued items into a quantum state by superposition (values become amplitudes):

[x1,…,xN]  =  ∑k=0N−1xk ∣BL(k)⟩\boxed{[x_1,\dots,x_N] \;=\; \sum_{k=0}^{N-1} x_k\,|\mathbb{B}_L(k)\rangle}

  • where L=⌈log⁡2N⌉L=\lceil\log_2 N\rceil is the number of qubits, and BL(k)\mathbb{B}_L(k) is kk written as an LL-bit binary string
  • The vector must be normalized first (∑∣xk∣2=1\sum|x_k|^2=1)

📝 Instructor's annotation: Under 1M∑∣xk⟩\frac{1}{\sqrt M}\sum|\mathbf x_k\rangle he wrote "uniform distribution" (every bitstring gets the same amplitude 1/M1/\sqrt M). He highlighted "convert a data item into an equivalent quantum state".

MethodInput dataQubits neededHow data is stored
Basisbinary features / bitstrings1 per bitwhich basis states appear (uniform superposition)
AngularNN real valuesNNrotation angles of RY\mathbf{RY}
AmplitudeNN real values (time series), normalized⌈log⁡2N⌉\lceil\log_2 N\rceilamplitudes of the superposition

🎙️ In class (Nov 17, 24:23–25:30): "Embedding" comes from embedding vector = assigning a vector to an item (a book, an apple). Quantum embedding = assigning a quantum state to an item.

🎙️ In class (Nov 17, 25:50–27:25): Basis embedding is the simplest — directly convert binary features into a superposition. (He deliberately skipped the details of how the encoding circuit is built: "just learn that it exists".)

🎙️ In class (Nov 17, 28:46–29:41): In angular embedding the data is "in the gate, not in the state": the input state is just ∣0⟩|0\rangle, and each feature becomes the rotation angle for its own qubit.

🎙️ In class (Nov 17, 29:51–30:43, student Q "how precise?"): Angular is less accurate — "fewer parameters". Each xkx_k is real, no longer binary.

🎙️ In class (Nov 17, 30:43–31:20): "You need to choose your embedding according to your data." Binary features → basis (very accurate). Real numbers → angular (qubit rotations) or amplitude.

🎙️ In class (Nov 17, 32:04–33:56): Amplitude embedding must be normalized (student asked; code divides by np.linalg.norm). "You don't really have to mention [the PennyLane commands] in the final exam. What you really have to do is to choose the embedding method according to the data."

❓ Why do we need quantum embedding? A quantum circuit can only process quantum states, not floating-point vectors. Embedding is the bridge from classical data to the quantum part of the VQA (like vectorizing an object before classical ML).

❓ Why basis embedding for binary features? Bits map exactly onto ∣0⟩/∣1⟩|0\rangle/|1\rangle — no loss of information, no rounding. Each bitstring becomes one basis state.

❓ Why angular embedding for real-valued features? A real number can't be a basis state, but it can be an angle. RY(x)\mathbf{RY}(x) turns ∣0⟩|0\rangle into cos⁡x2∣0⟩+sin⁡x2∣1⟩\cos\frac{x}{2}|0\rangle+\sin\frac{x}{2}|1\rangle — real amplitudes, easy to prepare, one qubit per feature. Rotation is periodic (non-linear) — it already behaves like a non-linear feature map.

❓ Why amplitude embedding? It is the most qubit-efficient: NN values in only ⌈log⁡2N⌉\lceil\log_2N\rceil qubits (exponential compression). Costs: data must be normalized (we lose the overall scale), and preparing an arbitrary state needs a deep circuit (noisy on NISQ).

❓ Can more than one method apply? Yes — binary data can be angle-encoded too (angles 00 or π\pi give ∣0⟩|0\rangle/∣1⟩|1\rangle), and real data can use either angular or amplitude. The choice is a trade-off: qubits available vs circuit depth vs accuracy.

💡 Analogy: Packing a parcel at a Thai post office. Basis = light switches on/off (one switch per bit). Angular = one volume knob per feature, turned to an angle. Amplitude = one big mixing desk where all values share one normalized "total volume" — super compact (few qubits), but you must rescale everything first.

Related

Quantum Embedding in PennyLane

basis_wires = ['d1', 'd2', 'd3']
angular_wires = ['g1', 'g2', 'g3']
amplitude_wires = ['a1', 'a2', 'a3']
dev = qml.device('default.qubit', wires=basis_wires + angular_wires + amplitude_wires)
 
@qml.qnode(dev, shots=100)
def embedding_circuit():
    # Basis encoding: N binary digits -> N qubits
    bitstring = [1, 0, 1]
    qml.BasisEmbedding(features=bitstring, wires=basis_wires)
    # Angular encoding: N continuous values -> N qubits
    angles = [np.pi / 4, np.pi / 3, np.pi / 2]
    qml.AngleEmbedding(features=angles, wires=angular_wires)
    # Amplitude encoding: 2^N continuous values -> N qubits
    amplitudes = [2.0, 1.0, 3.0, 7.0, 5.0, 4.0, 8.0, 6.0]
    amplitudes = amplitudes / np.linalg.norm(amplitudes)   # Normalization is required
    qml.AmplitudeEmbedding(features=amplitudes, wires=amplitude_wires)
    # Measurements
    return ( qml.counts(wires=basis_wires),
             qml.counts(wires=angular_wires),
             qml.counts(wires=amplitude_wires) )
 
basis_counts, angular_counts, amplitude_counts = embedding_circuit()
  • Key commands (highlighted by instructor): qml.BasisEmbedding, qml.AngleEmbedding, qml.AmplitudeEmbedding
  • Note: 3 qubits hold 3 bits (basis), 3 angles (angular), but 23=82^3=8 amplitudes (amplitude)

Ansatz (n.) 'guess' [German] {Exam Q7}

  • In most cases, we design parameterized quantum circuits in accordance with the problem; i.e. we make a guess or problem-inspired ansatz (quantum circuit)
  • There are also problem-agnostic ansatzes, e.g. entanglers, but they consist of more quantum gates and parameters
  • Example: consider the following ansatz (Figure 3: Simple ansatz)
    • Qubit 1: ∣0⟩→RX(θ1)|0\rangle \to \mathbf{RX}(\theta_1) → control of CNOT
    • Qubit 2: ∣0⟩→RX(θ2)|0\rangle \to \mathbf{RX}(\theta_2) → target of CNOT
CNOT1,2(2) RX2(2)(θ2) RX1(2)(θ1) ∣00⟩=CNOT1,2(2)(cos⁡θ12∣0⟩−isin⁡θ12∣1⟩)⊗(cos⁡θ22∣0⟩−isin⁡θ22∣1⟩)=CNOT1,2(2)(cos⁡θ12cos⁡θ22∣00⟩−icos⁡θ12sin⁡θ22∣01⟩−isin⁡θ12cos⁡θ22∣10⟩−sin⁡θ12sin⁡θ22∣11⟩)=cos⁡θ12cos⁡θ22∣00⟩−icos⁡θ12sin⁡θ22∣01⟩−isin⁡θ12cos⁡θ22∣11⟩−sin⁡θ12sin⁡θ22∣10⟩\begin{aligned} &\mathrm{CNOT}^{(2)}_{1,2}\,\mathbf{RX}^{(2)}_2(\theta_2)\,\mathbf{RX}^{(2)}_1(\theta_1)\,|00\rangle \\ &= \mathrm{CNOT}^{(2)}_{1,2}\left(\cos\tfrac{\theta_1}{2}|0\rangle - i\sin\tfrac{\theta_1}{2}|1\rangle\right)\otimes\left(\cos\tfrac{\theta_2}{2}|0\rangle - i\sin\tfrac{\theta_2}{2}|1\rangle\right) \\ &= \mathrm{CNOT}^{(2)}_{1,2}\Big(\cos\tfrac{\theta_1}{2}\cos\tfrac{\theta_2}{2}|00\rangle - i\cos\tfrac{\theta_1}{2}\sin\tfrac{\theta_2}{2}|01\rangle \\ &\qquad - i\sin\tfrac{\theta_1}{2}\cos\tfrac{\theta_2}{2}|10\rangle - \sin\tfrac{\theta_1}{2}\sin\tfrac{\theta_2}{2}|11\rangle\Big) \\ &= \cos\tfrac{\theta_1}{2}\cos\tfrac{\theta_2}{2}|00\rangle - i\cos\tfrac{\theta_1}{2}\sin\tfrac{\theta_2}{2}|01\rangle \\ &\qquad - i\sin\tfrac{\theta_1}{2}\cos\tfrac{\theta_2}{2}|11\rangle - \sin\tfrac{\theta_1}{2}\sin\tfrac{\theta_2}{2}|10\rangle \end{aligned}
  • Step logic: (1) each RX\mathbf{RX} acts on its own qubit → tensor product; (2) expand; (3) CNOT flips qubit 2 when qubit 1 is ∣1⟩|1\rangle → ∣10⟩↔∣11⟩|10\rangle\leftrightarrow|11\rangle swap their coefficients

📝 Instructor's annotation: At the top: "Challenge: How can we design a quantum prediction model by guessing a trial wave function for the problem?" with an arrow from "trial wave function" → "ansatz".

🎙️ In class (Nov 17, 34:19–35:28): Ansatz is German for guess. In quantum physics, to explain a phenomenon you try all possible wave functions consistent with your assumptions — each is a trial wave function. In quantum algorithms: try / guess all possible sets of parameters θ\theta.

🎙️ In class (Nov 17, 35:49–37:31): Figure 3 is a scheme: vary θ1,θ2\theta_1,\theta_2 → one ansatz; vary again → another. The final expression is a wave function whose every coefficient is controlled by θ1\theta_1 and θ2\theta_2. In QC, "ansatz" ≈ "quantum circuit with variables". He jokes he calls it by a similar-sounding Thai swear word (53:59).

🎙️ In class (Nov 17, 38:02–39:45): Designing a problem-inspired ansatz needs background knowledge of the data. In ML we prefer a generalized circuit → problem-agnostic ("problem-neutral") ansatz. Agnostic = you don't take sides (like religious agnosticism: neither support nor oppose).

❓ Why use an ansatz (a guessed circuit shape)? Searching over all unitaries is impossible. We fix a circuit shape (the guess) and only learn its angles — turning "design a quantum algorithm" into "optimize a few numbers", exactly like fixing a neural-network architecture and learning its weights.

❓ Why problem-agnostic in ML? We usually don't know the structure of the solution; a neutral rotation+entanglement circuit can be reused for any classification problem. Price: more gates and parameters.

💡 Analogy: An ansatz is a recipe template — "stir-fry: oil, protein, sauce, X minutes". The template is the guess; the amounts (θ) are what you tune by tasting (loss).

Problem-Agnostic Ansatzes/1 — Basic Entangler {Exam Q7}

  • Basic entangler: we rotate each kk-th qubit with RX(θk)\mathbf{RX}(\theta_k) and create an entangled state out of them

BEL(Θ)=∏j=1NCNOTj,(j+1)%N(N)  ∏k=1NRXk(N)(θk)\boxed{\mathrm{BEL}(\Theta) = \prod_{j=1}^{N}\mathrm{CNOT}^{(N)}_{j,(j+1)\%N}\;\prod_{k=1}^{N}\mathbf{RX}^{(N)}_k(\theta_k)}

  • where parameters Θ=(θ1,…,θN)\Theta=(\theta_1,\dots,\theta_N)
  • CNOTs form a ring: 1→2,  2→3,…,  N→11\to2,\;2\to3,\dots,\;N\to1 (control jj, target j+1j+1, wrapping around)
  • Recall that RX(θ)\mathbf{RX}(\theta) rotates the qubit about the X-axis:

∣0⟩↦cos⁡θ2∣0⟩−isin⁡θ2∣1⟩,∣1⟩↦−isin⁡θ2∣0⟩+cos⁡θ2∣1⟩\boxed{|0\rangle \mapsto \cos\tfrac{\theta}{2}|0\rangle - i\sin\tfrac{\theta}{2}|1\rangle, \qquad |1\rangle \mapsto -i\sin\tfrac{\theta}{2}|0\rangle + \cos\tfrac{\theta}{2}|1\rangle}

  • In one basic-entangler layer for NN wires, there are only NN parameters
  • We can stack LL basic-entangler layers in a more complex model:

MultiBEL(ΘL×N)=∏k=1LBEL(Θk)\boxed{\mathrm{MultiBEL}(\Theta_{L\times N}) = \prod_{k=1}^{L}\mathrm{BEL}(\Theta_k)}

  • Figure 4 (Basic-entangler layer, 4 wires): RX(θ1)…RX(θ4)\mathbf{RX}(\theta_1)\dots\mathbf{RX}(\theta_4), then CNOT 1→2, 2→3, 3→4, 4→1

📝 Instructor's annotation: Above the figure: "less parameters: easier to train but less flexible", with an arrow from "flexible" to "expressive".

🎙️ In class (Nov 17, 40:03–40:40): Rotation gates on each qubit (RX in the example, but RY/RZ also fine), then entangle, entangle, entangle in a ring.

🎙️ In class (Nov 17, 40:48–41:54): Why entangle? "In quantum ML we want to learn how to create an arbitrary quantum state, and in most cases they are entanglement. So we need to accommodate entanglement." Part 1 = parameterized rotation, part 2 = entanglement.

🎙️ In class (Nov 17, 42:18–44:09): One BEL is one layer; you can repeat it (e.g. 3 layers) → MultiBEL. A student summed it up: "rotate, entangle, rotate, entangle" — "How lovely." Then compare with training data, compute loss, readjust θ.

🎙️ In class (Nov 17, 52:44–54:46): Every entangler = (1) parameterized rotation + (2) entanglement. The CNOT arrangement can be anything "as long as it is entanglement"; in most cases follow the diagram.

❓ Why rotation and entanglement? Rotations alone only produce product states (⊗\otimes of single qubits) — they can't represent correlated (entangled) states, which most target states are. CNOTs alone have no parameters to learn. Together they can reach (approximately) any state as θ varies.

❓ Why stack layers? One layer has only NN angles → limited set of states. Each extra layer adds NN parameters and more entanglement → more expressive (like adding hidden layers to a neural net).

❓ Why is the basic entangler preferred in practice? Few parameters (L×NL\times N) → easier/faster to train (high trainability), hardware-friendly (RX + CNOT are native gates). "We prefer trainability to expressivity" (Nov 17, 56:21).

💡 Analogy: A line of people each spinning a hula hoop (rotation, own speed θ), then each passes a ribbon to the next person in a circle (CNOT ring) so everyone's movement becomes linked (entangled).

Problem-Agnostic Ansatzes/2 — Strong Entangler {Exam Q7}

  • Strong entangler layer: we rotate each kk-th qubit with R(αk,βk,γk,ϕ)\mathbf{R}(\alpha_k,\beta_k,\gamma_k,\phi) and create an entangled state out of them

SEL(Θ)=∏j=1NCNOT(j+1)%N, j(N)  ∏k=1NR(αk,βk,γk,ϕ)\boxed{\mathrm{SEL}(\Theta) = \prod_{j=1}^{N}\mathrm{CNOT}^{(N)}_{(j+1)\%N,\,j}\;\prod_{k=1}^{N}\mathbf{R}(\alpha_k,\beta_k,\gamma_k,\phi)}

  • where parameters Θ=(α1,β1,γ1,…,ϕ)\Theta=(\alpha_1,\beta_1,\gamma_1,\dots,\phi)
  • Note the CNOT direction is flipped vs BEL: control j+1j+1, target jj
  • R(α,β,γ,ϕ)\mathbf{R}(\alpha,\beta,\gamma,\phi) rotates the qubit with:

∣0⟩↦cis⁡βcos⁡α ∣0⟩−cis⁡(−γ)sin⁡α ∣1⟩,∣1⟩↦cis⁡γsin⁡α ∣0⟩+cis⁡(−β)cos⁡α ∣1⟩\boxed{|0\rangle \mapsto \operatorname{cis}\beta\cos\alpha\,|0\rangle - \operatorname{cis}(-\gamma)\sin\alpha\,|1\rangle, \qquad |1\rangle \mapsto \operatorname{cis}\gamma\sin\alpha\,|0\rangle + \operatorname{cis}(-\beta)\cos\alpha\,|1\rangle}

  • where the global phase term is cis⁡ϕ\operatorname{cis}\phi
  • In one strong-entangler layer for NN wires, there are 3N+13N+1 parameters
  • We can also stack LL strong-entangler layers:

MultiSEL(ΘL×3N)=∏k=1LSEL(Θk)\boxed{\mathrm{MultiSEL}(\Theta_{L\times 3N}) = \prod_{k=1}^{L}\mathrm{SEL}(\Theta_k)}

  • Figure 5 (Strong-entangler layer, 4 wires): R(αk,βk,γk,ϕ)\mathbf{R}(\alpha_k,\beta_k,\gamma_k,\phi) on each wire, then a ring of CNOTs

📝 Instructor's annotation: Above the figure: "more parameters: harder to train but more flexible", arrow from "flexible" → "expressive".

🎙️ In class (Nov 17, 45:16–46:21): "How strong? Instead of only one rotation, you've got four parameters." α, β control ∣0⟩|0\rangle; β, γ control ∣1⟩|1\rangle. "You don't really have to remember them… I don't really care about the rotation. What I care more about: these parameters control how you rotate ∣0⟩|0\rangle and ∣1⟩|1\rangle."

🎙️ In class (Nov 17, 46:27–46:47): ⚠️ "The final exam won't focus on calculation… it focuses more on why questions. Give me your rationale. Why do you choose this? Why do you choose that?"

🎙️ In class (Nov 17, 47:12–47:42): ϕ\phi = global phase, rotates both ∣0⟩|0\rangle and ∣1⟩|1\rangle together. "That's why the strong entangler gives you more flexibility — you can control how you rotate your qubit in every possible direction."

🎙️ In class (Nov 17, 47:48–48:22): "But it comes with a cost: a model with a lot of parameters takes ages to train" — like LLMs with 7B, 14B… parameters. (Anecdote: Qwen = Chinese qiān wèn, "thousand questions".)

🎙️ In class (Nov 17, 50:08–50:32): Student asked about CNOT order — "you can also flip the order of CNOT… it could be anything." The order on the slide is just one example.

❓ Why is the strong entangler more expressive? R(α,β,γ,ϕ)\mathbf R(\alpha,\beta,\gamma,\phi) is a general single-qubit rotation (any point on the Bloch sphere + phases), while RX\mathbf{RX} only rotates about one axis. More independent "knobs" per qubit → more reachable states/entanglement types.

❓ Why is it harder to train? 3N+13N+1 parameters per layer (vs NN) → bigger search space, more gradients to compute (each needs 2 circuit runs with the parameter shift rule), more randomness → more SGD iterations. Students' senior project found it ~4× slower even on small data (Nov 17, 59:05).

💡 Analogy: BEL = a car you can only steer left/right. SEL = a drone that can yaw, pitch, roll and change altitude — reaches anywhere, but much harder to learn to fly.

Exercise answers 8.1.5–8.1.8 (my worked computation — not from the instructor)

  • BEL(0)∣000⟩|000\rangle: RX(0)=I\mathbf{RX}(0)=\mathbf I, so state stays ∣000⟩|000\rangle; CNOT ring does nothing (all controls are 0) → ∣000⟩\boxed{|000\rangle}
  • BEL(π21\frac{\pi}{2}\mathbf 1)∣000⟩|000\rangle: each qubit → 12(∣0⟩−i∣1⟩)\frac{1}{\sqrt2}(|0\rangle-i|1\rangle), product =122∑x(−i)∣x∣∣x⟩=\frac{1}{2\sqrt2}\sum_x(-i)^{|x|}|x\rangle; then CNOT 1→2, 2→3, 3→1:

122(∣000⟩+i∣001⟩−∣010⟩−i∣011⟩−∣100⟩−i∣101⟩−∣110⟩−i∣111⟩)\tfrac{1}{2\sqrt2}\big(|000\rangle + i|001\rangle - |010\rangle - i|011\rangle - |100\rangle - i|101\rangle - |110\rangle - i|111\rangle\big)

  • SEL(0)∣000⟩|000\rangle: R(0,0,0,0)\mathbf R(0,0,0,0): ∣0⟩↦cos⁡0∣0⟩=∣0⟩|0\rangle\mapsto\cos0|0\rangle=|0\rangle → identity on ∣0⟩|0\rangle → ∣000⟩\boxed{|000\rangle}
  • SEL(π21\frac{\pi}{2}\mathbf 1)∣000⟩|000\rangle: ∣0⟩↦−cis⁡(−π2)∣1⟩=i∣1⟩|0\rangle\mapsto -\operatorname{cis}(-\frac{\pi}{2})|1\rangle = i|1\rangle, times global phase cis⁡π2=i\operatorname{cis}\frac{\pi}{2}=i → −∣1⟩-|1\rangle per qubit → −∣111⟩-|111\rangle; CNOTs (control j+1j{+}1 → target jj): ∣111⟩→∣011⟩→∣001⟩→∣001⟩|111\rangle\to|011\rangle\to|001\rangle\to|001\rangle → −∣001⟩-|001\rangle (i.e. ∣001⟩|001\rangle up to global phase)

Expressivity and Trainability

  • Expressivity = the number of entanglement types an ansatz can generate from its gates and parameters
  • Trainability = the number of iterations in ease of estimating the optimal parameters from the dataset
  • Hardware efficiency = ready-made hardware implementation of an ansatz so that it need not be emulated
  • Modularity = dividing the entanglement generation into manageable parts (with fewer parameters) so that the ansatz is more trainable
  • General trend:
    • The more parameters → the more types of entanglement it can generate → more flexible (expressive)
    • The more parameters → the more iterations it takes to estimate the optimal parameters (additional randomness) → less trainable

Table 1: Comparison of entangler layers

EntanglersBasicStrong
ParametersL×NL\times NL×(3N+1)L\times(3N+1)
EfficiencyMaximumHigh
ExpressivityLowMaximum
TrainabilityHighLow

📝 Instructor's annotation: He crossed out "number of iterations in" and wrote "ease of" (Trainability = ease of estimating the optimal parameters). He drew a Venn-style diagram: a small circle "BEL" inside a bigger box "SEL" — everything BEL can express, SEL can too (BEL ⊂ SEL).

🎙️ In class (Nov 17, 54:58–55:23): "In ML we don't say flexibility, we say expressivity — your quantum algorithm can express more quantum states… like freedom of expression = freedom of creation."

🎙️ In class (Nov 17, 56:21–57:31): ⭐ "We prefer trainability to expressivity… because we cannot wait. We all have ADHD." → in most cases use the basic entangler. Strong is OK for small models/few qubits; with 100 or 1,000 qubits it "takes ages".

❓ Why can't we have both? Both come from the same source — the number of parameters. More parameters = more states reachable (expressive) but a bigger, more random landscape to search (slow training, barren plateaus). It is a trade-off, like the bias–variance trade-off in ML.

💡 Analogy: A set menu (BEL) vs. build-your-own bowl with 40 toppings (SEL). The bowl can make anything, but choosing takes forever.

Ansatz Architectures

  • The design of ansatz architecture can be generally classified into three categories:
  • Hardware-Efficient Ansatz (HEA) — Frequently used
    • Offered by many NISQ device implementations
    • High expressivity: more layers = more coverage of quantum states
    • Low trainability due to numerous parameters
    • Figure 6: each entangler block spans all qubits
  • TENsor product ansatz (TEN)
    • Quantum states are divided into modules for ease of computation
    • Low expressivity: fewer entanglement types
    • High trainability due to modularity
    • Figure 7: separate entangler blocks on the top half and bottom half — never connected
  • ALTernating layered ansatz (ALT) (a.k.a. brick-wall ansatz) — Becoming popular
    • Crossing modules overlap one another
    • High expressivity: good at entanglements
    • Medium trainability due to modularity
    • Figure 8: blocks staggered like bricks, so modules overlap across layers

📝 Instructor's annotation: "Frequently used" over HEA; "Becoming popular" over ALT.

🎙️ In class (Nov 17-2, 00:30–01:07): HEA = one layer covers the whole set of qubits ("one layer takes all"); all hardware platforms provide predefined HEA circuits. ("Don't read it in Thai" — HEA sounds like a Thai swear word.)

🎙️ In class (Nov 17-2, 01:13–02:32): TEN = decompose the state into parts (tensor product). You must know the shape of the problem (e.g. first N/2N/2 qubits for one sub-task) — "if you know the problem very well, you can use TEN."

🎙️ In class (Nov 17-2, 02:39–03:32): ALT = brick wall; it is an approximation of HEA. HEA is the most expressive; ALT is less expressive "but good enough in most cases".

🎙️ In class (Nov 17-2, 03:58–04:43): Exam-technique joke: for a difficult question about missing experiments, say "due to time/hardware limitations we could not conduct this experiment."

❓ Why does ALT seem to outperform the others? (Ex 8.1.4) It gets the best of both: modular blocks (few parameters each → trainable like TEN) but the blocks overlap across layers, so entanglement still spreads through all qubits (expressive like HEA). A balanced trade-off.

Ansatz Architectures in PennyLane

import pennylane as qml
from pennylane import numpy as np
 
basic_wires = ['b1', 'b2', 'b3', 'b4']
strong_wires = ['s1', 's2', 's3', 's4']
dev = qml.device('default.qubit', wires=basic_wires + strong_wires)
basic_params = np.random.uniform(0, 2 * np.pi, (2, 4))       # 2 layers, 4 wires
strong_params = np.random.uniform(0, 2 * np.pi, (2, 4, 3))   # 2 layers, 4 wires, 3 angles
 
@qml.qnode(dev, shots=100)
def circuit(basic_params, strong_params):
    # Basic entangler requires a L x W matrix of weights
    qml.BasicEntanglerLayers(basic_params, wires=basic_wires)
    # Strong entangler requires a L x W x 3 matrix of weights
    qml.StronglyEntanglingLayers(strong_params, wires=strong_wires)
    return ( qml.counts(wires=basic_wires),
             qml.counts(wires=strong_wires) )
 
basic_counts, strong_counts = circuit(basic_params, strong_params)
print(basic_counts)
print(strong_counts)
  • Weight shapes: BEL = L×WL\times W; SEL = L×W×3L\times W\times 3

Exercise 8.1: Variational Quantum Algorithms

  1. Explain how we may apply variational quantum algorithms to machine learning. [Hint: problem-agnostic ansatzes]
  2. Discuss the differences between each quantum embedding method. Which method should be used in which situation? Are there any situations where more than one method can be applied?
  3. Discuss the differences of basic and strong entangler layers in terms of parameters, efficiency, expressivity, and trainability.
  4. Explain why the alternating layered ansatz seems to outperform the other architectures.
  5. Suppose we have a basic entangler layer of 3 qubits. Compute BEL(0)∣0⟩⊗3\mathrm{BEL}(\mathbf 0)|0\rangle^{\otimes3}.
  6. Suppose we have a basic entangler layer of 3 qubits. Compute BEL(π21)∣0⟩⊗3\mathrm{BEL}(\frac{\pi}{2}\mathbf 1)|0\rangle^{\otimes3}.
  7. Suppose we have a strong entangler layer of 3 qubits. Compute SEL(0)∣0⟩⊗3\mathrm{SEL}(\mathbf 0)|0\rangle^{\otimes3}.
  8. Suppose we have a strong entangler layer of 3 qubits. Compute SEL(π21)∣0⟩⊗3\mathrm{SEL}(\frac{\pi}{2}\mathbf 1)|0\rangle^{\otimes3}.
  • Answers to 1–4: see the ❓ boxes above (VQA, Quantum Embedding, Table 1, ALT); 5–8: see "Exercise answers 8.1.5–8.1.8"

2. Hybrid Classical-Quantum Machine Learning

Final Q7 — slides 14–15, 21–24

  • Prediction loss & its 3 challenges, SGD (why local optimum, update equation), hybrid models + which loss for which model, parameter shift rule (why it works / why it's needed / why irreversible), gradients of MSE/NLL/hinge. See Final - Instructor Hints.

Prediction Loss {Exam Q7}

  • Once an ansatz U(Θ)\mathbf U(\Theta) is established, we can translate an input data into an output quantum state w.r.t. the current parameters
  • Challenge 1: we estimate the ansatz's parameters to minimize the prediction loss (the difference between an output quantum state and a gold standard in classical computing)
  • Challenge 2: conversion from classical data to quantum state is usually noisy on NISQ hardware
  • Challenge 3: measurement of a quantum state depends on the observable (i.e. set of orthonormal projection axes)
  • Prediction loss: for observables {B1,…,BN}\{\mathbf B_1,\dots,\mathbf B_N\} and gold standard labels {t1,…,tN}\{t_1,\dots,t_N\}, the loss function is

L(Θ)=∑k=1Nf(Bk, U(Θ), tk)\boxed{L(\Theta) = \sum_{k=1}^{N} f\big(\mathbf B_k,\ \mathbf U(\Theta),\ t_k\big)}

  • Figure 9 (Quantum prediction): ∣ψinput⟩→U(Θ)→|\psi_{\text{input}}\rangle \to \mathbf U(\Theta) \to measure each qubit ⟨B1⟩,…,⟨B4⟩\langle\mathbf B_1\rangle,\dots,\langle\mathbf B_4\rangle (Prediction) ⟷ Prediction loss ⟷ t1,…,t4t_1,\dots,t_4 (Gold standard)

📝 Instructor's annotation: Title area: "Objective: Create a prediction model that yields the least prediction error as possible." → arrow "prediction error" → "loss function in ML". In the formula: U(Θ)\mathbf U(\Theta) labelled "prediction model"; tkt_k labelled "training data item at kk-th dim"; Bk\mathbf B_k labelled "expectation on each projection axis (usually Z)".

🎙️ In class (Nov 17-2, 07:00–09:38): Loss = difference between the model's output and the training data (gold standard). E.g. 4-class output vs gold (0,0,1,0)(0,0,1,0) — how to compare two vectors? Dot product / cosine similarity — "we do the same thing in the quantum algorithm."

🎙️ In class (Nov 17-2, 09:55–12:05): Measure qubit kk and compare with bit kk of the training data, bit by bit. B\mathbf B = projection basis (X, Y or Z); in most cases Z, because you want the expectation of being 0 or 1 (north/south pole), which compares directly with binary labels.

🎙️ In class (Nov 17-2, 13:14–15:45): Z-expectation is in [−1,1][-1,1]: positive → points to ∣0⟩|0\rangle, negative → ∣1⟩|1\rangle. MSE example: (⟨Z1⟩−0)2, (⟨Z2⟩−0)2, (⟨Z3⟩−1)2, (⟨Z4⟩−0)2(\langle Z_1\rangle-0)^2,\ (\langle Z_2\rangle-0)^2,\ (\langle Z_3\rangle-1)^2,\ (\langle Z_4\rangle-0)^2, then average. "Expectation means average of the measurement."

❓ Why do we need a loss function? It turns "how good is this θ?" into one number we can minimize. Without it, the optimizer has no direction.

❓ Why measure expectations ⟨Bk⟩\langle\mathbf B_k\rangle instead of single shots? A single measurement is random (0 or 1). The expectation (average over many shots) is a smooth, real number in [−1,1][-1,1] that changes continuously with θ → it can be compared with labels and differentiated.

❓ Why Challenge 3? The same state gives different numbers on X, Y or Z. Choosing the observable is part of the model design — we choose Z so outputs line up with ∣0⟩|0\rangle/∣1⟩|1\rangle labels.

💡 Analogy: Prediction loss is the score on a practice exam: model answers vs answer key (tkt_k). Training = keep studying (adjusting θ) to lower the number of points lost.

Parameter Optimization (SGD) {Exam Q7}

  • We can approximate the parameters Θ\Theta such that the prediction loss LL is minimized at the optimal parameters Θ∗\Theta^*
  • Local optimum is guaranteed (not global)
  • Stochastic gradient descent (SGD):
    1. Initialize the parameters Θ(0)\Theta^{(0)} with randomization

Θ(0)∼Puniform(0,2π)\Theta^{(0)} \sim P_{\text{uniform}}(0,2\pi)

  1. Update the parameters w.r.t. the gradient (slope) at the current point — the update equation:

Θ(k+1)=Θ(k)−η∂L∂Θ∣Θ=Θ(k)\boxed{\Theta^{(k+1)} = \Theta^{(k)} - \eta\left.\frac{\partial L}{\partial\Theta}\right|_{\Theta=\Theta^{(k)}}}

 - where the **learning rate** $\eta$ is a small constant, e.g. $10^{-4}$

3. Repeat step 2 until the parameters converge (i.e. the gradient is close to zero)

  • Figure 10: loss curve LL vs Θ\Theta; green arrows walk down the slope; "The gradient ∂L/∂Θ\partial L/\partial\Theta decays as we approach the minimum" → Optimal Θ∗\Theta^*

📝 Instructor's annotation: In red next to the figure: "Main challenge: How can we find the gradient ∂L∂Θ\frac{\partial L}{\partial\Theta}?" (answered later by the parameter shift rule).

🎙️ In class (Nov 17-2, 17:51–18:12): He calls SGD the "hill descending algorithm".

🎙️ In class (Nov 17-2, 18:19–23:11): Start at a random θ; compute the gradient (slope) = Δy/Δx\Delta y/\Delta x = ∂L/∂θ\partial L/\partial\theta. The slope tells you two things: direction and step size. Big slope → big step; as you near the minimum, slope shrinks → smaller steps.

🎙️ In class (Nov 17-2, 23:25–25:01): At G1G_1 the slope is negative but you move right → multiply by −1-1 (flip the sign). Slope can be enormous → scale down with learning rate η\eta ("ETA — not estimated time of arrival!"), e.g. 10−410^{-4}.

🎙️ In class (Nov 17-2, 25:35–26:20): At the minimum the slope is zero → the update term is zero → θ(k+1)=θ(k)\theta^{(k+1)}=\theta^{(k)} → you stop.

🎙️ In class (Nov 17-2, 26:31–27:16): Everything is fine classically, "until you realize — what if I have an ansatz? How could I compute that gradient? A gradient of a quantum gate is difficult already; how about a whole circuit?" → there is a trick (PSR).

❓ Why the minus sign? The gradient points uphill (direction of increasing loss). We want to go downhill, so we step in the opposite direction.

❓ Why a small learning rate? A huge step can overshoot the valley and bounce around/diverge. Small η\eta = careful steps.

❓ Why is only a local optimum guaranteed? (Ex 8.2.2, hint: mountain range) SGD only looks at the local slope. In a mountain range with many valleys, walking downhill gets you to the bottom of whichever valley you started in — gradient = 0 there, so it stops, even if a deeper valley exists elsewhere. Random initialization decides which valley.

❓ Why initialize from U(0,2π)U(0,2\pi)? Parameters are rotation angles, periodic with period 2π2\pi — that range covers every possible angle once.

💡 Analogy: Walking down Doi Inthanon in thick fog. You can only feel the ground slope under your feet; step downhill, smaller steps as it flattens. You'll reach a valley — maybe not the lowest one in Thailand.

Projection-based Loss Functions

  • Recall CH4: suppose ∣ψ⟩=a∣0⟩+b∣1⟩|\psi\rangle = a|0\rangle+b|1\rangle. Projections on popular observables are:

⟨X(ψ)⟩=∣a+b∣2−∣a−b∣2⟨Y(ψ)⟩=∣a+bi∣2−∣a−bi∣2⟨Z(ψ)⟩=∣a∣2−∣b∣2⟨I(ψ)⟩=∣a∣2+∣b∣2=1\boxed{\begin{aligned}\langle\mathbf X^{(\psi)}\rangle &= |a+b|^2-|a-b|^2 \\ \langle\mathbf Y^{(\psi)}\rangle &= |a+bi|^2-|a-bi|^2 \\ \langle\mathbf Z^{(\psi)}\rangle &= |a|^2-|b|^2 \\ \langle\mathbf I^{(\psi)}\rangle &= |a|^2+|b|^2 = 1\end{aligned}}

  • Projection on Z is the most popular because it points towards ∣0⟩|0\rangle (positive value) and ∣1⟩|1\rangle (negative value)
  • Our ansatz makes a prediction by taking ∣0⟩⊗N|0\rangle^{\otimes N} as an input:

∣ψ⟩=U(Θ)∣0⟩⊗N|\psi\rangle = \mathbf U(\Theta)|0\rangle^{\otimes N}

  • Letting B∈{X,Y,Z}\mathbf B\in\{\mathbf X,\mathbf Y,\mathbf Z\} be a basis, projection on B\mathbf B is

⟨B(ψ)⟩=⟨ψ∣B∣ψ⟩=[⟨0∣⊗NU∗(Θ)]B[U(Θ)∣0⟩⊗N]\boxed{\langle\mathbf B^{(\psi)}\rangle = \langle\psi|\mathbf B|\psi\rangle = \Big[\langle0|^{\otimes N}\mathbf U^*(\Theta)\Big]\mathbf B\Big[\mathbf U(\Theta)|0\rangle^{\otimes N}\Big]}

  • or in abbreviation

⟨B(ψ)⟩=⟨0∣U∗(Θ) B U(Θ)∣0⟩\langle\mathbf B^{(\psi)}\rangle = \langle0|\mathbf U^*(\Theta)\,\mathbf B\,\mathbf U(\Theta)|0\rangle

📝 Instructor's annotation: He highlighted "Projection on Z is the most popular…". In the last formula he highlighted ⟨0∣U∗(Θ)\langle0|\mathbf U^*(\Theta) in green and labelled it ⟨ψ∣\langle\psi|, and U(Θ)∣0⟩\mathbf U(\Theta)|0\rangle in orange labelled ∣ψ⟩|\psi\rangle.

🎙️ In class (Nov 17-2, 27:26–31:00): "Don't be scared by the math" — the point is projection on Z gives values for 0/1. Expectation = state, times B\mathbf B, times the bra of the state. The bra of U∣0⟩\mathbf U|0\rangle is ⟨0∣U∗\langle0|\mathbf U^* (adjoint, reverse the order). We drop the ⊗N\otimes N for abbreviation.

❓ Why U∗\mathbf U^* on the left? ⟨ψ∣=(∣ψ⟩)†=(U∣0⟩)†=⟨0∣U†\langle\psi| = (|\psi\rangle)^\dagger = (\mathbf U|0\rangle)^\dagger = \langle0|\mathbf U^\dagger — taking the adjoint reverses the order and conjugate-transposes U\mathbf U.

Related

Projection-based Loss Functions (cont'd)

  • We define our loss function as projection on the basis Bk\mathbf B_k:

f(Bk,U(Θ),tk)=Δ(⟨Bk(U(Θ)∣0⟩)⟩, tk)=Δ(⟨0∣U∗(Θ) Bk U(Θ)∣0⟩, tk)\boxed{f(\mathbf B_k,\mathbf U(\Theta),t_k) = \Delta\Big(\big\langle\mathbf B_k^{(\mathbf U(\Theta)|0\rangle)}\big\rangle,\ t_k\Big) = \Delta\big(\langle0|\mathbf U^*(\Theta)\,\mathbf B_k\,\mathbf U(\Theta)|0\rangle,\ t_k\big)}

  • where Δ(bk,tk)\Delta(b_k,t_k) is a distance function between the expected measurement bkb_k and the gold standard label tkt_k
  • Since the expectation bk∈[−1,1]b_k\in[-1,1], each gold-standard label is tk∈{−1,1}t_k\in\{-1,1\}
  • Criteria for prediction loss:
    • Faithfulness: the minimum of prediction loss should correspond to the solution of the problem
    • Efficiency: we should be able to efficiently estimate the prediction loss by quantum measurement, perhaps accompanied with classical postprocessing
    • Meaningfulness: smaller prediction loss should indicate better quality of the solution
    • Trainability: the prediction loss should be possible to efficiently optimize the parameters ⇒ preferably differentiable by the parameters Θ\Theta

📝 Instructor's annotation: Arrow to the expectation: "bkb_k: expected measurement". Highlighted "Δ(bk,tk)\Delta(b_k,t_k) is a distance function" and "differentiable".

🎙️ In class (Nov 17-2, 31:24–32:56): bkb_k = expected measurement on the kk-th qubit; tkt_k = kk-th bit of training data; measure the difference bit by bit.

🎙️ In class (Nov 17-2, 33:28–33:56): "In most cases we care about meaningfulness — we need to interpret the meaning of such difference."

❓ Why must the loss be differentiable? SGD needs ∂L/∂Θ\partial L/\partial\Theta. No derivative → no direction → no training.

❓ Why tk∈{−1,1}t_k\in\{-1,1\} and not {0,1}\{0,1\}? Because ⟨Z⟩\langle\mathbf Z\rangle lives in [−1,1][-1,1]: +1=∣0⟩+1=|0\rangle, −1=∣1⟩-1=|1\rangle. Labels must live on the same scale as predictions.

  • Mean squared error (MSE) measures the squared differences between each expected measurement bkb_k and the corresponding gold standard label tkt_k

ΔMSE=1N∑k=1N(tk−bk)2\boxed{\Delta_{\text{MSE}} = \frac1N\sum_{k=1}^{N}(t_k-b_k)^2}

  • The gradient (slope) of MSE is derived by

∂∂ΘΔMSE=∂∂Θ1N∑k=1N(tk−bk)2=−2∑k=1N(tk−bk)∂bk∂Θ\frac{\partial}{\partial\Theta}\Delta_{\text{MSE}} = \frac{\partial}{\partial\Theta}\frac1N\sum_{k=1}^{N}(t_k-b_k)^2 = -2\sum_{k=1}^{N}(t_k-b_k)\frac{\partial b_k}{\partial\Theta}

  • (slide drops the constant 1N\frac1N in the last line; it is absorbed by the learning rate)
  • Figure 11: MSE measures the differences between prediction (green line) and the gold standard labels (yellow dots); these vertical distances are counted as loss

🎙️ In class (Nov 17-2, 34:16–36:58): Differences can be positive or negative (point above/below the line) → "neutralize the sign by squaring", then average. "Easy peasy lemon squeezy."

🎙️ In class (Nov 17-2, 38:33–39:02): But we're still stuck at ∂bk/∂Θ\partial b_k/\partial\Theta — "How can we compute it? … It's much easier than you think. Wait for it."

❓ Why square? So positive and negative errors don't cancel, and big errors are punished more. Squaring is also smooth → differentiable.

  • Negative Log-Likelihood (NLL) measures the likelihood of the gold-standard labels according to the current model

ΔNLL=−1N∑k=1Nlog⁡(ϖM(bk))\boxed{\Delta_{\text{NLL}} = -\frac1N\sum_{k=1}^{N}\log\big(\varpi_M(b_k)\big)}

  • Softmax distribution for an MM-dim vector:

ϖM(bk)=exp⁡(bk)∑j=1Mexp⁡(bj)\boxed{\varpi_M(b_k) = \frac{\exp(b_k)}{\sum_{j=1}^{M}\exp(b_j)}}

  • The gradient of NLL is derived by

∂∂ΘΔNLL=−∂∂Θ1N∑k=1Nlog⁡(ϖM(bk))=1N∑k=1N(ϖM(bk)−tk)∂bk∂Θ\frac{\partial}{\partial\Theta}\Delta_{\text{NLL}} = -\frac{\partial}{\partial\Theta}\frac1N\sum_{k=1}^{N}\log\big(\varpi_M(b_k)\big) = \frac1N\sum_{k=1}^{N}\big(\varpi_M(b_k)-t_k\big)\frac{\partial b_k}{\partial\Theta}

  • Figure 12: Prediction bk∈[−1,1]b_k\in[-1,1] → Softmax ∈[0,1]\in[0,1] ⟷ Gold standard tkt_k (one-hot); NLL measures the likelihood of the gold-standard label (green dot) according to the model (yellow dot)

📝 Instructor's annotation: "Used when differences between data items and target values are smaller than 1."

🎙️ In class (Nov 17-2, 39:08–40:27): If the model outputs [−1,1][-1,1], the max difference is 2 → MSE fine. If outputs are only in [0,1][0,1], differences are <1<1 → squaring makes them even tinier → "we cannot use MSE anymore". MSE is for large differences; NLL for small ones. NLL = care only about the correct class: take its probability, log, negate.

🎙️ In class (Nov 17-2, 41:44–42:07): "Do we really have to remember [the gradient]? No. The final exam is all about why questions."

❓ Why softmax? It turns any real vector into a probability distribution (all positive via exp⁡\exp, sums to 1) — so we can talk about "probability of the correct class". (Ex 8.2.5: yes, works for any real vector, because exp⁡>0\exp>0 and we divide by the total.)

❓ Why log and negative? Log turns tiny probabilities into large penalties (amplifies small differences); the minus makes "high probability of correct class" = low loss, so we can minimize.

  • Hinge loss (HL) measures the sign differences between each expected measurement bkb_k and the corresponding gold standard label tkt_k

ΔHL=1N∑k=1N{0sgn⁡tk=sgn⁡bk1−tkbkotherwise\boxed{\Delta_{\text{HL}} = \frac1N\sum_{k=1}^{N}\begin{cases}0 & \operatorname{sgn}t_k=\operatorname{sgn}b_k\\ 1-t_kb_k & \text{otherwise}\end{cases}}

  • The gradient of HL is derived by (only mispredicted items contribute)

∂∂ΘΔHL=∂∂Θ1N∑k=1Ndiff-signs(1−tkbk)=−1N∑k=1Ndiff-signstk∂bk∂Θ\frac{\partial}{\partial\Theta}\Delta_{\text{HL}} = \frac{\partial}{\partial\Theta}\frac1N\sum_{k=1}^{N_{\text{diff-signs}}}(1-t_kb_k) = -\frac1N\sum_{k=1}^{N_{\text{diff-signs}}}t_k\frac{\partial b_k}{\partial\Theta}

  • Figure 13: hinge loss measures the errors of the class boundary (green line) vs gold labels (yellow and blue dots); crossed dots = sign mispredictions, counted as loss

📝 Instructor's annotation: "Used when we emphasize only the number of mispredictions."

🎙️ In class (Nov 17-2, 42:31–43:43): Hinge loss ≈ count of mispredictions — in the figure, 5 points on the wrong side → loss 5.

🎙️ In class (Nov 17-2, 43:59–44:42): Why "hinge": the green line is like a door hinge; rotate the door (model) and count things on the wrong side of the door.

🎙️ In class (Nov 17-2, 44:51–46:12): Gradient is computed only from the mispredicted points. "And we're still stuck again… what is the gradient of the expected measurement?"

❓ Why does a correct prediction contribute 0? If signs match, the point is on the right side of the boundary; hinge loss only cares about classification errors, not how close the value is.

❓ NLL vs hinge (Ex 8.2.6): NLL uses all items' probabilities (smooth, probabilistic); hinge uses only misclassified items (sign-based, margin-style). NLL for classification with confidence; hinge when only the number of mistakes matters (SVM).

LossMeasuresUse whenClassic model
MSEsquared distancelarge differences, regressionLinear regression
NLL−log prob. of correct classsmall differences (< 1), classificationLogistic regression
Hingesign mispredictionsonly #mistakes mattersSVM

Hybrid Classical-Quantum Model {Exam Q7}

  • Hybrid model is a variational algorithm whose parameters are estimated classically
    • Linear regression: learn a linear trend of the dataset; i.e. linear relationship between the input features and the output scalar values — Loss: MSE
    • Logistic regression: learn to put labels from the input features using the logistic function — Loss: NLL
    • Support vector machine: learn to draw a class boundary with a non-linear function (kernel) — Loss: Hinge
  • Figure 14 (Classical ML): straight trend line; S-shaped logistic curve separating 0 and 1; a closed (circular) boundary around one class

🎙️ In class (Nov 17-2, 46:30–47:58): Linear regression = straight line predicting the trend (going up or down?). Logistic regression = the most basic binary classification model (0 below, 1 above). SVM = draw a boundary between classes; the line can be non-linear.

❓ Why is it called "hybrid"? The quantum circuit computes the prediction bkb_k; the classical computer computes the loss and the parameter updates. Neither does the whole job alone.

❓ Why pair each model with that loss? Regression predicts a continuous value → distance (MSE). Logistic regression predicts a probability → likelihood (NLL). SVM cares about which side of the boundary → sign errors (hinge).

Parameter Shift Rule (PSR) {Exam Q7}

  • Challenge: how can we compute

∂bk∂Θ=∂∂Θ⟨0∣U∗(Θ) Bk U(Θ)∣0⟩\frac{\partial b_k}{\partial\Theta} = \frac{\partial}{\partial\Theta}\langle0|\mathbf U^*(\Theta)\,\mathbf B_k\,\mathbf U(\Theta)|0\rangle

  • First, assume the ansatz U\mathbf U can be rewritten as

U(Θ)=cis⁡(−Θ2P)=exp⁡(−Θ2iP)\boxed{\mathbf U(\Theta) = \operatorname{cis}\Big(-\frac{\Theta}{2}\mathbf P\Big) = \exp\Big(-\frac{\Theta}{2}i\mathbf P\Big)}

  • where P\mathbf P is the Hermitian generator of U\mathbf U
  • The gradients of U\mathbf U and U∗\mathbf U^* are:

∂∂ΘU(Θ)=−i2PU(Θ)=−i2U(Θ)P,∂∂ΘU∗(Θ)=i2PU∗(Θ)=i2U∗(Θ)P\frac{\partial}{\partial\Theta}\mathbf U(\Theta) = -\frac i2\mathbf P\mathbf U(\Theta) = -\frac i2\mathbf U(\Theta)\mathbf P, \qquad \frac{\partial}{\partial\Theta}\mathbf U^*(\Theta) = \frac i2\mathbf P\mathbf U^*(\Theta) = \frac i2\mathbf U^*(\Theta)\mathbf P

  • Now compute the gradient (product rule):
∂bk∂Θ=∂∂Θ⟨0∣U∗(Θ)BkU(Θ)∣0⟩=⟨0∣(∂∂ΘU∗(Θ)BkU(Θ))∣0⟩=⟨0∣i2(U∗(Θ)PBkU(Θ)−U∗(Θ)BkPU(Θ))∣0⟩=⟨0∣(i2U∗(Θ)[P,Bk]U(Θ))∣0⟩\begin{aligned} \frac{\partial b_k}{\partial\Theta} &= \frac{\partial}{\partial\Theta}\langle0|\mathbf U^*(\Theta)\mathbf B_k\mathbf U(\Theta)|0\rangle \\ &= \langle0|\Big(\frac{\partial}{\partial\Theta}\mathbf U^*(\Theta)\mathbf B_k\mathbf U(\Theta)\Big)|0\rangle \\ &= \langle0|\frac i2\Big(\mathbf U^*(\Theta)\mathbf P\mathbf B_k\mathbf U(\Theta) - \mathbf U^*(\Theta)\mathbf B_k\mathbf P\mathbf U(\Theta)\Big)|0\rangle \\ &= \langle0|\Big(\frac i2\mathbf U^*(\Theta)[\mathbf P,\mathbf B_k]\mathbf U(\Theta)\Big)|0\rangle \end{aligned}
  • Commutator: [P,Bk]=PBk−BkP[\mathbf P,\mathbf B_k] = \mathbf P\mathbf B_k - \mathbf B_k\mathbf P
  • Since Bk\mathbf B_k is a Pauli operator, the identity is:

[P,Bk]=−i(U∗(π2)BkU(π2)−U∗(−π2)BkU(−π2))\boxed{[\mathbf P,\mathbf B_k] = -i\Big(\mathbf U^*(\tfrac{\pi}{2})\mathbf B_k\mathbf U(\tfrac{\pi}{2}) - \mathbf U^*(-\tfrac{\pi}{2})\mathbf B_k\mathbf U(-\tfrac{\pi}{2})\Big)}

📝 Instructor's annotation: Boxed the Challenge in red; labelled ⟨0∣U∗(Θ)\langle0|\mathbf U^*(\Theta) as ⟨ψ∣\langle\psi| and U(Θ)∣0⟩\mathbf U(\Theta)|0\rangle as ∣ψ⟩|\psi\rangle. Next to U(Θ)=cis⁡(−Θ2P)\mathbf U(\Theta)=\operatorname{cis}(-\frac\Theta2\mathbf P) wrote =exp⁡(−Θ2iP)=\exp(-\frac{\Theta}{2}i\mathbf P). Highlighted ∂∂ΘU=−i2PU\frac{\partial}{\partial\Theta}\mathbf U = -\frac i2\mathbf P\mathbf U. Margin note for the product rule: d(uv)=u dv+v dud(uv)=u\,dv+v\,du. Highlighted the −U∗BkPU-\mathbf U^*\mathbf B_k\mathbf P\mathbf U term, labelled [P,Bk][\mathbf P,\mathbf B_k] "commutator operator" =PBk−BkP= \mathbf P\mathbf B_k-\mathbf B_k\mathbf P.

🎙️ In class (Nov 17-2, 48:07–49:28): "The most important part is to compute the gradient of the expected measurement, which looks like an Einstein equation but it's not, believe me… if you understand this, you can understand quantum neural networks as well."

❓ Why can't we differentiate the circuit normally? On real hardware we can't see the matrix or the state — we only get measurement statistics. Classical backprop needs internal values; a QPU hides them. So we need a gradient formula that uses only measurements.

❓ Why does the Hermitian generator appear? Every rotation gate is e−iθ2Pe^{-i\frac\theta2\mathbf P} with P\mathbf P a Pauli (Hermitian) matrix — e.g. RX(θ)=e−iθ2X\mathbf{RX}(\theta)=e^{-i\frac\theta2\mathbf X}. Differentiating an exponential just pulls down −i2P-\frac i2\mathbf P — the same link between gates and Hamiltonians as in Chapter 7.

Related

Parameter Shift Rule (cont'd) {Exam Q7}

  • We then substitute this identity into the gradient and obtain
∂bk∂Θ=12⟨0∣(U∗(Θ+π2)BkU(Θ+π2))∣0⟩−12⟨0∣(U∗(Θ−π2)BkU(Θ−π2))∣0⟩\begin{aligned} \frac{\partial b_k}{\partial\Theta} &= \frac12\langle0|\Big(\mathbf U^*(\Theta+\tfrac\pi2)\mathbf B_k\mathbf U(\Theta+\tfrac\pi2)\Big)|0\rangle - \frac12\langle0|\Big(\mathbf U^*(\Theta-\tfrac\pi2)\mathbf B_k\mathbf U(\Theta-\tfrac\pi2)\Big)|0\rangle \end{aligned}

∂bk∂Θ=12(bk(Θ+π2)−bk(Θ−π2))(Parameter Shift Rule)\boxed{\frac{\partial b_k}{\partial\Theta} = \frac12\Big(b_k(\Theta+\tfrac\pi2) - b_k(\Theta-\tfrac\pi2)\Big)} \quad\text{(Parameter Shift Rule)}

  • where the expected measurement bk(Θ)b_k(\Theta) is

bk(Θ)=⟨0∣(U∗(Θ)BkU(Θ))∣0⟩\boxed{b_k(\Theta) = \langle0|\big(\mathbf U^*(\Theta)\mathbf B_k\mathbf U(\Theta)\big)|0\rangle}

  • Parameter shift rule is irreversible due to projection-based measurement

📝 Instructor's annotation: Green box around the whole derivation with stars, big green "Parameter Shift Rule (PSR)". Highlighted bk(Θ)b_k(\Theta) definition in green. Red-highlighted "projection-based measurement" and wrote bk=⟨B(ψ)⟩b_k = \langle\mathbf B^{(\psi)}\rangle.

🎙️ In class (Nov 17-2, 49:32–51:12): ⭐ The recipe: at the current θ\theta, add 90° (π2\frac\pi2), run the circuit, measure the expectation. Then subtract 90°, rerun, measure. Subtract the two expectations and halve → that's the gradient.

🎙️ In class (Nov 17-2, 51:12–52:21): "Instead of actually computing the gradient, you just shift the phase by 90° to negative and positive… you don't really have to differentiate any matrix at all."

🎙️ In class (Nov 17-2, 52:29–52:51): This is (student) Tun's senior project — he modified the PSR.

🎙️ In class (Nov 17-2, 53:04–55:13): Classical ML must differentiate all kinds of layers; quantum doesn't. "Training a model is not that difficult: you just run your algorithm twice — once at x+90°x+90°, once at x−90°x-90°."

🎙️ In class (Nov 17-2, 55:24–56:19): The proof takes ~2 A4 pages in his book, "but at the end of the day you end up with this." Because the parameters are phases, it's called phase shift / parameter shift rule.

❓ Why does PSR work? Rotation gates are exponentials of Pauli generators (P2=I\mathbf P^2=\mathbf I, eigenvalues ±1\pm1), so bk(θ)b_k(\theta) is a pure sinusoid Acos⁡θ+Bsin⁡θ+CA\cos\theta+B\sin\theta+C. For a sinusoid, the exact derivative is 12[b(θ+π2)−b(θ−π2)]\frac12[b(\theta+\frac\pi2)-b(\theta-\frac\pi2)] — an exact formula, not a finite-difference approximation.

❓ Why is PSR important / why do we need it? It gives the exact gradient using only two extra runs of the same circuit on the quantum hardware — no matrix differentiation, no access to the hidden state. This is what makes SGD (and backprop) possible on quantum circuits.

❓ Why shift by ±π2\pm\frac\pi2 (not a tiny hh like finite differences)? A tiny shift would make the two measurements almost equal; with shot noise the difference would be swamped by noise. A big shift of π2\frac\pi2 gives a large, measurable difference, and is still exact.

❓ Why is PSR irreversible? (Ex 8.2.8) Each bkb_k is obtained by projection-based measurement, which collapses (decoheres) the state. You get a number but destroy the state — you can't run it backwards; to evaluate again you must re-prepare and re-run the circuit.

💡 Analogy: You want to know how steep a hill is where you stand, but you're blindfolded (can't see the state). Ask a friend to stand one big step east and one big step west and shout their heights. Half the difference tells you the slope — no need to see the map.

  • Substitute PSR for ∂bk∂Θ\frac{\partial b_k}{\partial\Theta} in each loss gradient (constants absorbed into η\eta):
  • Gradient of Mean Squared Error:

∂∂ΘΔMSE(Θ)=∑k=1N(bk(Θ)−tk)(bk(Θ+π2)−bk(Θ−π2))\boxed{\frac{\partial}{\partial\Theta}\Delta_{\text{MSE}}(\Theta) = \sum_{k=1}^{N}\big(b_k(\Theta)-t_k\big)\Big(b_k(\Theta+\tfrac\pi2)-b_k(\Theta-\tfrac\pi2)\Big)}

  • Gradient of Negative Log-Likelihood:

∂∂ΘΔNLL(Θ)=∑k=1N(ϖ(bk(Θ))−tk)(bk(Θ+π2)−bk(Θ−π2))\boxed{\frac{\partial}{\partial\Theta}\Delta_{\text{NLL}}(\Theta) = \sum_{k=1}^{N}\big(\varpi(b_k(\Theta))-t_k\big)\Big(b_k(\Theta+\tfrac\pi2)-b_k(\Theta-\tfrac\pi2)\Big)}

  • Gradient of Hinge Loss:

∂∂ΘΔHL(Θ)=−12N∑k=1Ndiff-signstk(bk(Θ+π2)−bk(Θ−π2))\boxed{\frac{\partial}{\partial\Theta}\Delta_{\text{HL}}(\Theta) = -\frac{1}{2N}\sum_{k=1}^{N_{\text{diff-signs}}}t_k\Big(b_k(\Theta+\tfrac\pi2)-b_k(\Theta-\tfrac\pi2)\Big)}

🎙️ In class (Nov 17-2, 56:44–57:02): "From here you can compute the gradient of MSE, NLL and hinge loss by substituting the gradient with the PSR. That's all. You can implement it yourself, but I don't recommend that" (PennyLane/PyTorch do it).

❓ Why is every gradient "(error term) × (PSR difference)"? Chain rule: ∂L∂Θ=∂L∂bk⋅∂bk∂Θ\frac{\partial L}{\partial\Theta}=\frac{\partial L}{\partial b_k}\cdot\frac{\partial b_k}{\partial\Theta}. The first factor is classical (depends on the loss), the second is quantum (PSR). That's the hybrid split.

Parameter Optimization in PennyLane

import torch as T
from torch import nn as N
from torch import optim as O
 
wires = ['w1', 'w2', 'w3', 'w4']
dev = qml.device('default.qubit', wires=wires)
 
@qml.qnode(dev)
def circuit(inputs, params):                          # Quantum circuit
    qml.AngleEmbedding(inputs, wires=wires)           # Encode each input as a quantum state
    qml.BasicEntanglerLayers(params, wires=wires)     # Ansatz
    return [qml.expval(qml.PauliZ(wires=w)) for w in wires]  # Each dimension is in [-1, +1]
 
class HybridModel(N.Module):                          # Hybrid classical-quantum model
    def __init__(self):
        super().__init__()
        params_shapes = {"params": (3, 4)}            # Define the shape of parameters `params`
        self.circuit_layer = qml.qnn.TorchLayer(circuit, params_shapes)
        self.softmax = N.Softmax(dim=0)
    def forward(self, inputs):
        outvec = self.circuit_layer(inputs)
        outvec = self.softmax(outvec)
        return outvec

Parameter Optimization in PennyLane (cont'd)

invec = T.tensor([0.0, 0.0, 0.0, 0.0])        # Input vector
goldstd = T.tensor([0.5, 0.0, 0.5, 0.0])      # Gold-standard output vector
hybrid_model = HybridModel()                   # Our ansatz
loss_fn = N.MSELoss()                          # The loss function
opt = O.Adam(hybrid_model.parameters(), lr=0.1)  # SGD algorithm with adaptive gradients
no_iters = 100                                 # Number of iterations
 
# Make prediction before training
outvec = hybrid_model(invec)
print(f'Before: {outvec}')
 
# Training loop
for i in range(no_iters):
    outvec = hybrid_model(invec)               # Make prediction
    loss = loss_fn(outvec, goldstd)            # Compute prediction loss
    opt.zero_grad()                            # Re-estimate the parameters
    loss.backward()
    opt.step()
 
# Make prediction after training
outvec = hybrid_model(invec)
print(f'After: {outvec}')

🎙️ In class (Nov 17-2, 57:15–57:28): "This piece of code is runnable — I trained the model myself."

Exercise 8.2: Hybrid Classical-Quantum Machine Learning

  1. What is prediction loss? Explain its relevance to the VQA.
  2. Discuss why the stochastic gradient descent algorithm is guaranteed to achieve only a local optimum, not a global one. [Hint: Think about a mountain range.]
  3. Explain how the parameter shift rule can be used to compute the gradient in the SGD algorithm.
  4. Discuss the differences between three kinds of prediction loss: MSE, NLL, and HL. In which situation can each prediction loss be employed?
  5. Investigate if the softmax distribution ϖ\varpi can be used to convert any arbitrary real-valued vector to a probability distribution. Explain your rationale.
  6. Discuss the differences between the negative log-likelihood and the hinge loss. Analyze how they are computed.
  7. Review what and how these models learn from the dataset: linear regression, logistic regression, and support vector machine.
  8. Explain why the parameter shift rule is irreversible.
  • Answers: see the ❓ boxes in Prediction Loss, SGD, NLL, Hinge, Hybrid Model and PSR sections

Coding Challenge 8.2: Hybrid Classical-Quantum Machine Learning (cont'd)

  • Implement the following hybrid models using PennyLane. Generate your own randomized datasets for training and testing.
    1. Linear regression for 10-dimensional data (use MSE):

y=θ0+∑k=110θkxky = \theta_0 + \sum_{k=1}^{10}\theta_kx_k

  1. Logistic regression for 10-dimensional data (use NLL):

y=σ(θ0+∑k=110θkxk)y = \sigma\Big(\theta_0+\sum_{k=1}^{10}\theta_kx_k\Big)

  • where each xkx_k is the kk-th item of the data point x\mathbf x, and θk\theta_k is the kk-th parameter

📝 Instructor's annotation: A big green sweeping line across the bottom of the slide with the word "Final" — marks the boundary of final-exam material for this part (right after this, he cancelled the Quantum Kernel/SVM section).


3. Quantum Kernel Methods

Not in the final


🎙️ In class (Nov 17, 13:05): "You can cancel out the support vector machine right here. You can cancel it. I'm not going to take it to the final exam." This whole section was skipped in class. Kept here for completeness.

Class Separation and Kernel Functions

  • Class separation refers to how distinct different classes within data are, measured by a distance function
  • Kernel function k(x,x′)k(\mathbf x,\mathbf x') measures such distance between two data items x\mathbf x and x′\mathbf x'; its computation can be simplified as a feature map Φ:RN↦RV\Phi:\mathbb R^N\mapsto\mathbb R^V, where

k(x,x′)=⟨Φ(x),Φ(x′)⟩\boxed{k(\mathbf x,\mathbf x') = \langle\Phi(\mathbf x),\Phi(\mathbf x')\rangle}

  • VV is the number of features, and ⟨u,v⟩\langle\mathbf u,\mathbf v\rangle is the inner product of u\mathbf u and v\mathbf v
  • Limitation: time complexity is O(N2VM)O(N^2VM), where NN is the number of input features and MM is the number of training iterations
  • Figure 15: kernel function — x′x' close to xx (small kk distance, same circle), x′′x'' far away
  • Figure 16: the feature map converts a space of input data with a non-linear class boundary (circle) into an equivalent feature space with a linear class boundary (straight line)

💡 Analogy: Mixed red and green beads lying flat on a table, red ones in a ring around green ones — no straight line separates them. Toss them up (feature map adds a "height" dimension): green fly higher; now a flat sheet separates them.

Support Vector Machine

  • Support vectors are the data points nearest to the class boundary, and the margin is the total distance between these support vectors and the class boundary
  • Support vector machines (SVMs) are supervised max-margin models that learn classification and regression, once each data point xk\mathbf x_k is mapped to the feature space with linear class boundary

y^k=w⊤Φ(xk)+b\hat y_k = \mathbf w^\top\Phi(\mathbf x_k)+b

  • where Φ\Phi is a feature map function, and w\mathbf w are model parameters
  • The loss function of SVMs is

L(w)=∣w∣22+α ΔHL(y,y^)\boxed{L(\mathbf w) = |\mathbf w|_2^2 + \alpha\,\Delta_{\text{HL}}(\mathbf y,\hat{\mathbf y})}

  • where hyperparameter α\alpha determines the trade-off between margin size (0≤α<10\le\alpha<1) and more strict prediction (α>1\alpha>1)
  • Figure 17: black boundary line, two dashed green margin lines through the support vectors (circled), "margin" bracket

Quantum Kernel Functions

  • We can treat a feature map as a VQA:

UΦ(x)=∏k=1MH⊗VΛ(x)\mathbf U_\Phi(\mathbf x) = \prod_{k=1}^{M}\mathbf H^{\otimes V}\Lambda(\mathbf x)

  • where the unitary operator Λ(x)\Lambda(\mathbf x) is an angular embedding operator

Λ(x)=⨂s=1VRZ(ϕs(x))\Lambda(\mathbf x) = \bigotimes_{s=1}^{V}\mathbf{RZ}(\phi_s(\mathbf x))

  • and each ϕs(x)\phi_s(\mathbf x) is the ss-th feature extraction function
  • Observe that UΦ(x)\mathbf U_\Phi(\mathbf x) is untrainable because each xk\mathbf x_k is a constant data point
  • We then assemble a quantum SVM by incorporating UΦ\mathbf U_\Phi with an entangler layer:

UQSVM(x)=MultiBEL(ΘL×V) UΦ(x)\mathbf U_{\text{QSVM}}(\mathbf x) = \mathrm{MultiBEL}(\Theta_{L\times V})\,\mathbf U_\Phi(\mathbf x)

  • We compute the measurement operator My\mathbf M_y for the gold standard by

My=∣0⟩⊗V⟨0∣⊗V\mathbf M_y = |0\rangle^{\otimes V}\langle0|^{\otimes V}

  • which means we will make measurement only on the first qubit
  • Probability of outcome yy is therefore

p(y∣x)=⟨UQSVM∗(x) ∣ My ∣ UQSVM(x)⟩p(y|\mathbf x) = \big\langle\mathbf U^*_{\text{QSVM}}(\mathbf x)\,|\,\mathbf M_y\,|\,\mathbf U_{\text{QSVM}}(\mathbf x)\big\rangle

Quantum Support Vector Machine

  • Figure 18: ∣0⟩⊗4|0\rangle^{\otimes4} → [for i=1i=1 to MM: H\mathbf H on all → Λi(x)\Lambda_i(\mathbf x) → H\mathbf H → Λi(x)\Lambda_i(\mathbf x)] = UΦ(x)\mathbf U_\Phi(\mathbf x) (untrainable, fed by training data xk\mathbf x_k) → MultiBEL with ΘL×N\Theta_{L\times N} (trainable, fed by parameter optimization) → measure ⟨My⟩\langle\mathbf M_y\rangle → Hinge loss vs yk∈{+1,−1}y_k\in\{+1,-1\}
  • Time complexity for quantum SVM is O((log⁡N)2VM)O((\log N)^2VM), where NN is the number of input features, VV is the dimension of feature space, and MM is the number of training iterations (vs classical O(N2VM)O(N^2VM))

Quantum SVM in PennyLane/1

from sklearn.svm import SVC
from sklearn.metrics import accuracy_score
 
no_qubits = 4
wires = ['x1', 'x2', 'x3', 'x4']
dev = qml.device('lightning.qubit', wires=wires)
 
########################################
# Dataset Preparation
########################################
def prepare_dataset(no_training, no_testing):
    # Non-linear regression: y = x1 + x2^2 + x3^3 + x4^4 - x0
    # Output: +1 for y >= 0; -1, otherwise
    xs = 2 * np.random.random((no_training + no_testing, 4))
    for i in range(1, no_qubits):
        xs[:, i] = xs[:, i] ** (i + 1)
    coeffs = np.random.random(4)
    threshold = np.random.random() * 6
    ys = np.where(xs @ coeffs - threshold >= 0, +1, -1)
    return xs[:no_training], ys[:no_training], xs[no_training:], ys[no_training:]
 
xs_train, ys_train, xs_test, ys_test = prepare_dataset(no_training=200, no_testing=50)

Quantum SVM in PennyLane/2

########################################
# Quantum Support Vector Machine
########################################
def smv_layer(ftrs, params, wires):
    for wire in wires:
        qml.Hadamard(wires=wire)
    qml.AngleEmbedding(ftrs, wires=wires)
    qml.BasicEntanglerLayers(params, wires=wires)
 
def ansatz(ftrs, params, wires):
    for j in range(params.shape[0]):
        smv_layer(ftrs, params[j], wires)
 
@qml.qnode(dev)
def kernel_circuit(ftrs1, ftrs2, params):   # Distance between feature vectors ftrs1 and ftrs2
    ansatz(ftrs1, params, wires=wires)
    qml.adjoint(ansatz)(ftrs2, params, wires=wires)
    return qml.probs(wires=wires)
 
def kernel(ftrs1, ftrs2, params):           # We separate the kernel function from the quantum circuit
    probs = kernel_circuit(ftrs1, ftrs2, params)
    return probs[0]

Quantum SVM in PennyLane/3

########################################
# Training & Testing
########################################
def kernel_matrix(A, B, params):   # Distance between each pair of training items
    return np.array([[kernel(a, b, params) for b in B] for a in A])
 
def prepare_params(no_svmlayers, no_entlayers, no_wires):
    dims = (no_svmlayers, no_entlayers, no_wires)
    params = np.random.uniform(0, 2 * np.pi, dims, requires_grad=True)
    return params
 
no_svmlayers = 3
no_entlayers = 2
init_params = prepare_params(no_svmlayers, no_entlayers, no_qubits)
quantum_kernel = lambda A, B: kernel_matrix(A, B, init_params)
 
svm = SVC(kernel=quantum_kernel)          # Training
svm.fit(xs_train, ys_train)
predictions = svm.predict(xs_test)        # Prediction
print(f'Accuracy = {accuracy_score(predictions, ys_test)}')

Exercise 8.3: Quantum Support Vector Machines

  1. Explain how a kernel function measures the distance between two data items using a feature map. What enables non-linearity?
  2. Explain what support vectors are and why we want to maximize the margin of class separation in support vector machines.
  3. Examine the quantum feature map UΦ(x)\mathbf U_\Phi(\mathbf x). Discuss why we encode the features with the angular embedding operator and why we apply the Hadamard gates afterwards.
  4. Examine the PennyLane code of QSVM. We have to precompute the kernel matrix, where the distance between each pair of training items is measured with our quantum circuit. What is its time complexity for this step?
  5. Discuss the quantum advantage of QSVM. What helps improve the training speed of classical SVM?

4. Quantum Neural Networks

Final Q7 — slides 37–41

  • Classical vs quantum perceptron, why no activation function in a quantum perceptron, QMLP layers, QDNN (classical vs variational layers), backprop with PSR.
  • 🎙️ (Nov 17-3, 16:08): "This is included in the final, but it's not going to be involved with math… it's going to be just why questions." See Final - Instructor Hints.

Classical Perceptron {Exam Q7}

  • Perceptron is a mathematical model that imitates a neuron
  • Step 1: data item qq is encoded as a real-valued vector, or feature map

f=E(q)\mathbf f = E(q)

  • where EE is an encoding function
  • Step 2: each feature fkf_k is multiplied by a connection weight wkw_k, summed as a weighted average, and penalized by the input bias λ\lambda:

u=∑k=1Nwkfk−λ=w⊤f−λ\boxed{u = \sum_{k=1}^{N}w_kf_k - \lambda = \mathbf w^\top\mathbf f - \lambda}

  • Step 3: we produce an output value

y=α(u−δ)\boxed{y = \alpha(u-\delta)}

  • where α(⋅)\alpha(\cdot) is an activation function and δ\delta is the threshold parameter
  • Figure 19 (Perceptron): lime → input signals (1,0,1)(1,0,1) → weighted connections (×0.2, ×0.3, ×0.5\times0.2,\ \times0.3,\ \times0.5) → sum with bias λ\lambda → 0.70.7 → activation function (step at δ=0.5\delta=0.5) → output signal 1

🎙️ In class (Nov 17-3, 16:33–19:11): Perceptron = basic unit of all neural networks. Object → feature vector → multiply each feature by a weight → sum (+ bias "to compensate errors") → e.g. 0.7. Like a neuron: if the input signal is large enough (above the threshold), it "wakes up" (activates) and fires 1 to its neighbours.

🎙️ In class (Nov 17-3, 19:20–20:42): The parameters are the weights and the bias (and threshold) — change them and you get a different perceptron. One perceptron simulates one brain cell.

💡 Analogy: Deciding whether to go to a party: friends going (weight 0.5), free food (0.3), far away (0.2)… add them up; if the total beats your laziness threshold (δ), you go (output 1).

Quantum Perceptron {Exam Q7}

  • In a quantum perceptron, we do NOT need any additional activation function!
  • Step 1: each data item qkq_k is encoded (angular embedding):

∣x1…xN⟩=⨂k=1NRY(qk)\boxed{|x_1\dots x_N\rangle = \bigotimes_{k=1}^{N}\mathbf{RY}(q_k)}

  • Step 2: each feature ∣xk⟩|x_k\rangle is rotated about the X axis by phase θk\theta_k:

∣y⟩=⨂k=1NRX(θk)∣xk⟩\boxed{|y\rangle = \bigotimes_{k=1}^{N}\mathbf{RX}(\theta_k)|x_k\rangle}

  • where each θk\theta_k is a parameter
  • Note that this is a tensor product ⊗\otimes
  • In classical computing, we have to incorporate the activation function, e.g. Sigmoid σ(⋅)\sigma(\cdot), hyperbolic tangent tanh⁡\tanh, and rectified linear unit ReLU\mathrm{ReLU}, because the weighted average is only linearly learnable
  • However, we can treat each rotation in quantum perceptrons as a periodic activation function
  • Figure 20 (Quantum perceptron): ∣x1⟩,∣x2⟩,∣x3⟩|x_1\rangle,|x_2\rangle,|x_3\rangle → connections RX(θ1),RX(θ2),RX(θ3)\mathbf{RX}(\theta_1),\mathbf{RX}(\theta_2),\mathbf{RX}(\theta_3) → ⊗\otimes → ∣y1,y2,y3⟩|y_1,y_2,y_3\rangle

🎙️ In class (Nov 17-3, 21:13–21:54): "Instead of having weights, we have phases. From weights to phases" — each connection has its own θk\theta_k; then tensor product to get the final state.

🎙️ In class (Nov 17-3, 22:01–23:09): A classical NN has two parts: the weights = linear part ("they're actually linear regression") and the activation function = non-linear part.

🎙️ In class (Nov 17-3, 23:09–23:59): ⭐ "In the quantum perceptron, everything is non-linear. Even the rotation is non-linear — think about rotation, it's a circle. That means we don't need the activation function at all. The rotation itself is an activation function."

❓ Why does a classical perceptron need an activation function? Weighted sums are linear; stacking linear layers is still just one linear map — it can never learn a curved boundary (e.g. XOR). The activation function (sigmoid/tanh/ReLU) injects non-linearity.

❓ Why does a quantum perceptron NOT need one? (Ex 8.4.3) Its "weights" are rotation angles, and rotation acts through cos⁡θ2\cos\frac\theta2 and sin⁡θ2\sin\frac\theta2 — periodic, non-linear functions of both the parameter and the (angle-encoded) input. Measuring ⟨Z⟩\langle Z\rangle gives e.g. cos⁡(q+θ)\cos(q+\theta) — already a non-linear curve. So the non-linearity is built into the gate.

❓ Classical vs quantum perceptron (Ex 8.4.1): weights wkw_k ↔ phases θk\theta_k; weighted sum ↔ tensor product of rotations; real vector ↔ quantum state; separate activation function ↔ none needed (rotation is periodic activation).

💡 Analogy: A classical neuron is a ruler + a switch: the ruler (weights) can only measure straight lines, so you bolt on a switch (activation) to bend the result. A quantum neuron is a steering wheel — turning it is already circular motion; no extra part needed to make curves.

Quantum Multilayer Perceptron (QMLP) {Exam Q7}

  • Each layer consists of multiple quantum perceptrons
  • Input layer is the data encoder, not an actual group of quantum perceptrons
  • Variational hidden layer learns non-linear patterns from the dataset with rotation gates
  • Output layer learns to compute the score for each output class from the learned patterns
  • Activation functions are NOT necessary because the hidden layer already performs as an activation function
  • Figure 21 (QMLP): Input layer (features, 5 nodes) → Variational layer (basic entangler), 4 nodes each with θ\theta, labelled "QUANTUM" → Output layer (2 nodes)

🎙️ In class (Nov 17-3, 24:12–25:22): QMLP = quantum counterpart of the multilayer perceptron. The input layer is just a channel (no perceptron). Output layer: 2 quantum perceptrons. Hidden layer: multiple quantum perceptrons.

🎙️ In class (Nov 17-3, 25:42–29:39): ⭐ Design intuition: 5 input features → 2 classes directly is hard — "when the dimension becomes too much you cannot see the grouping; everything is spread in the space." Reduce 5 → 4 dims and grouping appears; then a plane can separate the classes. The hidden layer is a dimensionality reducer / data compressor — "the number of perceptrons [in the hidden layer] reflects the number of dimensions in the output" of that layer.

🎙️ In class (Nov 17-3, 29:49–29:56): Each hidden perceptron is a quantum perceptron with its own parameters.

❓ Why have a hidden layer at all? To transform (compress/re-represent) the data into a space where the classes group together and become separable — the hidden layer "learns non-linear patterns".

❓ Why is the input layer not a perceptron layer? It has no trainable parameters — it only encodes the classical features into qubits (quantum embedding).

❓ Why use a basic entangler as the hidden layer? It gives rotation (non-linearity + parameters) and entanglement (lets features interact) with the fewest parameters → trainable.

💡 Analogy: Sorting mail at Thailand Post: input layer = the mail slot (just receives); hidden layer = sorting by province (compresses messy addresses into a few groups); output layer = "Bangkok" vs "Upcountry" bins.

Quantum Deep Neural Networks (QDNNs) {Exam Q7}

  • Learning from multiple levels of representation
  • Each hidden layer can be either classical or variational (→ HYBRID)
    • Classical layer learns linear transformation
    • Variational layer learns an activation function
  • The more layers, the more abstract representation it can learn from data
  • This results in higher accuracy
  • Activation functions are NOT necessary because the hidden layer already performs as one
  • Figure 22 (QDNNs): Input layer (features) → Hidden 1 … Hidden nn (each node with θ\theta, box labelled "HYBRID") → Output layer

🎙️ In class (Nov 17-3, 30:13–30:48): Deep learning = multilayer perceptron with more than one hidden layer. "That's the definition."

🎙️ In class (Nov 17-3, 31:14–31:36): Again: "We don't need any activation functions because all quantum perceptrons are non-linear by themselves."

🎙️ In class (Nov 17-3, 34:26–34:54): ⭐ "In most cases we use a quantum algorithm as activation function. We mix the classical neural network with a quantum algorithm. This is a practical use — we don't use pure quantum algorithms."

🎙️ In class (Nov 17-3, 40:28–41:40): Advantage? Flexibility of the activation function: sigmoid/tanh are fixed to one shape; a variational layer is a learnable activation function → can reduce the complexity of the classical model.

❓ Why make the network hybrid (classical + variational layers)? Classical layers are cheap and great at linear transformations (and at changing dimensions); quantum layers provide a learnable non-linearity. Combining them uses each where it's strongest, and keeps the qubit count small (NISQ-friendly).

❓ Why does more depth help? Each layer builds a more abstract representation on top of the previous one (edges → shapes → objects), which typically raises accuracy — at the cost of more parameters (and barren plateaus).

Training QDNNs with Backpropagation Algorithm {Exam Q7}

  1. Feed a new input data item to the QDNN and let it produce an output state
  2. Measure the prediction loss

L=∑k=1NΔ(⟨0∣U∗(Θ) Bk U(Θ)∣0⟩, tk)\boxed{L = \sum_{k=1}^{N}\Delta\big(\langle0|\mathbf U^*(\Theta)\,\mathbf B_k\,\mathbf U(\Theta)|0\rangle,\ t_k\big)}

  1. For each layer from the last to the first, re-estimate each of its parameters θ\theta:

θ(k+1)=θ(k)−η∂L∂θ∣θ=θ(k)\boxed{\theta^{(k+1)} = \theta^{(k)} - \eta\left.\frac{\partial L}{\partial\theta}\right|_{\theta=\theta^{(k)}}}

  1. Repeat Steps 1–3 until convergence
  • Figure 23 (Backpropagation): Input → Hidden 1 → Hidden 2 → Hidden 3 → Output (0.25,0.75)(0.25, 0.75) vs gold-standard label (0,1)(0,1); "Adjust these weights to minimize the loss" (arrow pointing backwards)
  • Worked loss (MSE):

LMSE=(0.25−0)2+(0.75−1)22=0.0625+0.06252=0.0625L_{\text{MSE}} = \frac{(0.25-0)^2+(0.75-1)^2}{2} = \frac{0.0625+0.0625}{2} = 0.0625

🎙️ In class (Nov 17-3, 31:43–32:26): Train it "just like deep learning" — backpropagation: compute the prediction loss, then update parameters from the last layer to the first (last, second-last, third-last…), one set at a time.

🎙️ In class (Nov 17-3, 32:26–33:41): ⭐ "How would you update? Stochastic gradient descent — and you use the parameter shift rule to update each parameter." Step 3's ∂L∂θ\frac{\partial L}{\partial\theta} is computed by PSR. "Every time you compute the gradient: parameter shift rule. That's it."

🎙️ In class (Nov 17-3, 37:47–39:46): In the hybrid code, PyTorch separately estimates the parameters: classical layers → SGD (or Adam) via normal differentiation; quantum layers → parameter shift rule. "It's done automatically. You don't have to implement anything apart from your model."

❓ Why from the last layer to the first? The loss is measured at the output; the chain rule passes the error signal backwards — each layer's gradient depends on the gradients of the layers after it.

❓ How does backprop differ for classical vs quantum layers? (Ex 8.4.7) Same update equation for both. Classical layers: gradient by analytic differentiation (autograd). Quantum layers: gradient by PSR — run the circuit at θ±π2\theta\pm\frac\pi2 — because the quantum state can't be inspected/differentiated directly.

💡 Analogy: A relay team loses the race. The coach starts with the last runner ("you lost 2 s"), then works backwards to each earlier runner, telling each how much to adjust — for the quantum runners he can't watch the video, so he times them on two test runs (±90°) instead.

Example: XOR Model

  • In classical logic, the XOR gate poses a challenge in ML because its class boundary is non-linear, unlike AND and OR
  • We will develop a QMLP model that imitates the XOR gate
  • Figure 24: truth tables in the (A,B)(A,B) plane:
    • AND (both arguments must be true): only (1,1)=1(1,1)=1 — one straight line separates it
    • OR (at least one argument must be true): only (0,0)=0(0,0)=0 — one straight line separates it
    • XOR (exclusive OR, only one of the arguments must be true): (0,1)=(1,0)=1(0,1)=(1,0)=1, (0,0)=(1,1)=0(0,0)=(1,1)=0 — needs a curved boundary

❓ Why is XOR the classic test? No single straight line separates XOR's 1s from 0s → a linear model (single classical perceptron without non-linearity) cannot learn it. If our quantum layer learns XOR, it proves the layer provides non-linearity.

XOR Model in PennyLane/1

import torch as T
from torch import nn as N
from torch import optim as O
 
wires = ['w1', 'w2', 'w3', 'w4']
dev = qml.device('default.qubit', wires=wires)
 
##### Dataset Preparation #####
def prepare_dataset(no_training, no_testing):
    xor_tbl = T.tensor([ (0, 0, 0),
                         (0, 1, 1),
                         (1, 0, 1),
                         (1, 1, 0) ], dtype=T.float)
    training_idxs = np.random.randint(4, size=no_training)
    testing_idxs = np.random.randint(4, size=no_testing)
    training_data = xor_tbl[training_idxs]
    testing_data = xor_tbl[testing_idxs]
    return training_data, testing_data
 
no_training = 1000
no_testing = 100
training_data, testing_data = prepare_dataset(no_training, no_testing)

XOR Model in PennyLane/2

##### Hybrid Multilayer Perceptron #####
@qml.qnode(dev)
def circuit(inputs, params):
    qml.AngleEmbedding(inputs, wires=wires)
    qml.BasicEntanglerLayers(params, wires=wires)
    outvec = [qml.expval(qml.PauliZ(wires=w)) for w in wires]
    return outvec
 
class HybridMLP(N.Module):
    def __init__(self, dim_input, dim_output):
        super().__init__()
        (self.dim_input, self.dim_output) = (dim_input, dim_output)
        self.linear1 = N.Linear(self.dim_input, 4)
        self.qlayer = qml.qnn.TorchLayer(circuit, {"params": (3, 4)})
        self.linear2 = N.Linear(4, self.dim_output)
    def forward(self, inputs):
        outvec = self.linear1(inputs)      # Layer 1: Linear(2 -> 4)
        outvec = self.qlayer(outvec)       # Layer 2: Basic entangler
        outvec = self.linear2(outvec)      # Layer 3: Linear(4 -> 1)
        return outvec
 
xor_model = HybridMLP(dim_input=2, dim_output=1)
  • Architecture: classical Linear(2→4) → quantum layer (AngleEmbedding + 3 basic-entangler layers on 4 qubits, 3×4=123\times4=12 parameters, output ⟨Z⟩\langle Z\rangle per wire) → classical Linear(4→1)

🎙️ In class (Nov 17-3, 35:41–37:31): Classical parts = the N.Linear layers (PyTorch); quantum part = qml.qnn.TorchLayer(circuit, …). "We use quantum algorithms in the place of activation functions. We don't need the hyperbolic tangent."

XOR Model in PennyLane/3

##### Training #####
loss_fn = N.MSELoss()                                  # Mean squared error
opt = O.Adam(xor_model.parameters(), lr=0.1)           # parameters() returns a set of model parameters
no_iters = 30
batch_size = 20
loss_threshold = 1e-5
for i in range(no_iters):                              # Loop of epochs
    np.random.shuffle(training_data)
    total_loss = 0.0
    for j in range(no_training // batch_size):         # Batch training
        batch = training_data[j * batch_size : (j + 1) * batch_size]
        inmat = batch[:, 0:2]
        outmat = xor_model(inmat).flatten()            # Make prediction
        goldmat = batch[:, 2]
        loss = loss_fn(outmat, goldmat)                # Compute prediction loss
        total_loss += loss.detach().data.item()
        opt.zero_grad()                                # Perform backpropagation
        loss.backward()
        opt.step()
    print(f'Total loss {i}: {total_loss}')
    if total_loss < loss_threshold: break

XOR Model in PennyLane/4

##### Testing #####
no_correct = 0
for j in range(no_testing // batch_size):
    batch = testing_data[j * batch_size : (j + 1) * batch_size]
    inmat = batch[:, 0:2]
    goldmat = batch[:, 2] >= 0.5
    outmat = xor_model(inmat).flatten()
    preds = outmat >= 0.5
    no_correct += (preds == goldmat).sum().item()
print(f'Accuracy: {100 * no_correct / no_testing}')
# The accuracy is 100%. You should be proud of yourself. ;)

Some Types of Deep Learning Models/1

  • Unidirectional RNNs (Uni-RNNs): inputs x(1),…,x(N)\mathbf x^{(1)},\dots,\mathbf x^{(N)}, hidden states hL(t)\mathbf h_L^{(t)} passed left→right, outputs y(t)\mathbf y^{(t)}
  • Bidirectional RNNs (Bi-RNNs): two hidden chains hL(t)\mathbf h_L^{(t)} (left→right) and hR(t)\mathbf h_R^{(t)} (right→left)
  • Convolutional Neural Networks (CNNs): image → Conv2D(3) → feature maps → MaxPool → pooled feature map → Flatten → vector (x1,…,xN)(x_1,\dots,x_N) → MLP → class yy
  • Figure 25: Any deep learning model can be made hybrid by substituting its activation function with a more flexible variational layer. Its rotation gates automatically learn non-linear class boundaries.

Some Types of Deep Learning Models/2

  • Transformer model is the foundation of modern-day generative AI, e.g. LLMs
    • Residual network is incorporated only to avoid gradient vanishing
    • Position encoding simply attaches an index to each token for computing the distance penalty
  • Figure 26 (translation "Mary looks this word up" → Thai "แมรี่ ค้นหา คำ นี้"):
    1. Extract phrase structures in the source (encoder: position encoding → multi-head attention → Add & Norm → Feed Forward → Add & Norm, ×N)
    2. Align phrase structures to the target (decoder: masked self-attention, cross-attention with encoder Q/K/V)
    3. Produce translation (Linear → Softmax → right-shifted output "ค้นหา คำ นี้ ∅")
  • Transformer model can also be made hybrid in the same fashion.

Limitations

  • Barren plateau (pl. plateaux [FR])
    • In a high-dimensional parameter space, the prediction loss's landscape is mostly flat, resulting in very small gradients
    • Very small gradients cannot determine the optimal direction for the next moves
    • The SGD algorithm becomes inefficient
  • Scalability
    • Interaction between a classical computer and a quantum computer is prone to communication latency
    • Variational quantum algorithms usually have a significantly larger number of parameters, requiring more qubits than other quantum algorithms
  • Figure 27: loss LL vs Θ\Theta — mostly flat ("barren plateau" on both sides) with one narrow deep dip; gradients in the flat area are tiny, so the SGD update equation struggles to reach the optimum

🎙️ In class (Nov 17-3, 41:53–42:21, student Q on latency): "That's a problem at the moment. The quantum computers and the GPU cards are stored separately — you need a very fast bus for data transmission… Unless you've got a GPU/QPU card" (NVIDIA is developing/selling one).

🎙️ In class (Nov 17-3, 43:02–43:50): IBM platforms are slow (ms per computation); photonic QCs (PsiQuantum) aim for GHz speed. "When the platform is mature, hybrid models will show up."

❓ Why do barren plateaus hurt SGD? (Ex 8.4.8) The update is −η ∂L/∂θ-\eta\,\partial L/\partial\theta. On a flat plateau ∂L/∂θ≈0\partial L/\partial\theta\approx0, so steps are ~zero — the optimizer barely moves and can't tell which way leads to the narrow valley. Worse, with PSR the tiny gradient is buried in shot noise.

❓ Why would replacing all activations in a 1B-parameter LLM with quantum layers be very slow? (Ex 8.4.9) Every quantum parameter needs 2 extra circuit runs (PSR) per gradient step, each needing many shots, plus CPU/GPU↔QPU round trips (latency) — billions of times. Plus needs huge numbers of qubits and suffers barren plateaus.

💡 Analogy: Barren plateau = trying to find the one well in a perfectly flat desert while blindfolded — the ground feels the same in every direction, so you don't know where to step.

Exercise 8.4: Quantum Neural Networks

  1. Discuss the differences between classical perceptron and quantum perceptron.
  2. Recall that there are three data embedding methods: basic embedding, angular embedding, and amplitude embedding. Regarding the data encoding of the quantum perceptron, is it possible to substitute angular embedding with amplitude embedding? Discuss challenges that we may have to encounter if we do so.
  3. Explain why we do NOT need any activation function in the quantum perceptron.
  4. Study the PennyLane implementation of an XOR gate again. Observe that the input layer is 2-dimension, the hidden layer is 4-dimension, and the output layer is 1-dimension. Are we doing dimensionality reduction or expansion? Why?
  5. In connection with the previous question, how many basic entangler layers are there? How many parameters are there in each layer?
  6. Is it possible to perform dimensionality reduction or expansion directly in a quantum circuit? Explain your method.
  7. Explain how backpropagation works on a hybrid deep learning model. Analyze the differences in treating classical layers vs. quantum layers with the update equation.
  8. Explain how the issue of barren plateaux adversely affects the stochastic gradient descent algorithm.
  9. Let's consider Transformer-based large language models, which consist of more than 1 billion parameters. Explain why replacing all of their activation functions with quantum layers will make the training process very slow.
  10. Modify the implementation of the XOR model by varying the following factors:
    • Basic entangler layer of 4 dimensions vs. strong entangler layer (with 3 inner layers) of 4 dimensions vs. 3 basic entanglers of 4 dimensions
    • Batch sizes of 20 items vs. 10 items vs. 40 items
    • Adam optimizer vs. SGD optimizer vs. AdamW optimizer
    • Then compare these configurations in three aspects: training iterations, training time, total number of parameters
  • Answer hints (mine):
    • Q2: possible, but amplitude embedding needs normalization (loses scale), each feature is no longer tied to one qubit (no one-to-one "connection" per feature), and state preparation is deep/noisy
    • Q4: 2 → 4 = expansion first (lift XOR into a higher-dim space where it becomes separable, also to match 4 qubits), then 4 → 1 reduction to the answer
    • Q5: params shape (3,4)(3,4) → 3 basic-entangler layers, 4 parameters each (12 total)
    • Q6: reduction: measure / trace out only some qubits (or read fewer ⟨Z⟩\langle Z\rangles); expansion: add ancilla qubits and entangle them
    • Q3, Q7, Q8, Q9: see ❓ boxes above

5. Conclusion

Conclusion

  • Variational quantum algorithms (VQA) are quantum algorithms with adjustable parameters, in which variation in the parameters yields temporary solutions to a problem
  • Quantum embedding is a means to convert a data item in classical computing into an equivalent quantum state for VQAs: basic, angular, and amplitude embedding
  • An ansatz is a VQA whose parameters represent a problem of interest, and problem-agnostic ansatzes are classified into basic and strong entangler layers
  • In hybrid classical-quantum ML, we can train a VQA with a classical optimization method (e.g. SGD), where gradients are cascadingly computed with the parameter shift rule
  • We can incorporate a VQA into the deep learning framework, where the VQA performs as an adaptive activation function
  • Hybrid ML is limited by two issues: the barren plateau issue and scalability

🎙️ In class (Nov 17-3, 44:14–44:32): "This is only an anchor for the beginning of your career — if you're pursuing hybrid quantum-classical neural networks, this is one way to go."

Target Learning Outcomes/1

  • Variational Quantum Algorithms (VQA)
    1. Define the structure of a VQA as a hybrid classical-quantum approach to optimization
    2. Compare and contrast quantum embedding techniques, including basis, angular, and amplitude encoding
    3. Analyze ansatz architectures (HEA, TEN, and ALT) based on their trade-offs between expressivity, trainability, and hardware efficiency
  • Hybrid Classical-Quantum Machine Learning
    1. Formulate prediction loss functions for quantum states using MSE, NLL, and Hinge Loss
    2. Apply the Parameter Shift Rule (PSR) to compute gradients of quantum circuits for optimization
    3. Implement a hybrid model in PennyLane that integrates quantum layers into classical ML frameworks like PyTorch

Target Learning Outcomes/2

  • Quantum Kernel Methods
    1. Describe how kernel functions and feature maps enable non-linear class separation by moving data into a high-dimensional feature space
    2. Architect a quantum support vector machine (QSVM) by integrating a quantum feature map with trainable entangler layers
    3. Analyze the time complexity and quantum advantage of QSVMs compared to classical SVM implementations
  • Quantum Neural Networks (QNN)
    1. Differentiate between classical perceptrons and quantum perceptrons (Qurons), specifically regarding the role of activation functions
    2. Evaluate the limitations of training deep quantum networks, such as the Barren Plateau problem and communication latency