Quantum Circuit Lab / framework fundamentals
Lesson 09 · framework fundamentals

PennyLane Basics: Circuits as Differentiable Nodes

Learn the PennyLane circuit model by building a quantum node, returning an expectation value, and differentiating it.

Intermediate16–18 min readsoftware engineering · quantum computing

The quantum node

PennyLane makes a circuit look like a Python function with trainable arguments. A device provides the target, a QNode wraps the circuit, and the measurement determines the output.

import pennylane as qml
from pennylane import numpy as np

dev = qml.device("default.qubit", wires=1)

@qml.qnode(dev)
def circuit(theta):
    qml.RY(theta, wires=0)
    return qml.expval(qml.PauliZ(0))

print(circuit(0.0))   # 1.0
print(circuit(np.pi)) # -1.0

For this circuit the expectation is cos(theta), a simple quantum layer returning a numeric feature to classical code.

Differentiate the output

theta = np.array(0.8, requires_grad=True)
grad_fn = qml.grad(circuit)
print(grad_fn(theta))

opt = qml.GradientDescentOptimizer(stepsize=0.2)
for _ in range(20):
    theta = opt.step(circuit, theta)

Gradients can use automatic differentiation, parameter-shift rules, or device-specific methods. Differentiable does not mean free: a gradient estimate may require multiple noisy executions.

Good mental model: a QNode is a function inside a classical optimisation graph, not a replacement for the whole ML stack.

That model is useful when the circuit is part of a hybrid workflow. The trade-offs are compared in Qiskit vs. PennyLane.