Lesson 54 · 110 min · advanced
Quantum Reservoir Computing
Reservoir computing splits a learning machine for time series into a fixed dynamical system, the reservoir, and a linear readout, the only trained part. This lesson builds the quantum reservoir of Fujii and Nakajima (2017): four qubits under a transverse-field Ising Hamiltonian, an input injected at every step by replacing qubit , and virtual nodes between inputs. We prove that the injection is a quantum channel, show that the reservoir forgets its initial state, derive the ridge readout from the normal equations, and measure the memory and NARMA2 performance of the lab reservoir.
Prerequisites: Hamiltonian-Evolution Encoding & Trotterisation, Noise, Decoherence, $T_1$ and $T_2$
Objectives and key results
State the echo-state and fading-memory properties precisely, derive fading memory from a uniform echo-state property, and explain why training only a linear readout turns learning into a convex least-squares problem.
Write the input injection in Kraus form, prove that it is completely positive and trace preserving, and factor it into a reset followed by .
Prove that one reservoir step never increases the trace distance between two states, and distinguish this theorem from the measured, parameter-dependent exponential forgetting of the lab reservoir.
Count the features of a time-multiplexed reservoir, compute , and derive the ridge solution including positive definiteness and the Cholesky solve.
Evaluate a readout with the NMSE, the memory curve and the memory capacity, and explain why the NARMA2 benchmark must be driven by .
- theorem · Input injection is a quantum channel
- theorem · A reservoir step does not increase the trace distance
- formula · Time-multiplexed features
- formula · Ridge readout
- definition · NMSE and memory capacity
- formula · NARMA2
Reservoir computing: fixed dynamics, trained readout#
Recurrent neural networks process a time series by feeding every input into an internal state that also remembers earlier inputs; training their recurrent weights requires backpropagation through time. Jaeger (2001, echo state networks) and Maass, Natschläger and Markram (2002, liquid state machines) observed that this training is often unnecessary: a random but fixed recurrent system already produces rich nonlinear functions of the recent inputs, and a linear combination of its state variables, trained by least squares, suffices for many tasks. Any physical system with suitable dynamics can serve as the reservoir, a quantum system included.
Definition
Reservoir computer
A reservoir is a state space with a metric , an input set and an update map , so that an input sequence drives the states from an initial state . A feature map extracts real numbers from each state, and the readout predicts with a weight vector . Only is trained. Here is the set of four-qubit density matrices, the trace distance, , and the measured values plus a constant .
Definition
Echo-state property and fading memory
The reservoir has the (uniform) echo-state property if there is a sequence such that for all initial states and all input sequences, the two trajectories driven by the same inputs satisfy . The state after many steps is then, up to , a function of the inputs alone; it echoes the input history and has forgotten where it started. The reservoir has fading memory if, for every , there is a horizon such that two input histories that agree on their last inputs lead to states within of each other, however different their earlier inputs and initial states were.
The uniform echo-state property implies fading memory
- Step 1:Unroll the last updates. The state at time depends on the past only through the state reached steps earlier.
- Step 2:A second history with possibly different early inputs and a different initial state, but the same last inputs , uses the same maps applied to another state .
- Step 3:Both are -step trajectories of the same inputs from and ; the uniform echo-state property bounds their distance by for every pair of initial states.
- Step 4:Since , choose the horizon with . This is the fading-memory property, and the feature map turns it into a statement about the features if is continuous.
- Step 5:For the quantum features: Hölder's inequality with and the trace distance . Each feature is Lipschitz in the state, so states within give features within .
Why only the readout is trained
- Step 1:The states, and therefore the feature vectors , are computed once from the fixed dynamics; the prediction is linear in the trainable parameters.
- Step 2:The squared-error loss with an penalty is a quadratic polynomial in ; stacking the feature vectors as the rows of a matrix gives the compact form.
- Step 3:The Hessian is constant and positive definite for (ridge section), so is strictly convex: no local minima, no learning rate, and a closed-form minimiser.
- Step 4:Training a parameter of the dynamics instead would require this backpropagation-through-time sum, with products of up to Jacobians.
- Step 5:For the quantum reservoir each step is a linear map on density matrices whose trace-norm gain on differences of states is at most (next section). The contraction that produces fading memory also makes these gradient products vanish, and on hardware the state is not even accessible.
The quantum reservoir: Ising dynamics and input injection#
Fujii and Nakajima (2017) proposed the natural dynamics of a small quantum many-body system as the reservoir: the state space of qubits has real parameters. The lab reservoir has qubits, a fixed Ising Hamiltonian with all-to-all couplings and a transverse field, and an input written onto qubit at every time step.
The reservoir Hamiltonian of the lab
- Step 1:The blueprint model: an Ising interaction in the direction between every pair of qubits and a field in the direction, which does not commute with the couplings and therefore generates nontrivial dynamics.
- Step 2:The fixed couplings of the lab, drawn once at random and then frozen. Couplings of different sizes and signs avoid symmetries between qubits, which would make some features linearly dependent.
- Step 3:The same operator as a sum of ten Pauli words, which is how the engine stores it before building the matrix.
- Step 4:and are real symmetric, hence so are their tensor products and . Its sixteen eigenvalues lie between and and are non-degenerate. The Bohr frequencies that appear in range from to , i.e. periods from to : during one input period the fastest modes complete more than three oscillations while the slowest barely move, so the features mix fast and slow time scales.
- Step 5:anticommutes with on the same qubit, so anticommutes with and with , and two sign changes cancel. The unitary dynamics alone conserves the parity ; the injection, which resets qubit , breaks this conservation law and lets the input steer the state.
Input injection is completely positive and trace preserving
For let . The discard-and-replace map on four qubits has the Kraus operators , , with . Hence is a quantum channel: it maps density matrices to density matrices, also when the four qubits are entangled with an outside reference system.
Proof (7 steps)
- Step 1:Definition of the partial trace over qubit (partial-trace lesson): the sum of the two diagonal blocks of .
- Step 2:Write ; the outer factors and act on qubit only and produce the projector in the tensor product.
- Step 3:Sum the previous line over and use the first line: the Kraus form reproduces the discard-and-replace map exactly.
- Step 4:Completeness of the Kraus operators, using that is normalised for every .
- Step 5:Trace preservation follows from cyclicity of the trace and completeness.
- Step 6:Complete positivity: extended to any reference system , the map keeps its Kraus form, and each term of a positive semidefinite is positive semidefinite, hence so is the sum.
- Step 7:The injected single-qubit state as a matrix: a pure state with populations and and real coherences.
∎
Injection = reset, then a rotation R_Y(2 arcsin √s)
- Step 1:The non-selective reset of qubit has the Kraus operators and ; it is the case of the theorem, since .
- Step 2:with ; its first column is the image of .
- Step 3:for , where the cosine is non-negative, so the positive square root is the right one. Hence .
- Step 4:The rotation written with the input itself, exactly the matrix the engine applies after its reset.
- Step 5:Apply the rotation to the reset state with . The injection is a reset followed by an ordinary data-dependent rotation, as in angle encoding, except that the reset discards whatever qubit carried.
- Step 6:Right after the injection, the magnetisation of qubit encodes the input linearly; also and , so the Bloch vector lies in the plane at polar angle . For the first input of the lab, .
Quick check
The input is injected into qubit . What is immediately after the injection, before any evolution?
Forgetting the initial state. One reservoir step is the channel . The injection destroys everything stored in qubit , and the Hamiltonian keeps moving information from qubits to onto qubit , where the next injection destroys it. A step can never increase the distinguishability of two states; how fast it decreases depends on the dynamics.
Reservoir steps do not increase the trace distance
For all four-qubit density matrices and every input , and the full step satisfies the same inequality. Consequently, for any two initial states driven by the same input sequence, is non-increasing in . Equality holds in the inequality whenever for a pure state of qubit , for example when both states have the same pure qubit and differ only on qubits to .
Proof (7 steps)
- Step 1:The partial trace is linear, and both states receive the same injected factor .
- Step 2:The singular values of are the products of the singular values of and , so the sums factorise. A pure-state projector has the single nonzero singular value . This proves the equality in the statement.
- Step 3:Duality of the trace norm: with , because , with equality for .
- Step 4:The defining property of the partial trace, with . Taking the maximum over on the left gives the contraction of the trace norm under the partial trace.
- Step 5:Unitary conjugation does not change the singular values. The evolution between injections therefore preserves the trace distance exactly; it only moves information around.
- Step 6:Combine the last two steps for one full step; induction over gives a non-increasing sequence .
- Step 7:The equality case: a difference stored on qubits to passes an injection untouched. Information is only erased after the Hamiltonian has carried it onto qubit , so the speed of forgetting is a property of the dynamics.
∎
Measured forgetting of the lab reservoir. Start one copy in and another in and feed both the same inputs mulberry32(42)(). After the first step exactly: the injection leaves and on qubits to , which are orthogonal, so , and the unitary keeps them orthogonal. From then on the engine measures:
| step | |
|---|---|
The distance falls by a factor of about per step between and . Since , the features after the lab's -step washout depend on the initial state by less than .
The scope runs the lab reservoir on inputs and plots the inputs, the twenty feature traces, the delay- readout against its target, and the test NMSE for delays to . Move the sliders for , and . With a short evolution the input written onto qubit is overwritten by the next injection before the couplings have spread it to the other qubits: the engine measures a delay- test NMSE of for and , no memory at all, for . The lab's is not the optimum either; gives a memory capacity (defined below) of instead of .
Virtual nodes: more features from the same qubits#
Four per input are too few features. Fujii and Nakajima therefore read out the system at equally spaced times between two inputs; each intermediate time acts as an additional virtual node, giving features that sample the trajectory.
Time multiplexing and the feature vector
- Step 1:All factors are exponentials of the same operator, so they commute and their exponents add. The sub-steps reproduce the evolution over the full time between inputs; here .
- Step 2:Inject the input, then evolve in sub-steps. The state after the last sub-step is the reservoir state that the next injection acts on.
- Step 3:is diagonal in the computational basis; with qubit as the most significant bit, the bit of qubit is bit of the integer .
- Step 4:Evaluate the trace in the computational basis and use . Only the diagonal, i.e. the measurement probabilities , enters.
- Step 5:The feature row of time step , ordered sub-step by sub-step, followed by a constant that lets the readout add an offset (the bias column).
- Step 6:The lab readout therefore has weights. The first rows are discarded as washout and the last rows are the test window.
- Step 7:The cost of the exact simulation: each sub-step computes , two products of matrices. On hardware each expectation value needs many shots and measurement disturbs the state, so each feature needs an ensemble of identical systems (the NMR setting of Fujii and Nakajima) or a re-run of the input history.
For the first input , starting from : right after the injection , and after the first sub-step of duration the four features are . The couplings have already transported part of the input into qubits and . The remaining sixteen entries of the row follow the state through the other four sub-steps.
Quick check
The same four-qubit reservoir is read out with virtual nodes instead of , with of every qubit after every sub-step and a bias column. How many weights does the linear readout have?
Training the readout: ridge regression#
Given the feature matrix (rows , bias column included) and the targets , the readout minimises the squared error plus a ridge penalty, which keeps the problem well posed when features are nearly collinear.
The ridge readout solves the normal equations
Let , and . The function has exactly one minimiser, and is symmetric positive definite. For the same formula holds if and only if has full column rank.
Proof (7 steps)
- Step 1:Expand the squared norms; the two cross terms and are equal scalars.
- Step 2:Gradients of a quadratic and a linear form, obtained by differentiating and with respect to .
- Step 3:Apply the two rules with , which is symmetric, , and for the penalty.
- Step 4:Setting the gradient to zero gives the normal equations, a linear system of size , here , independent of the number of time steps .
- Step 5:The matrix is symmetric because , and positive definite because the quadratic form is a sum of a non-negative term and a positive one. A positive definite matrix has only positive eigenvalues, so it is invertible and exists.
- Step 6:Exact second-order expansion of the quadratic ; the linear term vanishes by the normal equations. The remaining term is positive for , so is the unique global minimiser and there are no other critical points.
- Step 7:Without regularisation the argument goes through exactly when no nonzero satisfies , i.e. when the columns of are linearly independent (ordinary least squares).
∎
The bias inside X, and the Cholesky solve
- Step 1:Row (the bias column, all ones) of the normal equations reads . Because the bias sits inside , the penalty shrinks it as well, as in the engine. Textbook ridge often leaves the intercept unpenalised, which would make the mean residual exactly zero.
- Step 2:For the lab's delay- readout (, , bias weight ) the effect is negligible: the mean residual on the training rows is below .
- Step 3:Every symmetric positive definite matrix has a unique Cholesky factorisation with lower triangular and . Writing out the product shows which entries of enter each .
- Step 4:Solve the previous equation column by column for the diagonal entry and then for the entries below it. The radicand is positive: it equals , a ratio of leading principal minors, which are positive for a positive definite matrix.
- Step 5:, so the system splits into a forward substitution from the top and a back substitution from the bottom.
- Step 6:Forming dominates. The factorisation costs multiply-adds and the two triangular solves each; the lab's system is tiny.
- Step 7:The measured eigenvalues of the lab's Gram matrix. The condition number is large but harmless in double precision; shifts the smallest eigenvalue by less than , so it guards against singularity without biasing the fit.
Measuring the reservoir: NMSE, memory capacity and NARMA2#
Definition
Normalised mean squared error
On an evaluation window of steps with targets , mean and predictions , with the population variance . The NMSE is for a perfect prediction and does not change when the targets are rescaled. The lab and the engine evaluate it on the test window , which the readout never saw during training.
Reference values of the NMSE
- Step 1:Insert and expand; the cross term vanishes by the definition of .
- Step 2:Divide by . Predicting the mean scores exactly ; a useful readout must stay well below .
- Step 3:The all-zero readout. For inputs uniform on the mean is and the variance . On the lab's test window and , which gives .
- Step 4:Recalling the wrong delay perfectly is worse than predicting the mean: for independent inputs of equal variance, .
- Step 5:On the training rows of an ordinary least-squares fit, the residual is orthogonal to every column of . The bias column gives a zero mean residual, and since lies in the column space, it is orthogonal to the residual.
- Step 6:Pythagoras for the orthogonal decomposition . Moreover , so the squared Pearson correlation equals the explained fraction. On the training rows exactly; on test rows only approximately.
Quick check
The inputs are independent and uniform on , and the task is to recall . A readout returns , so it predicts at every step. Approximately what NMSE does the grader measure on a long test window?
Definition
Memory curve and short-term memory capacity
For the delay task , train a readout for each delay and let be the squared Pearson correlation between its prediction and the target on the test window. The function is the memory curve, and is the short-term memory capacity (Jaeger 2001). A perfect memory of the last inputs contributes . For independent inputs, Jaeger showed that the capacity summed over all delays cannot exceed the number of reservoir features (here ).
The memory curve of the lab reservoir (engine values, inputs from mulberry32(42), steps, washout , training rows to , test rows to , ):
| delay | test NMSE | |
|---|---|---|
Summed over the memory capacity is out of a maximum of . The last three inputs are recalled almost perfectly; beyond the memory fades quickly, as the measured contraction predicts. On the test window , the training-window identity derived above.
With the delay set to , the predicted trace still follows the target closely (test NMSE ), and the bar chart shows the whole memory curve. Increase to and the prediction visibly shrinks towards the mean: the readout cannot reconstruct what the dynamics has already forgotten.
Definition
NARMA2 benchmark
The second-order nonlinear autoregressive moving-average task (Atiya and Parlos 2000) asks the readout to emulate the recurrence driven by an input sequence . The target needs both memory (two past outputs, one past input) and nonlinearity (a product and a cube), so it tests more than the delay tasks. In this lesson, in the engine and in the scope, NARMA2 is driven by (the constant NARMA2_INPUT_SCALE = 0.5 of the engine), while the reservoir itself still receives .
Why the drive must be scaled: bounded for u ≤ 1/2, divergent for u on [0, 1)
- Step 1:All terms are non-negative, which gives the lower bound ; the upper bound uses .
- Step 2:Solve the quadratic inequality; its discriminant is .
- Step 3:Induction starting from : the interval is mapped into . With the scaled drive the target is bounded; the engine measures for the seed- inputs.
- Step 4:For inputs near there is no equilibrium at all: the fixed-point equation of the constant drive has no real solution. Since every term is non-negative, ; once two consecutive values exceed , each new value exceeds the previous one and grows like a Fibonacci sequence, a double-exponential blow-up.
- Step 5:Measured with the engine for the seed- inputs: a run of large inputs pushes above at step , the value first exceeds at step (the th value), and at step it overflows double precision. A target that diverges cannot be learned by any bounded readout, so the benchmark uses , the range for which Atiya and Parlos defined it.
With the same features and ridge readout, the NARMA2 test NMSE is : ten times the delay- error, but far below the mean predictor's . Products such as are only partly present in twenty expectation values; larger reservoirs, correlators and more virtual nodes are the usual levers (Mujal et al. 2021).
The TypeScript cell reproduces every number of this lesson with the engine: the inputs, the first feature row, the delay- to delay- test errors, the memory curve, the trace distances of the two copies and both NARMA2 runs.
import { DensityMatrix, Statevector, expmIHermitian, hamiltonianToMatrix, matrix, traceDistance } from 'quantumcore';
import { L54_RESERVOIR, delayTask, injectInput, memoryCurve, narma2, narma2Target, nmse, predictReadout, reservoirFeatures, reservoirHamiltonian, reservoirInputs, ridgeRegression } from 'quantumcore/qml';
const spec = L54_RESERVOIR; // n = 4, the six J_ij, h = 0.5, tau = 4, V = 5, injection on qubit 0
const s = reservoirInputs(42, 1200); // s_k = mulberry32(42)()
const sci = (v: number) => v.toExponential(3).replace(/e([+-])(\d)$/, (_m, sign, digit) => 'e' + sign + '0' + digit); // 1.000e+00 as in Python
console.log('inputs s_0..s_2: ' + s.slice(0, 3).map((v) => v.toFixed(10)).join(', '));
// Exact density-matrix reservoir: one row per input = 4 x 5 values <Z_q> followed by the bias 1.
const X = reservoirFeatures(spec, s);
console.log('features: ' + X.length + ' rows x ' + X[0].length + ' columns, row 0 starts ' + X[0].slice(0, 4).map((v) => v.toFixed(6)).join(' '));
// Ridge readout trained on k = 200..799, tested on k = 800..1199.
for (const d of [1, 2, 3]) {
const y = delayTask(s, d);
const w = ridgeRegression(X.slice(200, 800), y.slice(200, 800), 1e-6);
console.log('delay ' + d + ': test NMSE ' + nmse(predictReadout(X.slice(800), w), y.slice(800)).toPrecision(4) + ', ' + w.length + ' weights');
}
const r2 = memoryCurve(spec, s, 6, { washout: 200, trainEnd: 800, lambda: 1e-6, features: X });
console.log('memory curve r_d^2: ' + r2.map((v) => v.toFixed(4)).join(' ') + ' -> MC = ' + r2.reduce((a, b) => a + b, 0).toFixed(3));
// Fading memory: the same inputs drive |0000> and |1111>; one step = injection + V sub-steps U = exp(-i H tau / V).
const U = expmIHermitian(hamiltonianToMatrix(reservoirHamiltonian(spec), 4), spec.tau / spec.virtualNodes);
const Ud = matrix.adjoint(U);
function step(rho: DensityMatrix, input: number): DensityMatrix {
injectInput(rho, spec.injectQubit, input);
for (let v = 0; v < spec.virtualNodes; v++) rho = new DensityMatrix(4, matrix.mul(matrix.mul(U, rho.toMatrix()), Ud).data);
return rho;
}
let a = DensityMatrix.fromStatevector(Statevector.fromBitstring('0000'));
let b = DensityMatrix.fromStatevector(Statevector.fromBitstring('1111'));
const dist: string[] = [];
for (let k = 1; k <= 60; k++) {
a = step(a, s[k - 1]);
b = step(b, s[k - 1]);
if ([1, 10, 20, 40, 60].includes(k)) dist.push('k=' + k + ' ' + sci(traceDistance(a, b)));
}
console.log('trace distance: ' + dist.join(', '));
// NARMA2: diverges when driven by s in [0, 1), bounded when driven by u = s/2.
const raw = narma2(s.slice(0, 80));
console.log('NARMA2 driven by s: |y_k| > 1 first at k = ' + raw.findIndex((v) => Math.abs(v) > 1) + ', > 1000 at k = ' + raw.findIndex((v) => Math.abs(v) > 1000));
const yN = narma2Target(s); // = narma2(s.map((v) => v / 2))
const wN = ridgeRegression(X.slice(200, 800), yN.slice(200, 800), 1e-6);
console.log('NARMA2 driven by s/2: y in [' + Math.min(...yN.slice(1)).toFixed(4) + ', ' + Math.max(...yN).toFixed(4) + '], test NMSE ' + nmse(predictReadout(X.slice(800), wN), yN.slice(800)).toPrecision(4));Expected output
inputs s_0..s_2: 0.6011037519, 0.4482905590, 0.8524657935 features: 1200 rows x 21 columns, row 0 starts -0.089304 0.850546 0.230656 0.300436 delay 1: test NMSE 0.01052, 21 weights delay 2: test NMSE 0.03571, 21 weights delay 3: test NMSE 0.05027, 21 weights memory curve r_d^2: 0.9895 0.9644 0.9502 0.8836 0.7916 0.5480 -> MC = 5.127 trace distance: k=1 1.000e+00, k=10 3.250e-01, k=20 6.011e-02, k=40 1.276e-03, k=60 4.931e-05 NARMA2 driven by s: |y_k| > 1 first at k = 57, > 1000 at k = 75 NARMA2 driven by s/2: y in [0.1163, 0.3343], test NMSE 0.1015
The NumPy cell rebuilds the reservoir from scratch: a port of mulberry32, the Hamiltonian from Kronecker products, the injection as an explicit partial trace and the ridge readout by Cholesky. It prints the same lines as the TypeScript cell.
import numpy as np
# Port of the engine's mulberry32 (bit-for-bit identical floats).
def mulberry32(seed):
a = seed & 0xFFFFFFFF
def imul(u, v):
return (u * v) & 0xFFFFFFFF
def r():
nonlocal a
a = (a + 0x6D2B79F5) & 0xFFFFFFFF
t = imul(a ^ (a >> 15), 1 | a)
t = ((t + imul(t ^ (t >> 7), 61 | t)) & 0xFFFFFFFF) ^ t
return (t ^ (t >> 14)) / 4294967296
return r
# The L54 reservoir: 4 qubits (qubit 0 = most significant bit), H = sum J_ij X_i X_j + h sum Z_q.
n, h, tau, V = 4, 0.5, 4.0, 5
J = {(0, 1): 0.0695, (0, 2): 0.6305, (0, 3): -0.0920, (1, 2): -0.0749, (1, 3): -0.3440, (2, 3): 0.8774}
I2, X, Z = np.eye(2), np.array([[0.0, 1.0], [1.0, 0.0]]), np.diag([1.0, -1.0])
def on(ops): # tensor product with ops[q] on qubit q and I elsewhere
out = np.eye(1)
for q in range(n):
out = np.kron(out, ops.get(q, I2))
return out
H = sum(c * on({i: X, j: X}) for (i, j), c in J.items()) + h * sum(on({q: Z}) for q in range(n))
E, W = np.linalg.eigh(H)
U = W @ np.diag(np.exp(-1j * E * tau / V)) @ W.conj().T # one virtual-node step e^{-i H tau / V}
SIGNS = np.array([[1 - 2 * ((x >> (n - 1 - q)) & 1) for q in range(n)] for x in range(2**n)]) # (-1)^{x_q}
def inject(rho, s): # rho -> |psi_s><psi_s| (x) Tr_0 rho
blocks = rho.reshape(2, 8, 2, 8)
reduced = blocks[0, :, 0, :] + blocks[1, :, 1, :]
psi = np.array([np.sqrt(1 - s), np.sqrt(s)])
return np.kron(np.outer(psi, psi), reduced)
def step(rho, s): # inject, then V sub-steps; returns the new state and the 4V features
rho, row = inject(rho, s), []
for _ in range(V):
rho = U @ rho @ U.conj().T
row.extend(SIGNS.T @ np.real(np.diag(rho))) # <Z_q> = sum_x (-1)^{x_q} rho_xx
return rho, row
def basis_state(bits):
rho = np.zeros((2**n, 2**n), dtype=complex)
rho[int(bits, 2), int(bits, 2)] = 1
return rho
r = mulberry32(42)
s = np.array([r() for _ in range(1200)])
print("inputs s_0..s_2:", ", ".join(f"{v:.10f}" for v in s[:3]))
rho, rows = basis_state("0000"), []
for sk in s:
rho, row = step(rho, sk)
rows.append(row + [1.0])
F = np.array(rows)
print(f"features: {F.shape[0]} rows x {F.shape[1]} columns, row 0 starts", " ".join(f"{v:.6f}" for v in F[0, :4]))
def ridge(Xm, y, lam): # (X^T X + lam I) w = X^T y by Cholesky
L = np.linalg.cholesky(Xm.T @ Xm + lam * np.eye(Xm.shape[1]))
return np.linalg.solve(L.T, np.linalg.solve(L, Xm.T @ y))
def nmse(pred, y):
return np.sum((pred - y) ** 2) / np.sum((y - y.mean()) ** 2)
r2 = []
for d in range(1, 7):
y = np.concatenate([np.full(d, np.nan), s[:-d]]) # y_k = s_{k-d}
w = ridge(F[200:800], y[200:800], 1e-6)
pred = F[800:] @ w
r2.append(np.corrcoef(pred, y[800:])[0, 1] ** 2)
if d <= 3:
print(f"delay {d}: test NMSE {nmse(pred, y[800:]):.4g}, {len(w)} weights")
print("memory curve r_d^2:", " ".join(f"{v:.4f}" for v in r2), f"-> MC = {sum(r2):.3f}")
# Fading memory: the same inputs drive |0000> and |1111>; trace distance T = 1/2 sum |eigenvalues of the difference|.
a, b, dist = basis_state("0000"), basis_state("1111"), {}
for k in range(1, 61):
a, _ = step(a, s[k - 1])
b, _ = step(b, s[k - 1])
dist[k] = 0.5 * np.sum(np.abs(np.linalg.eigvalsh(a - b)))
print("trace distance:", ", ".join(f"k={k} {dist[k]:.3e}" for k in (1, 10, 20, 40, 60)))
def narma2(u):
y = np.zeros(len(u))
for k in range(1, len(u)):
y_km2 = y[k - 2] if k >= 2 else 0.0
y[k] = 0.4 * y[k - 1] + 0.4 * y[k - 1] * y_km2 + 0.6 * u[k - 1] ** 3 + 0.1
return y
raw = narma2(s[:80])
print(f"NARMA2 driven by s: |y_k| > 1 first at k = {np.argmax(np.abs(raw) > 1)}, > 1000 at k = {np.argmax(np.abs(raw) > 1000)}")
y = narma2(0.5 * s) # u = s/2
w = ridge(F[200:800], y[200:800], 1e-6)
print(f"NARMA2 driven by s/2: y in [{y[1:].min():.4f}, {y.max():.4f}], test NMSE {nmse(F[800:] @ w, y[800:]):.4g}")Expected output
inputs s_0..s_2: 0.6011037519, 0.4482905590, 0.8524657935 features: 1200 rows x 21 columns, row 0 starts -0.089304 0.850546 0.230656 0.300436 delay 1: test NMSE 0.01052, 21 weights delay 2: test NMSE 0.03571, 21 weights delay 3: test NMSE 0.05027, 21 weights memory curve r_d^2: 0.9895 0.9644 0.9502 0.8836 0.7916 0.5480 -> MC = 5.127 trace distance: k=1 1.000e+00, k=10 3.250e-01, k=20 6.011e-02, k=40 1.276e-03, k=60 4.931e-05 NARMA2 driven by s: |y_k| > 1 first at k = 57, > 1000 at k = 75 NARMA2 driven by s/2: y in [0.1163, 0.3343], test NMSE 0.1015
In the lab you write the readout yourself; the grader scores your weights on the test steps.
References
- K. Fujii and K. Nakajima, Harnessing disordered-ensemble quantum dynamics for machine learning, Physical Review Applied 8, 024030 (2017).doi:10.1103/PhysRevApplied.8.024030
- H. Jaeger, The "echo state" approach to analysing and training recurrent neural networks, GMD Report 148, German National Research Center for Information Technology (2001).ai.rug.nl
- H. Jaeger, Short term memory in echo state networks, GMD Report 152, German National Research Center for Information Technology (2002).
- K. Nakajima and I. Fischer (eds.), Reservoir Computing: Theory, Physical Implementations, and Applications, Springer, Singapore (2021).doi:10.1007/978-981-13-1687-6
- P. Mujal, R. Martínez-Peña, J. Nokkala, J. García-Beni, G. L. Giorgi, M. C. Soriano and R. Zambrini, Opportunities in quantum reservoir computing and extreme learning machines, Advanced Quantum Technologies 4, 2100027 (2021).doi:10.1002/qute.202100027
- A. F. Atiya and A. G. Parlos, New results on recurrent network training: unifying the algorithms and accelerating convergence, IEEE Transactions on Neural Networks 11, 697–709 (2000).doi:10.1109/72.846741
- W. Maass, T. Natschläger and H. Markram, Real-time computing without stable states: a new framework for neural computation based on perturbations, Neural Computation 14, 2531–2560 (2002).doi:10.1162/089976602760407955
Hands-on labs
Train the ridge readout of a quantum reservoir
1 step · auto-gradedOpen labThe -qubit quantum reservoir of the lesson is fixed: its Ising Hamiltonian, the input injection on qubit and the virtual nodes per input are never trained. Only the linear readout is learned. Your TypeScript function receives the feature matrix of the training window (the expectation values plus a bias column) and the targets of a short-term memory task, and returns the ridge-regression weights . The grader recomputes the reservoir and scores your weights on unseen time steps: recalling the input of one step ago must reach , recalling the input of two steps ago .