Quantum machine learning¶
Polypus trains quantum models in two ways:
- Your Qiskit circuits with
polypus.qml.train(): you bring a feature map, an ansatz and a cost that scores the measured bitstrings. Polypus runs the circuits; their meaning is yours. - Native models with
polypus.qml.Model: Polypus builds the model from encoders, trainable layers and a readout, so it also knows how to differentiate it exactly, predict with it and save it.
qml.train (Qiskit circuits) |
qml.Model (native) |
|
|---|---|---|
| The model | Any feature map and ansatz you build in Qiskit | Encoders, a hardware-efficient ansatz, QCNN convolution and pooling |
| Scoring | Your function of the measured bitstrings (or counts) | A readout of Pauli observables and a loss (hinge, cross-entropy, squared error, …) |
| Adam's gradient | Finite differences of the fitness | Analytic gradient: adjoint differentiation with exact=True, a parameter-shift estimate with shots |
| Exact probabilities instead of shots | No | Yes (exact=True, local native simulator) |
| Minibatches | No | Yes (batch_size) |
| Prediction | Counts per row (qml.predict); you map them to classes |
Decisions per row (TrainedModel.predict), or counts |
| Saving a trained model | Save best_params yourself |
TrainedModel.save / qml.load |
Both run on the same backends and infrastructures and take the same optimizers. Pass native pieces to qml.train and it raises TypeError.
Qiskit circuits: qml.train¶
polypus.qml.train() trains a data-encoding circuit: a Qiskit feature_map encodes each row of x_train (one sample per row, len(feature_map.parameters) values each), an ansatz holds the trainable weights, and the optimizer maximises the mean per-sample score over the training set. It takes the same optimizers and parameters as train() except fusion and trace, so a qml.train run writes no call trace. polypus.External works too: each candidate the library asks for runs one circuit per training sample, and max_evaluations counts candidates, not circuits.
Pass y_train (one label per row) to train a supervised model: each sample is then scored against its own label. Here a binary classifier reads out the parity of the measured bits:
from qiskit.circuit.library import real_amplitudes, zz_feature_map
feature_map = zz_feature_map(feature_dimension=4, reps=2)
ansatz = real_amplitudes(num_qubits=4, reps=2)
def correct(bitstring, label): # 1.0 when the read-out matches the label
return float(bitstring.count("1") % 2 == label)
result = polypus.qml.train(
feature_map,
ansatz,
X_train, # shape (n_samples, 4)
polypus.DE(generations=50, population_size=20),
shots=1024,
n_qpus=1,
dimensions=len(ansatz.parameters),
expectation_function=correct, # fitness = expected training accuracy
infrastructure="local",
nodes=1,
cores_per_qpu=1,
id="qml_classifier",
y_train=y_train, # shape (n_samples,): class indices
)
Like train(), it takes a keyword-only callback, called once per iteration with a polypus.TrainProgress; returning True stops the run with what it has reached (see Watching and stopping a run). Its evaluations count candidates, each one circuit per training sample.
Cost functions¶
With y_train, expectation_function takes one of three forms:
expectation_function |
Scores each sample by |
|---|---|
f(bitstring, label) -> float |
the count-weighted mean of f over its shots; f runs once per distinct (label, bitstring) of each batch |
polypus.CachedCost(f) |
the same, memoised across generations (f must be pure) |
polypus.SampleCost(g) |
g(counts, label) -> float on its whole {bitstring: count} dict, for losses that are not linear in the outcome probabilities |
For example, a polypus.SampleCost can maximise the log-likelihood, i.e. minimise the cross-entropy:
import math
def log_likelihood(counts, label):
hits = sum(n for bits, n in counts.items() if bits.count("1") % 2 == label)
# Clip before the log: every score must be finite.
return math.log(max(hits / sum(counts.values()), 1e-6))
expectation_function = polypus.SampleCost(log_likelihood)
polypus.Rotosolve needs a fitness that averages a cost per bitstring, so it does not train with a SampleCost: qml.train raises polypus.ConfigurationError (a ValueError) before anything runs. It trains the ansatz only, so the feature map's gates are free; see Rotosolve.
Integer labels (Python or NumPy ints and bools) reach your function as int; if any label is not an integer, all of them arrive as float (regression targets). y_train is validated before anything runs: a length other than the number of rows, a NaN/inf, a string, a complex number (even a NumPy one with no imaginary part) or a one-hot row is rejected with the offending index. Without y_train, one expectation_function(bitstring) is shared by every sample, as before.
Prediction¶
To evaluate a trained model, polypus.qml.predict() builds the circuits training ran and executes every sample in one scheduled run: one backend batch and, on CUNQA, one allocation. Its RunResult.counts holds one dict per row, in row order; map them to classes with the objective's read-out:
run = polypus.qml.predict(
feature_map,
ansatz,
X_test,
result.best_params,
shots=1024,
infrastructure="local",
seed=7,
)
def majority_parity(counts):
odd = sum(n for bits, n in counts.items() if bits.count("1") % 2)
return int(odd > sum(counts.values()) - odd)
predictions = [majority_parity(counts) for counts in run.counts]
With n_qpus > 1 the samples are spread over the QPUs; one sample's shots are never split. See examples/basic_qml.py for a complete classifier, from training to held-out accuracy.
Native models: qml.Model¶
A native model has three pieces: an Encoder that loads each sample, an Ansatz with the trainable layers, and a Readout that turns the measurement into a prediction. Model.fit trains it and returns a TrainResult, as train() does; bind fixes the trained parameters for inference.
import numpy as np
import polypus
from polypus import qml
# Two classes on one feature: small angles are +1, large ones -1.
X = np.array([[0.1], [0.3], [0.2], [2.9], [3.0], [2.8]])
y = np.array([1, 1, 1, -1, -1, -1])
model = qml.Model(
qml.Encoder(1).angle_encoder("ry"),
qml.Ansatz(1).real_amplitudes(1),
qml.Readout([qml.Z(0)], decision="sign"),
)
result = model.fit(
X, y, method=polypus.Adam(max_iters=60, learning_rate=0.1), loss="hinge", seed=3
)
trained = model.bind(result.best_params)
labels = trained.predict(np.array([[0.15], [2.95]])) # [1, -1]
examples/qml_iris_demo.py trains one on the Iris flowers end to end, and examples/qml_native_showcase.py runs every encoder, layer, optimizer, readout, decision and loss in twenty checked scenarios: classification, regression, an unsupervised ground state and data re-uploading among them, SPSA on sampled results, Rotosolve and the models it refuses, an ask/tell optimizer of your own through polypus.External, and a trained model run on Aer with a noise model.
Everything after y is keyword-only. The execution arguments have defaults (shots=1024, infrastructure="local", n_qpus=1, nodes=1, cores_per_qpu=2, id="qml"), and without backend the native simulator runs the model locally (on CUNQA, whose QPUs run Aer, it is "aer").
Building a model¶
Encoder(num_qubits) and Ansatz(num_qubits) declare their width, which must match. Each method appends a layer and returns the same object, so calls chain. A layer that cannot work is rejected where you write it: pooling below two qubits raises ValueError at that .pool(...), and the object keeps its previous layers.
A model is also bounded in size, before any circuit is built. It has at most 1 000 000 qubits (Encoder(num_qubits) and Ansatz(num_qubits) refuse more), and its layers emit at most 4 000 000 gates in all. The layer that would pass that budget raises ValueError where you add it, naming the gate count it would reach; a reps so large that the count does not even fit in 64 bits gets its own message. Encoders count their gates for the features they carry, so a model with many features can only pass the budget once it meets the data: in fit, predict or run the error is then a polypus.ConfigurationError. The readout's basis change and measurements are not counted. An amplitude encoder emits 2^(n+1) − 3 gates on n qubits, so it takes at most 20.
| Layer | Method | Trainable parameters |
|---|---|---|
Angle encoding: feature j as a rotation of qubit j |
angle_encoder("rx" \| "ry" \| "rz") |
none |
Amplitude encoding: up to 2^n features in the amplitudes (must come first; n at most 20) |
amplitude_encoder() (Encoder only) |
none |
Basis encoding: X on qubit j when feature j is 1.0 |
basis_encoder() |
none |
IQP (ZZFeatureMap) encoding |
iqp_encoder(entanglement="full") |
none |
Hardware-efficient block (Qiskit's TwoLocal) |
hardware_efficient(reps, rotations=["ry", "rz"], entangler="cx", entanglement="linear", final_rotation_layer=True) (Ansatz only) |
one per rotation gate |
RealAmplitudes |
real_amplitudes(reps) (Ansatz only) |
one per rotation gate |
PennyLane's StronglyEntanglingLayers: per layer, Rz(φ), Ry(θ), Rz(ω) (in that order) on every qubit, then an entangler from each qubit i to (i + r) mod n |
strongly_entangling(reps, ranges=None, entangler="cx") (Ansatz only) |
3·n·reps (n: qubits active at that point) |
PennyLane's SimplifiedTwoDesign: an Ry on every qubit, then per block CZ + Ry on the even and then the odd pairs |
simplified_two_design(reps) (Ansatz only) |
n + 2·(n − 1)·reps (n: qubits active at that point) |
QCNN convolution, one block shared by every pair; "odd_pairs" needs at least 3 active qubits, the other pairings at least 2 |
conv("basic" \| "cartan", pairing="alternating") (Ansatz only) |
4 ("basic") or 3 ("cartan") |
| QCNN pooling: each pair of active qubits becomes one | pool("basic", keep="even_positions") (Ansatz only) |
3 |
In strongly_entangling, ranges gives each layer's r: one per layer, each from 1 to n − 1, or None for PennyLane's default r = (layer mod (n − 1)) + 1 (1, 2, …). A range outside those bounds, or a count other than reps, raises ValueError at the call. One active qubit gets no entanglers, only the rotations. The parameters go layer by layer, qubit by qubit, (φ, θ, ω) each: PennyLane's (reps, n, 3) weights flattened in C order.
simplified_two_design starts with an Ry(θ) on every qubit. Each of its reps blocks then takes the even pairs (0, 1), (2, 3), … and after them the odd pairs (1, 2), (3, 4), …, and on each pair applies CZ followed by an Ry(θ) on both of its qubits. The parameters are the n initial weights and then, block by block and pair by pair, two per pair: PennyLane's initial weights (n,) followed by its (reps, n − 1, 2) weights in C order. With reps=0, or with a single active qubit (no pairs) whatever reps, only the initial Ry layer remains. PennyLane still declares (reps,) block weights for a single wire, which it never uses; Polypus reserves none, so drop them when porting such weights.
Two other common templates are hardware_efficient settings rather than methods of their own:
- Qiskit's
EfficientSU2is theTwoLocalwith["ry", "rz"]rotations, sohardware_efficient(reps)isEfficientSU2(n, reps, entanglement="linear"). With Qiskit's defaultentanglement="reverse_linear", usehardware_efficient(reps, entanglement="full"): the same unitary (Qiskit chose"reverse_linear"as the cheaper equivalent of"full"), with moreCXgates. - PennyLane's
BasicEntanglerLayersishardware_efficient(reps, rotations=[axis], entanglement="circular", final_rotation_layer=False), withaxisitsrotation("rx"by default). On two qubits they differ:"circular"entangles(0, 1)and then(1, 0), PennyLane only(0, 1).
The Ansatz may also re-encode the data between its trainable layers (data re-uploading) with angle_encoder, basis_encoder and iqp_encoder. Model(encoder, ansatz, readout) copies the pieces, so building on them afterwards does not change it; it checks that some layer loads the data, that the layers have trainable parameters and that the readout fits the qubits left at the end, and reports num_params.
The readout¶
Readout(observables, decision="raw", threshold=None) measures Pauli observables and turns their expectations into a prediction. Write an observable as a product, qml.Z(0) or qml.Z(0) @ qml.Z(1) (also X and Y), or as a weighted sum, qml.Observable([(0.5, qml.Z(0)), (-1.0, qml.Z(0) @ qml.Z(1))]). Positions count the qubits still active, so after a pooling Z(0) is the first survivor.
decision |
Prediction | Observables |
|---|---|---|
"raw" |
the expectation ⟨O₀⟩ itself (float) |
one (others are ignored) |
"sign" |
+1 if ⟨O₀⟩ ≥ 0, else -1 |
one |
"threshold" |
+1 if ⟨O₀⟩ ≥ threshold, else -1 |
one |
"argmax" |
the index of the largest ⟨O_k⟩: the class |
one per class, at least two |
X and Y observables are measured by rotating those qubits first; the readout may mix them as long as each qubit is measured in one basis throughout.
Training¶
model.fit(x, y=None, *, method, loss=None, ...) takes rows of features (a list or a NumPy array of real numbers: a complex feature or label, even a NumPy one with no imaginary part, is a TypeError naming its position) or a qml.Dataset, and any optimizer: polypus.Adam gets the exact gradient, and DE, PSO, QNG, CMAES, SPSA and polypus.External work as in train(). polypus.Rotosolve needs a fitness that is a sinusoid of each parameter, so it takes only loss="expectation" and models whose trainable parameters each sit in one rotation: a conv or pool layer over more than one pair shares its parameters, and fit raises polypus.ConfigurationError for it before anything runs.
loss |
Labels | Scores ⟨O₀⟩ (or all ⟨O_k⟩) as |
|---|---|---|
"hinge" |
+1 / -1 |
max(0, 1 − y·⟨O₀⟩) |
"binary_cross_entropy" |
0 / 1 |
cross-entropy with p = (1 + ⟨O₀⟩) / 2 |
"squared_error" |
any number | (⟨O₀⟩ − y)² |
"categorical_cross_entropy" |
class index 0 … k−1 |
softmax cross-entropy over the k observables (the loss for "argmax") |
"expectation" |
none | −⟨O₀⟩: maximises the readout |
With labels, loss is required. Without them (y=None), the run maximises the readout's first observable, and a supervised loss raises polypus.ConfigurationError. To minimise a cost Hamiltonian, write it as an Observable with negated coefficients:
cost = qml.Readout([qml.Observable([(-1.0, qml.Z(0) @ qml.Z(1)), (-0.5, qml.Z(1))])])
model = qml.Model(
qml.Encoder(2).angle_encoder("ry"), qml.Ansatz(2).hardware_efficient(1), cost
)
result = model.fit(X_unlabeled, method=polypus.Adam(max_iters=100))
Five more options are keyword-only:
exact=Truecomputes each circuit's probabilities exactly instead of sampling, soshotsno longer matters and the run has no shot noise. It needs the local native simulator, and memory grows as2^nper circuit.batch_size=bscores each evaluation onbsamples drawn afresh from the seed (1 ≤ b < number of samples). Adam uses the batch for its gradient and keeps its best result on the whole set; the other optimizers reportbest_fitnessre-scored on the whole set at the end.initial_pointstarts the optimizer fromnum_paramsparameters you choose instead of random ones, as intrain()(see Starting point): thebest_paramsof an earlier run, or theparamsof a saved model to keep training it (see Saving).final_shots=nre-evaluates the best candidates once the optimizer has stopped, withnshots per circuit, as intrain()(see Final re-evaluation):result.final_paramsis the one with the best value andresult.final_fitnessthat value. The final batch scores every training sample, also withbatch_size, and the run before it is the one withoutfinal_shots.exact=Trueuses no shots, sofitrefusesfinal_shotswith it.callback=fcallsfonce per iteration with apolypus.TrainProgress, as intrain(): returningTruestops the run, which returns what it has reached, and thefinal_shotsbatch is still sent (see Watching and stopping a run). Withbatch_size, thebest_fitnessit sees is the minibatch estimate, except for Adam, whose best is on the whole set. With Adam,evaluationscounts the point each gradient batch measures, not the gradient's shifted circuits.
Cost of the exact gradient. One gradient runs samples × (1 + 2 × occurrences) circuits, where occurrences counts the trainable gates. A parameter that several gates share costs two circuits per gate: a basic convolution over 4 qubits has 4 parameters on 3 pairs, so 12 occurrences and 25 circuits per sample instead of 9. The 1 is the parameters' own circuits, so an Adam iteration is that one batch: Adam reads the iteration's fitness from it rather than running them again. With batch_size, the gradient runs on the minibatch and Adam scores the parameters on the whole set apart, one more batch of samples circuits.
Prediction¶
model.bind(params) returns a TrainedModel with those parameters; the Model itself does not change, so it can carry several (from different seeds, say). Both methods take rows or a Dataset, and the execution arguments of fit.
trained.predict(x)returns one decision per row: anintfor"sign","threshold"and"argmax", afloatfor"raw".trained.run(x)returns the counts behind them: aRunResultwith one dict per row (merged_countsisNone). Withexact=Trueit returns anExactResult, whoseprobabilitiesholds one dict per row.
Inspecting the circuit¶
model.circuit(x) returns the circuit the model runs for one sample x, a polypus.Circuit to draw or export like any other (see Drawing and Export). The features are fixed, the trainable angles are the parameters theta_0, theta_1, … in the order of best_params, and the readout's basis change comes right before the measurement:
from polypus import qml
model = qml.Model(
qml.Encoder(2).angle_encoder("ry"),
qml.Ansatz(2).real_amplitudes(1),
qml.Readout([qml.Y(0)], decision="sign"),
)
qc = model.circuit([0.3, 1.2])
print(qc)
print(qc.param_names) # ['theta_0', 'theta_1', 'theta_2', 'theta_3']
┌─────────┐ ┌─────────────┐ ┌─────────────┐ ┌─────┐ ┌───┐ ┌─┐
q0: ─┤ Ry(0.3) ├─┤ Ry(theta_0) ├───■───┤ Ry(theta_2) ├─┤ S† ├─┤ H ├─┤M├─────
└─────────┘ └─────────────┘ │ └─────────────┘ └─────┘ └───┘ └╥┘
┌─────────┐ ┌─────────────┐ ┌─┴─┐ ┌─────────────┐ ║ ┌─┐
q1: ─┤ Ry(1.2) ├─┤ Ry(theta_1) ├─┤ X ├─┤ Ry(theta_3) ├────────────────╫──┤M├─
└─────────┘ └─────────────┘ └───┘ └─────────────┘ ║ └╥┘
║ ║
c2: ══════════════════════════════════════════════════════════════════╩═══╩══
0 1
S† then H rotates Y onto Z, which is what the measurement reads (X needs only the H). model.circuit(x, params) fixes the trainable angles too, and trained.circuit(x) does so with the trained model's own parameters: it is exactly the circuit trained.run([x]) executes, so polypus.run_quantum_circuit(trained.circuit(x), shots, "local", backend="polypus", seed=s) gives the counts of trained.run([x], shots=shots, seed=s). x is checked as a row of fit is: a feature count the encoders cannot carry or a non-finite value raises ValueError.
Your own training loop: qml.expval, qml.jacobian and qml.vjp¶
fit runs the whole optimization. To write the loop yourself, with a loss of your own or another framework's optimizer, these functions give you the model's raw values and their derivatives, as NumPy arrays (float64, one row per row of x):
qml.expval(model, x, params)returns the expectation of every readout observable, shape(rows, observables), whatever the decision: one column per class for"argmax".qml.jacobian(model, x, params, wrt="params")returns their derivatives with respect to the parameters, shape(rows, observables, num_params).wrt="inputs"differentiates with respect to the features instead, shape(rows, observables, features), andwrt="both"returns the two arrays as a tuple.
Both take params as a list or an array of num_params values and the execution arguments of run (with exact=True, the exact values; with shots, estimates). The Jacobian is that of the expectations, not of a loss, so the chain rule is yours. For a squared error:
params = np.zeros(model.num_params)
for _ in range(40):
values = qml.expval(model, X, params, exact=True)[:, 0]
by_params = qml.jacobian(model, X, params, exact=True)[:, 0, :]
gradient = 2 * (values - y) @ by_params / len(y) # d mean((⟨O₀⟩ − y)²) / dθ
params = params - 0.3 * gradient
examples/qml_expval_jacobian_loop.py runs this loop to the end and checks that the loss goes down.
- Only the product. When you only need the Jacobian multiplied by a vector, as a reverse-mode backward pass does,
qml.vjp(model, x, params, cotangent, wrt="params")gives it directly.cotangentholds one weight per row and observable, shape(rows, observables), for example∂loss/∂⟨O⟩. Withwrt="params"you getΣ_rows,obs cotangent · J, shape(num_params,), summed over the rows.wrt="inputs"gives one row per row ofx, shape(rows, features), andwrt="both"gives the two as a tuple. Withexact=True, it costs one adjoint pass per row however many observables the readout has, instead of one per row and observable. With shots it runs the same circuits asjacobian. The squared error above becomesgradient = qml.vjp(model, X, params, (2 * (values - y) / len(y))[:, None], exact=True)for a one-observable readout. ANaNor an infinity in the cotangent is not refused: it shows up in the result, as it would if you multiplied the Jacobian yourself. - Inputs. The derivative with respect to the features covers angle encoders, re-uploaded ones included, and IQP encoders (for
Rzz(x_i·x_j)it applies the product rule). Amplitude and basis encoders have no derivative in the data:wrt="inputs"or"both"with one raisespolypus.ConfigurationError;wrt="params"works with any model. - Cost.
expvalruns one circuit per row. With shots,jacobianruns two per shifted gate per row (+π/2and−π/2): every gate that reads a parameter (a parameter shared by several gates, as inconvandpool, counts once per gate), every encoder gate that reads the row for"inputs", both for"both". Areal_amplitudes(1)over 2 qubits has 4 parameters, so 8 circuits per row. Withexact=Trueit differentiates every one of those gates at once by adjoint differentiation: one pass per row and observable, about three simulations long, whatever the number of parameters, holding two statevectors at a time. When the memory budget holds one statevector of the model's width but not two, it runs the parameter shift instead and says so once in the log atinfolevel; the result is the same to rounding.Model.fit's exact gradient for Adam goes the same way, and so doesvjp(with one pass per row);QuantumLayer's exact backward pass is avjp. - Execution. A call opens one backend for all its rows (one allocation on CUNQA) and runs them in blocks sized from the cores and the backend, so memory stays bounded however many rows you pass; Ctrl+C stops it between blocks, and with
exact=Truealso inside a block. The result does not depend on the blocks: a call on all the rows equals the calls on pieces of them, put together. - Seeds. The functions return bare arrays, so the seed drawn when you omit
seedis only logged: passseed=to repeat a sampled call exactly. On Aer and CUNQA, a seeded call repeats on the same machine and configuration.
In a PyTorch network: polypus.torch.QuantumLayer¶
polypus.torch.QuantumLayer(model, ...) is a torch.nn.Module built on those two functions: its forward pass is qml.expval, its backward pass qml.vjp, and its trainable parameters (layer.params) are the model's. Put it between classical layers and train the whole network with any torch.optim optimizer. PyTorch is not a dependency of Polypus; install it with the extra, and import the module explicitly (import polypus does not import it):
pip install "polypus-quantum[torch]"
import torch
from polypus import qml
from polypus.torch import QuantumLayer
model = qml.Model(
qml.Encoder(2).angle_encoder("ry"),
qml.Ansatz(2).real_amplitudes(1),
qml.Readout([qml.Z(0), qml.Z(1)]),
)
quantum = QuantumLayer(model, exact=True)
net = torch.nn.Sequential(
torch.nn.Linear(4, 2), # four features onto the two qubits' angles
quantum, # (batch, 2) -> (batch, quantum.num_observables)
torch.nn.Linear(quantum.num_observables, 1),
)
optimizer = torch.optim.Adam(net.parameters(), lr=0.1)
examples/qml_torch_hybrid.py trains this network on two classes and checks that it learns them.
- Arguments.
QuantumLayer(model, *, initial_params=None, seed=None, ...)takes aModelandqml.expval's execution arguments (shots,infrastructure,backend,exact, …), whichexpvalchecks at the first forward pass. Withoutinitial_paramsthe parameters start uniform in[-π, π), drawn with PyTorch's generator (torch.manual_seedrepeats them).layer.num_paramsandlayer.num_observables(alsomodel.num_observables) size the neighbouring layers. For a model trained withfitor read withqml.load,polypus.torch.from_trained(trained, ...)starts from its parameters. - Shapes. The input is
(batch, features)and the output(batch, num_observables); a 1-D input is one sample and gives(num_observables,). Each forward pass is oneexpvalcall with the whole batch, and each backward pass onevjpcall with the incoming gradient as its cotangent, with respect to what needs a gradient: the parameters, the input (which a layer before it needs), or both. - Inputs. The gradient with respect to the input needs an angle or IQP encoder, as
qml.jacobianandqml.vjpdo: with an amplitude or basis encoder, an input that requires a gradient makes the backward pass raisepolypus.ConfigurationError. Put such a layer first, or detach its input. - dtype and device. The quantum computation runs in
float64on the CPU. The output comes back in the dtype and on the device of the input, and each gradient in its tensor's, so afloat32network needs no.double(); the input is rounded at the boundary. A complex input is aTypeError. The layer's own parameter isfloat64unless you convert the layer. GPU tensors are moved to the CPU and back; CI does not test that path. - Seeds. With
shots,seed=makes training repeatable: every forward and backward pass gets its own seed, derived fromseedand the number of the forward pass, so two layers built with the sameseedand fed the same batches give the same values and gradients at every step. That counter is not saved in thestate_dict: to replay, build a new layer with the sameseed. A seeded layer is not safe to call from several threads at once. Withoutseed, each call draws its own. - Cost. Every forward pass and every backward pass opens and closes a backend: two per training step, so on CUNQA two
qraiseallocations per step. Preferexact=Trueon the local simulator while you develop. - Limits. No second derivatives (no
create_graph=Truethrough the layer), notorch.compileand notorch.vmap. Save thestate_dict;copy.deepcopy(layer)works too.
Quantum kernels: qml.kernel_matrix¶
A quantum kernel compares two samples by how much the states an encoder prepares for them overlap: K(x, y) = |⟨φ(x)|φ(y)⟩|², with |φ(x)⟩ = U(x)|0…0⟩. qml.kernel_matrix(encoder, x1, x2=None) returns that Gram matrix as a NumPy array (float64, shape (len(x1), len(x2))), ready for any kernel method that takes a precomputed kernel, such as scikit-learn's support vector machine:
from sklearn.svm import SVC
encoder = qml.Encoder(2).iqp_encoder()
k_train = qml.kernel_matrix(encoder, x_train, exact=True) # (train, train)
k_test = qml.kernel_matrix(encoder, x_test, x_train, exact=True) # (test, train)
svm = SVC(kernel="precomputed").fit(k_train, y_train)
accuracy = svm.score(k_test, y_test)
examples/qml_kernel_svc.py trains this SVM on data no straight line separates, exactly and with shots, and checks its accuracy. scikit-learn is not a dependency of Polypus: pip install -r requirements-examples.txt brings it.
- Arguments.
encoderis aqml.Encoder, every layer of which loads the data; anything else (anAnsatz, aModel, aTrainedModel) is aTypeError: trainable kernels, with an ansatz inside the feature map, are not supported.x1andx2are rows orDatasets (labels are not used) of the same width, checked asqml.expvalchecks its rows; each rejection is apolypus.ConfigurationErrorthat namesx1orx2. The execution arguments areqml.expval's, with its rules. exactor shots. Withexact=True(local native simulator only) the kernel comes from the inner products of the statevectors: each sample's state is simulated once when they all fit in the memory budget, otherwise in tiles. The matrix itself counts against the budget (8 bytes an entry): when what it leaves holds one statevector of the encoder's width but not the two an inner product needs, each entry is computed from one statevector instead, by the circuit below, and the log says so once atinfolevel; when it leaves no room even for one, the call raisespolypus.InsufficientMemoryError, the same exception as a statevector that does not fit, before anything runs. Compute fewer rows ofx1at a time (np.vstackof the pieces is the same matrix, bit for bit, while each piece takes the inner products) or raisePOLYPUS_MEM_BUDGET. With shots, each entry is the frequency of0…0in the circuitU(x1_i)followed byU(x2_j)†(onemeasure_all), an unbiased estimate with standard error√(K(1−K)/shots). The two give the same kernel up to rounding and shot noise.- Cost. Without
x2, the matrix ofx1with itself is symmetric: only the upper triangle, diagonal included, runs,N(N+1)/2circuits forNrows, and the lower half is its mirror, soK == K.Texactly. Withx2, every entry runs,N·Mcircuits, even ifx2isx1(nothing compares them). Exactly, it isNsimulations (orN + M) instead of circuits, as long as the states fit in memory. - The diagonal.
K(x, x)is executed like any other entry, never set to1: it is1to rounding exactly, and below1on noisy hardware or with a noise model, which is information about the device. - Positive semi-definite. The exact Gram matrix is PSD (to rounding); one estimated with shots may not be, by a little. scikit-learn's
SVCaccepts it as it is. If your method needs a PSD matrix, clip its negative eigenvalues (w, v = np.linalg.eigh(K); K = (v * np.maximum(w, 0)) @ v.T), or add a small multiple of the identity, or use more shots; Polypus leaves the matrix as measured. - Scaling the features. Like any encoder, the kernel is only as good as the angles it gets. Angle encoders take the feature itself as the angle; IQP encoders also take products of features (
Rzz(x_i·x_j)), which grow quadratically with the range: scale the features to a modest interval first, such as[-1, 1]or[0, π](Dataset.scale_features_to, andscale_features_withthe training set's ranges for the test set). A range too wide makes every pair of samples look unrelated, and the matrix tends to the identity. - Execution. A call opens one backend (one allocation on CUNQA) and runs the pairs in blocks sized like
qml.expval's rows; Ctrl+C stops it between blocks and, withexact=True, inside the inner products. Exactly, a call on some rows ofx1gives those rows of the whole matrix, bit for bit. With shots, passseed=to repeat a call.
Data¶
qml.Dataset(x, y=None) checks the rows once (non-empty, at least one feature, equal width, finite) and keeps the labels with them. It splits reproducibly and scales features:
data = qml.Dataset(X, y)
train, test = data.train_test_split(0.25, seed=7)
ranges = train.feature_ranges()
train.scale_features_to(0.0, np.pi) # angle encoding works best on [0, π]
test.scale_features_with(ranges, 0.0, np.pi) # the same scaling, frozen on train
result = model.fit(train, method=polypus.Adam(), loss="hinge")
labels = model.bind(result.best_params).predict(test)
A Dataset built without labels stays unlabeled through splits, and trains only with loss="expectation". With a Dataset, do not pass y.
Saving¶
trained.save("classifier.json")
trained = qml.load("classifier.json")
The file is JSON: the model and its parameters, with a format name and a version. Loading checks it as Model and bind would, so a damaged or edited file raises ValueError, and it never runs code. The parameters read back exactly, so a loaded model predicts as the saved one did. save replaces any file at that path.
A loaded model can keep training from where it stopped: its model is the Model, and its params are the starting point.
trained = qml.load("classifier.json")
more = trained.model.fit(
X, y, method=polypus.Adam(), loss="hinge", initial_point=trained.params
)
trained = trained.model.bind(more.best_params)