Skip to content

torch

eigenkit.photonics.torch

The PyTorch interface for photonic circuits (experimental).

PhotonicCircuit is a PyTorch nn.Module that stores the weights of the circuit as an nn.Parameter. With it, loss.backward() computes the exact photonic parameter-shift gradient. It uses the same torch.autograd.Function bridge as the qubit backends that use the parameter-shift rule (see eigenkit/torch/interface.py). This is what makes photonic circuits trainable for quantum machine learning with the usual PyTorch tools, such as the optimisers and the combination with classical layers.

PyTorch is imported at the top of this module. The module is imported only when the PyTorch interface is requested, so the rest of the photonics package (and import eigenkit) imports neither PyTorch nor Perceval.

Scope: one observable that is diagonal in the Fock basis, so the output is a single number, and one sample per forward pass. Outputs with several values or several observables, batches, and gradients computed by PyTorch's own automatic differentiation are not supported yet.

PhotonicCircuit

Bases: Module

A trainable linear-optical circuit, as a PyTorch nn.Module.

It stores the circuit's weights as an nn.Parameter. forward(inputs) returns the expectation value of observable, connected to PyTorch's automatic differentiation.

Parameters:

Name Type Description Default
spec PhotonicCircuitSpec

The circuit to train.

required
observable PhotonicObservable

The readout, a single observable that is diagonal in the Fock basis.

required
backend_name str

The Perceval backend, as for PercevalBackend. Default: "SLOS".

'SLOS'
init_weights Sequence[float] | Tensor | None

The initial weights, of length spec.n_weights. The default is zeros.

None
dtype dtype

The data type of the weights. The default is torch.float64, to match the precision of the executor.

float64

Raises:

Type Description
ValueError

If init_weights does not have the shape (spec.n_weights,), if observable can never match the output of the circuit (a mode outside the circuit, or a target with the wrong length or number of photons), or if backend_name is unknown or only samples.

forward(inputs=None)

Return the expectation value of observable for one sample.

The value is connected to PyTorch's automatic differentiation.

Parameters:

Name Type Description Default
inputs Sequence[float] | Tensor | None

The 1-D input vector, of length spec.n_inputs. The default is zeros.

None