merlin.algorithms.kernels module
- class merlin.algorithms.kernels.FeatureMap(circuit=None, input_size=None, *, builder=None, experiment=None, input_parameters, trainable_parameters=None, dtype=torch.float32, device=None, encoder=None)
Bases:
objectQuantum feature map.
FeatureMap embeds a datapoint within a quantum circuit and computes the associated unitary for quantum kernel methods.
- Parameters:
circuit (pcvl.Circuit | None) – Pre-compiled Perceval circuit used to encode features.
input_size (int | None) – Dimension of incoming classical data. Required.
builder (CircuitBuilder | None) – Optional builder used to compile a circuit declaratively.
experiment (pcvl.Experiment | None) – Optional experiment providing both the circuit and detector configuration. Exactly one of
circuit,builder, orexperimentmust be supplied.input_parameters (str | list[str] | None) – Parameter prefix(es) that host the classical data.
trainable_parameters (list[str] | None) – Optional trainable parameter prefixes.
dtype (str | torch.dtype) – Torch dtype used when constructing the unitary.
device (torch.device | None) – Torch device on which unitaries are evaluated.
encoder (Callable[[torch.Tensor], torch.Tensor] | None) – Optional custom encoder used when the raw input shape does not match the circuit parameter layout.
- compute_unitary(x, *training_parameters)
Generate the circuit unitary after encoding x and applying trainables.
- Parameters:
x (torch.Tensor | numpy.ndarray | float) – Single datapoint to embed; accepts scalars, NumPy arrays, or tensors.
training_parameters (torch.Tensor) – Optional overriding trainable tensors.
- Returns:
Complex unitary matrix representing the prepared circuit.
- Return type:
- is_datapoint(x)
Determine if
xdescribes one sample or a batch.- Parameters:
x (torch.Tensor | numpy.ndarray | float | int) – Candidate input data.
- Returns:
Truewhenxcorresponds to a single datapoint.- Return type:
- classmethod simple(cls, input_size, *, dtype=torch.float32, device=None, angle_encoding_scale=1.0, n_modes=None)
Simple factory method to create a FeatureMap with minimal configuration.
- Parameters:
input_size (int) – Classical feature dimension. Maximum is 19.
dtype (str | torch.dtype) – Target dtype for internal tensors.
device (torch.device | None) – Optional torch device handle.
angle_encoding_scale (float) – Global scaling applied to angle encoding features. Default is
1.0.n_modes (int | None) – Number of photonic modes used by the helper circuit. If omitted,
n_modes = input_size + 1. Maximum is 20.
- Returns:
Configured feature-map instance.
- Return type:
- class merlin.algorithms.kernels.FidelityKernel(feature_map, input_state, *, shots=None, sampling_method='multinomial', computation_space=None, force_psd=True, device=None, dtype=None)
Bases:
MerlinModuleFidelity Quantum Kernel
For a given input Fock state, \(|s \rangle\) and feature map, \(U\), the fidelity quantum kernel estimates the following inner product using SLOS:
\[|\langle s | U^{\dagger}(x_2) U(x_1) | s \rangle|^{2}\]Transition probabilities are computed in parallel for each pair of datapoints in the input datasets.
- Parameters:
feature_map (FeatureMap) – Feature map object that encodes a given datapoint within its circuit.
shots (int | None) – Number of circuit shots. If
None, the exact transition probabilities are returned. Default:None.sampling_method (str) – Probability distributions are post-processed with a pseudo-sampling method:
"multinomial","binomial", or"gaussian". Default is"multinomial".computation_space (ComputationSpace | str | None) – Logical computation subspace; one of
{"fock", "unbunched", "dual_rail"}. Default:FOCK.force_psd (bool) – Projects the training kernel matrix to the closest positive semi-definite matrix. Default is
True.device (torch.device | None) – Device on which to perform SLOS.
dtype (str | torch.dtype | None) – Datatype with which to perform SLOS.
Examples
For a given training and test datasets, one can construct the training and test kernel matrices with the following structure:
circuit = Circuit(2) // PS(P("X0")) // BS() // PS(P("X1")) // BS() feature_map = FeatureMap(circuit, ["X"]) quantum_kernel = FidelityKernel( feature_map, input_state=[0, 4], ) K_train = quantum_kernel(X_train) K_test = quantum_kernel(X_test, X_train)
Use with scikit-learn for kernel-based machine learning:
from sklearn.svm import SVC svc = SVC(kernel="precomputed") svc.fit(K_train, y_train) y_pred = svc.predict(K_test)
- forward(x1, x2=None)
Calculate the quantum kernel for input data
x1andx2.If
x1andx2are datapoints, a scalar value is returned. For input datasets the kernel matrix is computed.- Parameters:
x1 (float | numpy.ndarray | torch.Tensor) – First input datapoint or dataset.
x2 (float | numpy.ndarray | torch.Tensor | None) – Second input datapoint or dataset. If omitted, the training kernel matrix for
x1is computed.
- Returns:
Scalar kernel value for datapoints, or a kernel matrix for datasets.
- Return type:
- classmethod simple(cls, input_size, *, shots=0, sampling_method='multinomial', computation_space=None, force_psd=True, dtype=torch.float32, device=None, angle_encoding_scale=1.0, n_modes=None)
Create a simple fidelity kernel with minimal configuration.
- Parameters:
input_size (int) – Classical feature dimension.
shots (int) – Number of pseudo-sampling shots. Default is
0.sampling_method (str) – Sampling method used when
shotsis positive. Default is"multinomial".computation_space (ComputationSpace | str | None) – Logical computation subspace.
force_psd (bool) – Whether to project the training kernel matrix to the nearest positive semi-definite matrix. Default is
True.dtype (str | torch.dtype) – Target dtype for internal tensors. Default is
torch.float32.device (torch.device | None) – Device on which to execute computations.
angle_encoding_scale (float) – Global scaling applied to angle encoding features. Default is
1.0.n_modes (int | None) – Number of photonic modes used by the helper construction.
- Returns:
Configured fidelity kernel.
- Return type:
- class merlin.algorithms.kernels.KernelCircuitBuilder
Bases:
objectBuilder for creating photonic quantum kernel circuits.
This class provides a fluent interface for building quantum kernel circuits with various configurations, inspired by the core.layer architecture.
- angle_encoding(*, scale=1.0)
Configure the angle encoding scale.
- Return type:
- build_feature_map()
Build and return a
FeatureMapinstance.- Returns:
Configured feature map.
- Return type:
- Raises:
ValueError – If required parameters are missing.
- build_fidelity_kernel(input_state=None, *, shots=0, sampling_method='multinomial', computation_space=None, force_psd=True)
Build and return a
FidelityKernelinstance.- Parameters:
input_state (list[int] | None) – Input Fock state. If
None, it is generated automatically.shots (int) – Number of sampling shots. Default is
0.sampling_method (str) – Sampling method for pseudo-sampling. Default is
"multinomial".computation_space (ComputationSpace | str | None) – Logical computation subspace; one of
{"fock", "unbunched", "dual_rail"}.force_psd (bool) – Whether to project to the nearest positive semi-definite matrix. Default is
True.
- Returns:
Configured fidelity kernel.
- Return type:
- device(device)
Set the computation device.
- Return type:
- dtype(dtype)
Set the data type for computations.
- Return type:
- input_size(size)
Set the input dimensionality.
- Return type:
- n_modes(modes)
Set the number of modes in the circuit.
- Return type:
- n_photons(photons)
Set the number of photons.
- Return type:
- trainable(enabled=True, *, prefix='phi')
Enable or disable trainable rotations generated by the helper.
- Return type:
Note
When the wrapped FeatureMap exposes a
pcvl.Experiment, fidelity kernels compose the attached
pcvl.NoiseModel (photon loss) before applying any detector
transforms. The resulting kernel values therefore reflect both survival
probabilities and detector post-processing.
Examples
Quickstart: Fidelity kernel in a few lines
import torch
from merlin import ComputationSpace
from merlin.algorithms.kernels import FidelityKernel
# Build a kernel where inputs of size 2 are encoded in a 4-mode circuit
kernel = FidelityKernel.simple(
input_size=2,
n_modes=4, # Here the number of modes is optional, if n_modes is not given, n_modes=input_size+1
shots=0, # exact probabilities (no sampling)
computation_space=ComputationSpace.FOCK, # allow bunched outcomes if needed
dtype=torch.float32,
device=torch.device("cpu"),
)
# X_train: (N, 2), X_test: (M, 2)
X_train = torch.rand(10, 2)
X_test = torch.rand(5, 2)
K_train = kernel(X_train) # (N, N)
K_test = kernel(X_test, X_train) # (M, N)
Custom experiment with FeatureMap
import torch
import perceval as pcvl
from merlin.algorithms.kernels import FeatureMap, FidelityKernel
# Define a photonic circuit
circuit = pcvl.Circuit(6)
# Add whatever to the circuit...
# Define the Experiment
experiment = pcvl.Experiment(circuit)
# Add noise models, detectors, etc...
experiment.noise = pcvl.NoiseModel(brightness=0.9)
experiment.detectors[0] = pcvl.Detector.threshold()
experiment.detectors[5] = pcvl.Detector.ppnr(n_wires=3)
# Use the experiment to create a FeatureMap automatically
feature_map = FeatureMap.from_photonic_backend(
input_size=0,
experiment=experiment,
)
# Build the kernel with a specific input state
kernel = FidelityKernel(
feature_map=feature_map,
input_state=[2, 0, 2, 0, 2, 0],
computation_space=ComputationSpace.FOCK,
)
X = torch.rand(8, 3)
K = kernel(X) # (8, 8)
Use with scikit-learn (precomputed kernel)
import torch
from sklearn.svm import SVC
from merlin.algorithms.kernels import FidelityKernel
# Build kernel and compute Gram matrices
kernel = FidelityKernel.simple(input_size=4, n_modes=6)
K_train = kernel(X_train)
K_test = kernel(X_test, X_train)
# Train a precomputed-kernel SVM
clf = SVC(kernel="precomputed")
clf.fit(K_train, y_train)
y_pred = clf.predict(K_test)