API Documentation

class DataGenTorch(batch_size=None, shuffle=False, seed=None, device=device(type='cpu'))[source]

Abstract base class for generating data in PyTorch.

Parameters:
  • batch_size (int) – Size of batch for data loader. Defaults to None (batch mode).

  • shuffle (bool) – Shuffle data in loader. Defaults to False.

  • seed (int) – The seed used to initialize the random number generator. Defaults to None.

  • device (Device) – The device where to run the computations. Defaults to torch.device(“cpu”).

abstractmethod gen_data(*args, **kwargs)[source]

Generate the data.

Parameters:
  • args – Variable length argument list.

  • kwargs – Arbitrary keyword arguments.

Returns:

The generated data.

Return type:

D

abstractmethod data_to_loader(*args, **kwargs)[source]

Convert data from gen_data to pytorch data loader.

Parameters:
  • args – Variable length argument list.

  • kwargs – Arbitrary keyword arguments.

Returns:

Data loader.

Return type:

L

class PriorTorch(sizex, seed=None, device=device(type='cpu'))[source]

Abstract base class for generating priors in PyTorch.

Parameters:
  • sizex (int) – Dimension of feature space.

  • seed (int, optional) – The seed used to initialize the random number generator. Defaults to None.

  • device (Device) – The device where to run the computations. Defaults to torch.device(“cpu”).

abstractmethod gen_data(*args, **kwargs)[source]

Generate the data.

Parameters:
  • args – Variable length argument list.

  • kwargs – Arbitrary keyword arguments.

Returns:

The generated data.

Return type:

D

class DataGenCapacity(sizex, num_samples=10, scale=2.0, shift=-1.0, **kwargs)[source]

Generates data for memory capacity estimation.

Parameters:
  • sizex (int) – The size of the input data.

  • num_samples (int, optional) – The number of output samples to generate. Defaults to 10.

  • scale (float, optional) – The re-scaling factor for uniform random numbers in [0, 1]. Defaults to 2.0.

  • shift (float, optional) – The shift value for uniform random numbers in [0, 1]. Defaults to -1.0.

  • kwargs – Keyword arguments passed to the base class.

gen_data(N)[source]

Generate the data.

Parameters:

N (int) – The number of inputs for the model.

Returns:

A dictionary containing the generated data.

Return type:

DataOut

data_to_loader(data, s)[source]

Convert data to pytorch loader.

Parameters:
  • data (DataOut) – Output of gen_data.

  • s (int) – Current label sample.

Return type:

DataLoader

Raises:

ValueError – For invalid data or index s.

class DataGenFat(prior, Sb=10, Sr=10, gamma=0.0, **kwargs)[source]

Generates data for estimating fat shattering dimension.

Parameters:
  • prior (DataGenTorch) – Data generator for prior X.

  • Sb (int, optional) – The number of binary samples to check shattering. Defaults to 10.

  • Sr (int, optional) – The number of level offset samples to check shattering. Defaults to 10.

  • gamma (float, optional) – The fat shattering parameter gamma. Defaults to 0.0 (pseudo-dimension).

  • kwargs – Keyword arguments passed to the base class.

gen_data(d)[source]

Generate the data.

Parameters:

d (int) – The number of inputs to shatter.

Returns:

A dictionary containing the generated data.

Return type:

DataOut

data_to_loader(data, sr, sb)[source]

Convert data to pytorch loader.

Parameters:
  • data (DataOut) – Output of gen_data.

  • sr (int) – Current r sample.

  • sb (int) – Current b sample.

Returns:

Pytorch data loader.

Return type:

DataLoader

Raises:

ValueError – For invalid data or indeces sr or sb.

class DataGenRademacher(prior, num_sigma_samples=10, num_data_samples=10, **kwargs)[source]

Generates uniform data for estimating the empirical Rademacher complexity.

Parameters:
  • prior (PriorTorch) – Prior for generating X samples.

  • num_sigma_samples (int, optional) – Number of samples for sigma. Defaults to 10.

  • num_data_samples (int, optional) – Number of samples for data sets. Defaults to 10.

  • gamma (float, optional) – The fat shattering parameter gamma Defaults to 0.0 (pseudo-dimension).

  • scale (float, optional) – The re-scaling factor for uniform random numbers in [0, 1]. Defaults to 2.0.

  • shift (float, optional) – The shift value for uniform random numbers in [0, 1]. Defaults to -1.0.

  • kwargs – Keyword arguments passed to the base class.

gen_data(m)[source]

Generate the data.

Parameters:
  • m (int) – Size of data set.

  • m – int:

Returns:

A dictionary containing the generated data.

Return type:

DataOut

data_to_loader(data, s)[source]

Convert data to pytorch loader.

Parameters:
  • data (DataOut) – Output of gen_data.

  • s (int) – Current sample.

Returns:

Pytorch data loader.

Return type:

DataLoader

Raises:

ValueError – For invalid data or index s.

class UniformPrior(sizex, scale=2.0, shift=-1.0, **kwargs)[source]

Generates uniform prior X.

Parameters:
  • sizex (int) – The size of the input data (dim of feature space).

  • scale (float, optional) – The re-scaling factor for uniform random numbers in [0, 1]. Defaults to 2.0.

  • shift (float, optional) – The shift value for uniform random numbers in [0, 1]. Defaults to -1.0.

  • kwargs – Keyword arguments passed to the base class.

gen_data(m)[source]

Generate the data.

Parameters:

m (int) – Size of data set.

Returns:

Prior X.

Return type:

Tensor

class NormalPrior(sizex, scale=1.0, shift=0.0, **kwargs)[source]

Generates normal prior for X.

Parameters:
  • sizex (int) – The size of the input data (dim of feature space).

  • scale (float, optional) – The re-scaling factor for standard normal. Defaults to 1.0.

  • shift (float, optional) – The shift value for standard normal. Defaults to 0.0.

  • kwargs – Keyword arguments passed to the base class.

gen_data(m)[source]

Generate the data.

Parameters:

m (int) – Size of data set.

Returns:

Prior X.

Return type:

Tensor

gen_dataset_capacity(N, sizex, num_samples=10, seed=None, scale=2.0, shift=-1.0, device=device(type='cpu'))[source]

Generates a dataset of input features x and output labels y.

Parameters:
  • N (int) – The number of inputs.

  • sizex (int) – The dimension of each input.

  • num_samples (int, optional) – The number of output samples to generate. Defaults to 10.

  • seed (int, optional) – The random seed to use for generating the dataset. Defaults to None.

  • scale (float, optional) – The re-scaling factor for uniform random numbers in [0,1]. Defaults to 2.0.

  • shift (float, optional) – The shift value for uniform random numbers [0,1]. Defaults to -1.0.

  • device (Device) – Torch device to run on. Defaults to CPU.

Returns:

A tuple containing the input tensor x of shape (N, sizex) and the output (num_samples, N).

Return type:

Tuple[Tensor, Tensor]

generate_samples_b_fat(d, S, seed=None)[source]

Generate S unique samples of b from {0, 1}^d.

Parameters:
  • d (int) – Number of input data samples for shattering.

  • S (int) – Number of binary samples to check shattering (for scalability if d is large).

  • seed (int, optional) – The random seed. Defaults to None.

Returns:

An array of shape (S, d) containing unique samples of b.

Return type:

Array

generate_samples_r_fat(d, S, seed=None)[source]

Generate S samples of r from [0, 1]^d using Latin Hypercube Sampling.

Parameters:
  • d (int) – Dimension of the feature space.

  • S (int) – Number of samples to generate.

  • seed (int, optional) – The random seed. Defaults to None.

Returns:

An array of shape (S, d) containing samples of r.

Return type:

Array

gen_synthetic_features(d, sizex, seed=None, scale=2.0, shift=-1.0, device=device(type='cpu'))[source]

Generates d inputs x of dimension sizex sampled uniformly from scale*[0,1]+shift.

Parameters:
  • d (int) – The number of inputs x to generate.

  • sizex (int) – The size of each input.

  • seed (int, optional) – The random seed to use for generating the features. Defaults to None.

  • scale (float, optional) – The re-scaling factor for uniform random numbers in [0,1]. Defaults to 2.0.

  • shift (float, optional) – The shift value for uniform random numbers [0,1]. Defaults to -1.0.

  • device (Device) – Torch device to run on. Defaults to CPU.

Returns:

Tensor X of shape (d, sizex).

Return type:

Tensor

gen_synthetic_features_normal(d, sizex, seed=None, scale=1.0, shift=0.0, device=device(type='cpu'))[source]

Generates d inputs x of dimension sizex sampled from N(shift, scale^2).

Parameters:
  • d (int) – The number of inputs x to generate.

  • sizex (int) – The size of each input.

  • seed (int, optional) – The random seed to use for generating the features. Defaults to None.

  • scale (float, optional) – The re-scaling factor for uniform random numbers in [0,1]. Defaults to 1.0.

  • shift (float, optional) – The shift value for uniform random numbers [0,1]. Defaults to 0.0.

  • device (Device, optional) – Torch device to run on. Defaults to CPU.

Returns:

Tensor X of shape (d, sizex).

Return type:

Tensor

gen_synthetic_labels_fat(b, r, gamma=0.0, device=device(type='cpu'))[source]

Generate constant label values equal to r_i + gamma when b_i = 1 and r_i - gamma when b_i = 0.

Parameters:
  • b (Array) – An array of shape (Sb,d) containing Sb samples of d-dim binary values.

  • r (Array) – An array of shape (Sr,d) containing Sr samples of d-dim real values in [0, 1].

  • gamma (float, optional) – The fat-shattering margin value. Defaults to 0.0.

  • device (Device, optional) – Torch device to run on. Defaults to CPU.

Returns:

Y of shape (Sr, Sb, d, 1).

Return type:

Tensor

Raises:

ValueError – If the length of b[0] is not the same as the length of r[0].

gen_sigmas(m, seed=None, device=device(type='cpu'))[source]

Random vector of +-1.

Parameters:
  • m (int) – Number of sigmas.

  • seed (int, optional) – The random seed to use for generating the features. Defaults to None.

  • device (Device, optional) – Torch device to run on. Defaults to CPU.

Returns:

Tensor of sigmas.

Return type:

Tensor

generate_lhs_samples(n_samples, n_dims, lower_bound, upper_bound, seed=None)[source]

Generate Latin Hypercube Samples (LHS) within the specified range.

Parameters:
  • n_samples (int) – The number of samples to generate.

  • n_dims (int) – The number of dimensions for each sample.

  • lower_bound (float) – The lower bound for the samples.

  • upper_bound (float) – The upper bound for the samples.

  • seed (int, optional) – The random seed. Defaults to None.

Returns:

A numpy array containing the generated samples.

Return type:

Array

generate_model_lhs_samples(model, n_samples, lower_bound, upper_bound, device=None, dtype=None, seed=None)[source]

Generate Latin Hypercube Samples (LHS) for each parameter of a given model.

Parameters:
  • model (Model) – The model whose parameters to sample.

  • n_samples (int) – The number of samples to generate.

  • lower_bound (float) – The lower bound for the samples.

  • upper_bound (float) – The upper bound for the samples.

  • cdevice (CDevice, optional) – Classical device to store the parameters, defaults to None.

  • dtype (DType, optional) – Data type of the parameters, defaults to None.

  • seed (int, optional) – The random seed. Defaults to None.

Returns:

A list of lists containing samples for each parameter.

Return type:

ParameterList

fat_shattering_dim(model, datagen, trainer, dmin, dmax, gamma=0.0, dstep=1)[source]

Estimate the fat-shattering dimension for a model with a given architecture.

Parameters:
  • model (QModel) – The model.

  • datagen (Datagen) – The (synthetic) data generator.

  • trainer (Trainer) – The trainer.

  • dmin (int) – Iteration start for dimension check.

  • dmax (int) – Iteration stop for dimension check (including).

  • gamma (float, optional) – The margin value. Defaults to 0.0 (pseudo-dim).

  • dstep (int) – Dimension iteration step size. Defaults to 1.

Returns:

The estimated fat-shattering dimension.

Return type:

int

check_shattering(model, datagen, trainer, d, gamma)[source]

Check if the model shatters a given dimension d with margin value gamma.

Parameters:
  • model (QModel) – The model.

  • datagen (Datagen) – The (synthetic) data generator.

  • trainer (Trainer) – The trainer.

  • d (int) – Size of data set to shatter.

  • gamma (float) – The margin value.

Returns:

True if the model shatters a random data set of size d, False otherwise.

Return type:

bool

normalize_const(weights, gamma, Rx)[source]

Compute a normalization constant given a tensor of weights and the margin parameter gamma.

Rationale: the fat-shattering dimension of a linear classifier, with weights bounded by Rw and data bounded by Rx, is bounded by <= Rw^2*Rx^2/gamma^2. Hence, normalizing the fat-shattering dimension of a model with unbounded weights compares it to the best linear classifier with the same weight norm.

Parameters:
  • weights (Tensor) – Tensor of weights

  • gamma (float) – Margin parameter.

  • Rx (float) – Estimated 2-radius of input data.

Returns:

A positive real-valued normalization constant.

Return type:

float

class RademacherLoss(sigmas)[source]

Computes the loss function required to estimate emprical Rademacher complexity.

Parameters:

sigmas (Tensor) – 1D Tensor of sigmas.

forward(output, _=None)[source]

Compute loss = -1/m * sum_k sigma_k*f_k.

Parameters:
  • output (Tensor) – Predicted value tensor.

  • _ (Tensor) – Ignored. Defaults to None.

Returns:

Loss value.

Return type:

Tensor

Raises:

ValueError – If output not a 1D Tensor, or not the same length as sigmas.

_check_sigmas(sigmas)[source]

Ensures sigmas has the expected format.

Parameters:

sigmas (Tensor) – sigmas Tensor.

Return type:

None

Returns:

None

Raises:

ValueError – If sigmas has invalid shape or values.

memory(model, datagen, trainer, Nmin, Nmax, Nstep=1, early_stop=True, stop_count=1)[source]

Estimates the memory capacity of a model over a range of values of N.

Parameters:
  • model (Model) – The model.

  • datagen (Datagen) – The (synthetic) data generator.

  • trainer (Trainer) – The trainer.

  • Nmin (int) – The minimum value of N.

  • Nmax (int) – The maximum value of N, included.

  • Nstep (int, optional) – Step size for N. Defaults to 1.

  • early_stop (bool, optional) – Stops early if previous stop_count iterations capacity at least as large. Defaults to True.

  • stop_count (int, optional) – See early_stop. Defaults to 1.

Returns:

List of tuples (N, mre=2^(-m), m, N*m).

Return type:

Capacity

See also

arXiv:1908.01364.

fit_rand_labels(model, datagen, trainer, N)[source]

Fits random labels to a model and returns the mean relative error.

Parameters:
  • model (Model) – The model.

  • datagen (Datagen) – The data generation class.

  • trainer (Trainer) – The trainer.

  • N (int) – The number of inputs.

Returns:

The mean relative error.

Return type:

float

parity_all_hamiltonian(num_qubits, weights)[source]

Hamiltonian corresponding to the parity of all combinations of Pauli Z operators.

Parameters:
  • num_qubits (int) – Number of qubits.

  • weights (Tensor) – Observable weights of shape (2^num_qubits,)

Returns:

Observable corresponding to the parity of Pauli Z operators

Return type:

Observable

Raises:

ValueError – If shape of weights is not as specified above.

parities_all_observables(n)[source]

Generates a list of observables corresponding to the parity of all possible binary combinations of n qubits.

Parameters:

n (int) – The number of qubits.

Returns:

A list of observables corresponding to the parity of all possible binary combinations of n qubits plus Idenity.

Return type:

List[Observable]

sequence2parity_observable(parity_sequence)[source]

Generates a list of observables corresponding to the parity of the indeces defined by the sequence.

Parameters:

parity_sequence (ParitySequence) – The sequence of Z parities.

Returns:

A list of observables corresponding to the parity of all possible binary combinations of n qubits plus Idenity.

Return type:

List[Observable]

class MeasurementType(value)[source]

Measurement type for a measurement layer.

Expectation = 'expectation'

return vector of probabilities.

Type:

Probabilities

Probabilities = 'probabilities'

return measurement samples.

Type:

Samples

Samples = 'samples'

calculate the von Neumann entropy of a subsystem.

Type:

Entropy

class CircuitLayer(wires)[source]

Base class for a quantum circuit layer.

A circuit layer transforms a quantum state but does not perform any measurements. Thus, a circuit layer produces no classical output. It can be combined with a measurement layer that returns classical output. By default, the base class does nothing (zero state). Derived classes need to override circuit().

Parameters:

wires (Wires) – Number or list of circuits.

forward(x)[source]

Forward pass. See circuit()

Return type:

None

circuit(_)[source]

Applies input-dependent unitary transformations to a circuit.

Parameters:

x (Tensor.) – Input data samples.

Returns:

None for the base class.

Return type:

None.

set_wires(wires)[source]

Set circuit (qubit) wires.

Return type:

None

class IQPEmbeddingLayer(wires, n_repeat=1, **kwargs)[source]

Layer for IQP (Instantaneous Quantum Polynomial) embedding.

Parameters:
  • wires (Wires) – The wires to be used by the layer

  • n_repeat (int, optional) – The number of times to repeat the IQP embedding, defaults to 1

  • kwargs – Extra arguments passed to the IQP embedding

circuit(x)[source]

Define the quantum circuit for this layer.

Parameters:

x (Tensor) – Input tensor that is passed to the quantum circuit.

Return type:

None

class HatBasisQFE(wires, basis, sqrt=False, normalize=False)[source]

Layer for the 1D hat basis quantum feature embedding.

Parameters:
  • basis (HatBasis) – The hat basis class.

  • wires (Wires) – The wires to be used by the layer

  • sqrt (bool) – Set flag to take square roots before applying hat basis.

  • normalize (bool) – Set flag to normalize basis vector before embedding.

circuit(x)[source]

Define the quantum circuit for this layer.

Parameters:

x (Tensor) – Input tensor that is passed to the quantum circuit.

Return type:

None

compute_norm(x)[source]

Compute the norm of the basis vector for the given input x.

Parameters:

x (Tensor) – Input tensor that is passed to basis vector.

Returns:

The norm.

Return type:

float

class Linear2DBasisQFE(wires, basis, sqrt=False, normalize=False, zorder=False)[source]

Layer for the 2D hat basis quantum feature embedding.

Parameters:
  • basis (HatBasis) – The 1D hat basis class.

  • wires (Wires) – The wires to be used by the layer

  • sqrt (bool) – Set flag to take square roots before applying hat basis.

  • normalize (bool) – Set flag to normalize basis vector before embedding.

circuit(x)[source]

Define the quantum circuit for this layer.

Parameters:

x (Tensor) – Input tensor that is passed to the quantum circuit.

Return type:

None

compute_norm(x)[source]

Compute the norm of the basis vector for the given input x.

Parameters:

x (Tensor) – Input tensor that is passed to basis vector.

Returns:

The norm.

Return type:

float

class RYCZLayer(wires, n_layers=1, cdevice=None, dtype=None, **kwargs)[source]

Layer for the RYCZ (Rotation around Y and Controlled-Z) gates.

Parameters:
  • wires (Wires) – The wires to be used by the layer.

  • n_layers (int, optional) – The number of layers for the simplified two-design architecture, defaults to 1.

  • cdevice (CDevice, optional) – Classical device to store the initial layer weights and internal layer weights, defaults to None.

  • dtype (DType, optional) – Data type of the weights, defaults to None.

  • kwargs – Extra arguments passed to the SimplifiedTwoDesign.

circuit(_=None)[source]

Define the quantum circuit for this layer.

Parameters:

_ – Input tensor that is passed to the quantum circuit (ignored).

Return type:

None

class AltRotCXLayer(wires, n_layers=1, cdevice=None, dtype=None, **kwargs)[source]

Layer for alternating CNOT gates with universal 1-qubit rotation.

Parameters:
  • wires (Wires) – The wires to be used by the layer.

  • n_layers (int, optional) – The number of layers for the simplified two-design architecture, defaults to 1.

  • cdevice (CDevice, optional) – Classical device to store the initial layer weights and internal layer weights, defaults to None.

  • dtype (DType, optional) – Data type of the weights, defaults to None.

  • kwargs – Extra arguments passed to the SimplifiedTwoDesign.

circuit(_=None)[source]

Define the quantum circuit for this layer.

Parameters:

_ (Optional[Tensor]) – Input tensor that is passed to the quantum circuit (ignored).

Return type:

None

class AltRXCXLayer(wires, n_layers=1, cdevice=None, dtype=None, **kwargs)[source]

Layer for alternating CNOT gates with RX rotations.

Parameters:
  • wires (Wires) – The wires to be used by the layer.

  • n_layers (int, optional) – The number of layers for the simplified two-design architecture, defaults to 1.

  • cdevice (CDevice, optional) – Classical device to store the initial layer weights and internal layer weights, defaults to None.

  • dtype (DType, optional) – Data type of the weights, defaults to None.

  • kwargs – Extra arguments passed to the SimplifiedTwoDesign.

circuit(_=None)[source]

Define the quantum circuit for this layer.

Parameters:

_ (Optional[Tensor]) – Input tensor that is passed to the quantum circuit (ignored).

Return type:

None

class IQPERYCZLayer(wires, num_uploads=1, num_varlayers=1, num_repeat=1, base=tensor(1.), omega=tensor(0.), cdevice=None, dtype=None, iqpe_opts={}, rycz_opts={})[source]

Layer combining an IQP embedding layer and an RY-CZ variational layer.

Parameters:
  • wires (Wires) – The wires to be used by the layer.

  • num_uploads (int, optional) – The number of times to repeat data uploading, defaults to 1.

  • num_varlayers (int, optional) – The number of times to repeat the variational layer, defaults to 1.

  • num_repeat (int, optional) – The number of times to repeat the combined layers, defaults to 1.

  • base (float, optional) – The base of the exponent by which the inputs are scaled on each repetition, defaults to 1.0

  • omega (float, optional) – The exponent for the base of the power by which the inputs are scaled on each repetition, defaults to 0.0

  • cdevice (CDevice, optional) – Classical device to store the observable weights. If None specified, the default device is used.

  • dtype (DType, optional) – Data type of the variational weights.

  • iqpe_opts (Dict, optional) – Options for the IQPE class. Defaults to empty.

  • rycz_opts (Dict, optional) – Options for the RYCZLayer class. Defaults to empty.

circuit(x)[source]

Define the quantum circuit for this layer.

Parameters:

x (Tensor) – Input tensor that is passed to the quantum circuit.

Return type:

None

class IQPEAltRotCXLayer(wires, num_uploads=1, num_varlayers=1, num_repeat=1, base=tensor(1.), omega=tensor(0.), cdevice=None, dtype=None, iqpe_opts={}, altrotcx_opts={})[source]

Layer combining an IQP embedding layer and an alternating U3-CX variational layer.

Parameters:
  • wires (Wires) – The wires to be used by the layer.

  • num_uploads (int, optional) – The number of times to repeat data uploading, defaults to 1.

  • num_varlayers (int, optional) – The number of times to repeat the variational layer, defaults to 1.

  • num_repeat (int, optional) – The number of times to repeat the combined layers, defaults to 1.

  • base (float, optional) – The base of the exponent by which the inputs are scaled on each repetition, defaults to 1.0

  • omega (float, optional) – The exponent for the base of the power by which the inputs are scaled on each repetition, defaults to 0.0

  • cdevice (CDevice, optional) – Classical device to store the observable weights. If None specified, the default device is used.

  • dtype (DType, optional) – Data type of the variational weights.

  • iqpe_opts (Dict, optional) – Options for the IQPE class. Defaults to empty.

  • altrotcx_opts (Dict, optional) – Options for the AltRotCXLayer class. Defaults to empty.

circuit(x)[source]

Define the quantum circuit for this layer.

Parameters:

x (Tensor) – Input tensor that is passed to the quantum circuit.

Return type:

None

class HadamardLayer(wires)[source]

A layer that adds Hadamard gates to each wire.

Parameters:

wires (Wires) – The wires to be used by the layer.

circuit(_=None)[source]

Apply the quantum circuit for this layer.

Parameters:

_ (Optional[Tensor]) – Input tensor that is passed to the quantum circuit (ignored).

Return type:

None

class ParallelIQPEncoding(wires, num_features, n_repeat=1, base=tensor(1.), omega=tensor(0.), **kwargs)[source]

A class that applies the IQPEmbedding to different parts of the input data.

Parameters:
  • wires (Wires) – The wires on which the circuit will be applied

  • num_features (int) – The number of features in the input

  • n_repeat (int, optional) – The number of times the IQPEmbedding will be repeated, defaults to 1

  • base (float, optional) – The base of the exponent by which the inputs are scaled on each repetition, defaults to 1.0

  • omega (float, optional) – The exponent for the base of the power by which the inputs are scaled on each repetition, defaults to 0.0

Raises:
  • ValueError – If the number of wires is less than the number of features

  • ValueError – If the number of wires is not a multiple of the number of features

circuit(x)[source]

Apply the quantum circuit for this layer.

Parameters:

x (Tensor) – Input tensor that is passed to the quantum circuit.

Return type:

None

class ParallelEntangledIQPEncoding(wires, num_features, n_repeat=1, base=tensor(1.), omega=tensor(0.), **kwargs)[source]

A class that applies the IQPEmbedding on the entire constructed large feature vector.

Parameters:
  • wires (Wires) – The wires on which the circuit will be applied

  • num_features (int) – The number of features in the input

  • n_repeat (int, optional) – The number of times the IQPEmbedding will be repeated, defaults to 1

  • base (float, optional) – The base of the exponent by which the inputs are scaled on each repetition, defaults to 1.0

  • omega (float, optional) – The exponent for the base of the power by which the inputs are scaled on each repetition, defaults to 0.0

Raises:
  • ValueError – If the number of wires is less than the number of features

  • ValueError – If the number of wires is not a multiple of the number of features

circuit(x)[source]

Apply the quantum circuit for this layer.

Parameters:

x (Tensor) – Input tensor that is passed to the quantum circuit.

Return type:

None

class TwoQubitRotCXMPSLayer(wires, n_layers_mps=1, n_layers_block=1, reverse=False, cdevice=None, dtype=None)[source]

Layer with 2-qubit MPS sctructure.

Parameters:
  • wires (Wires) – The wires to be used by the layer.

  • n_layers_mps (int) – The number of layers to repeat the MPS, defaults to 1.

  • n_layers_block (int, optional) – The number of layers for each block of the MPS, defaults to 1.

  • reverse (bool, optional) – Flag to reverse the MPS sequence to bottom to top, defaults to False.

  • cdevice (CDevice, optional) – Classical device to store the initial layer weights and internal layer weights, defaults to None.

  • dtype (DType, optional) – Data type of the weights, defaults to None.

circuit(_=None)[source]

Define the quantum circuit for this layer.

Parameters:

_ – Input tensor that is passed to the quantum circuit (ignored).

Return type:

None

class EmbedU(wires, U)[source]

Layer that embeds an arbitrary unitary.

Parameters:
  • wires (Wires) – The wires to be used by the layer.

  • U (Tensor.) – The unitary to embed.

circuit(_=None)[source]

Define the quantum circuit for this layer.

Parameters:

_ – Input tensor that is passed to the quantum circuit (ignored).

Return type:

None

class MeasurementLayer(*circuits, qdevice=None, measurement_type=MeasurementType.Probabilities, observables=None, **kwargs)[source]

Base class for measurment layers.

Measurement layers are appended to quantum circuits and return classical output.

Parameters:
  • circuits (tuple) – Quantum circuits before the measurement.

  • qdevice (Optional[QDevice], defaults to None) – Quantum device. If None, the default device will be used.

  • measurement_type (MeasurementType, defaults to MeasurementType.Probabilities) – Type of quantum measurement.

  • observables (Optional[Observables], defaults to None) – Observables to measure. None only works with Probabilities and Samples.

  • kwargs – Additional keyword arguments for qml.QNode.

forward(x=None)[source]

Forward pass, depending on measurement type. See expectation(), probabilities() and samples().

Parameters:

x (Optional[Tensor]) – Input data samples.

Returns:

Forward evaluation of model on data.

Return type:

Tensor

expectation(x=None)[source]

Calculate the expectation value of the observable for given circuits.

Parameters:

x (Optional[Tensor]) – Input tensor that is passed to the quantum circuits, defaults to None.

Returns:

Expectation value object for the observable.

Return type:

Expectation

probabilities(x=None)[source]

Calculate the outcome probabilities for given circuits.

Parameters:

x (Optional[Tensor]) – Input tensor that is passed to the quantum circuits, defaults to None.

Returns:

Probabilities of the outcomes of the circuits.

Return type:

Probability

samples(x=None)[source]

Sample the outcomes of the given circuits.

Parameters:

x (Optional[Tensor]) – Input tensor that is passed to the quantum circuits, defaults to None.

Returns:

Samples of the outcomes of the circuits.

Return type:

Sample

entropy(x=None)[source]

Calculate the Von Neumann Entropy of a subsystem.

Parameters:

x (Optional[Tensor]) – Input tensor that is passed to the quantum circuits, defaults to None.

Returns:

Entropy value object for a subsystem.

Return type:

Entropy

set_qnode()[source]

Set the quantum node for the layer and measurement type.

Returns:

The set QNode.

Return type:

QNode

check_measurement_type()[source]

Check if the measurement type is valid. Raises errors for invalid measurement types.

Raises:
  • NotImplementedError – If the measurement type is not recognized.

  • ValueError – If the expectation measurement type doesn’t have an observable, or if the sample measurement type doesn’t have an integer number of shots.

Return type:

None

class HamiltonianLayer(*circuits, observables, qdevice=None, cdevice=None, dtype=None, **kwargs)[source]

A layer that computes the expectation of a Hamiltonian.

The Hamiltonian is defined by a list of observables and their associated weights. The weights are trainable parameters.

Parameters:
  • circuits (tuple) – Quantum circuits that make up the circuit layer before measurement.

  • observables (list of Observable) – Observables defining the Hamiltonian.

  • qdevice (Optional[QDevice]) – Quantum device. If None specified, the default device is used.

  • cdevice (CDevice, optional) – Classical device to store the observable weights. If None specified, the default device is used.

  • dtype (DType, optional) – Data type of the observable weights.

  • kwargs – Additional keyword arguments passed to the superclass.

expectation(x=None)[source]

Compute the expectation of the Hamiltonian.

Parameters:

x (Optional[Tensor]) – Input tensor, defaults to None.

Returns:

Expectation value of the Hamiltonian.

Return type:

Expectation

rademacher(model, trainer, X, sigmas, datagen)[source]

Estimate Rademacher complexity of a given model.

Parameters:
  • model (QModel) – Prediction model.

  • trainer (Trainer) – The trainer.

  • X (Tensor) – Data tensor of size (num_data_samples, size_data_set, dim_feature)

  • sigmas (Tensor) – Sigmas tensor of size (num_sigma_samples, size_data_set)

  • datagen (Datagen) – Datagen object for converting to loader.

Returns:

Scalar-valued tensor with Rademacher complexity.

Return type:

Tensor

class EpochType(value)[source]

Enum to denote the type of epoch in the training process.

Variables:
  • Train – Indicates the epoch is a training epoch.

  • Validate – Indicates the epoch is a validation epoch.

class SupervisedTrainer(optimizer, loss_fn, num_epochs, metrics={}, writer=None, logger=None)[source]

Class to handle the training of a supervised learning model.

Parameters:
  • optimizer (Optimizer) – The optimizer to be used in the training process.

  • loss_fn (Loss) – The loss function used for optimization.

  • num_epochs (int) – The number of epochs to train for.

  • metrics (Dict[str, Metric], optional) – A dictionary mapping metric names to the metric functions to be evaluated. Defaults to empty dict.

  • writer (Optional[Writer]) – An optional writer for logging purposes. Default is None.

  • logger (Optional[Logger]) – An optional logger for logging purposes. Default is None.

train(model, train_data, valid_data)[source]

Train the given model using the provided data loaders.

Parameters:
  • model (Model) – The model to be trained.

  • train_data (DataLoader) – The DataLoader for the training data.

  • valid_data (DataLoader) – The DataLoader for the validation data.

Return type:

None

train_epoch(model, train_data, epoch=0)[source]

Train the model for one epoch.

Parameters:
  • model (Model) – The model to be trained.

  • train_data (DataLoader) – The DataLoader for the training data.

  • epoch (int) – The current epoch number. Default is 0.

Return type:

None

validate_epoch(model, valid_data, epoch=0)[source]

Validate the model after an epoch of training.

Parameters:
  • model (Model) – The model to be validated.

  • valid_data (DataLoader) – The DataLoader for the validation data.

  • epoch (int) – The current epoch number. Default is 0.

Return type:

None

class RidgeRegression(lambda_reg, metrics={}, logger=None)[source]

Class to handle the training of a model using Ridge Regression.

Parameters:
  • lambda_reg (float) – Regularization strength. Must be positive.

  • metrics (Dict[str, Metric], optional) – A dictionary mapping metric names to the metric functions to be evaluated. Defaults to empty dict.

  • logger (Optional[Logger]) – An optional logger for logging purposes. Default is None.

train(model, train_data, valid_data)[source]

Train the given model using the provided data loaders using Ridge Regression.

Parameters:
  • model (QKernel) – The quantum kernel model to be trained.

  • train_data (DataLoader) – The DataLoader for the training data.

  • valid_data (DataLoader) – The DataLoader for the validation data.

Return type:

None

Warning

Training changes the state of the model by assigning X_train.

kernel_ridge_regression(model, inputs, labels)[source]

Compute Ridge Regression solution for the given inputs and labels using the provided model.

Parameters:
  • model (QKernel) – The quantum kernel model.

  • inputs (Tensor) – Input data tensor.

  • labels (Tensor) – Corresponding labels tensor.

Returns:

The computed alpha parameter tensor.

Return type:

Parameter

_log_metrics(phase, metrics)[source]

Log computed metrics for the provided phase.

Parameters:
  • phase (str) – The phase (train or validate) being logged.

  • metrics (Dict[str, float]) – Dictionary of computed metrics.

Return type:

None

Frequently used functions.

probabilities_to_dictionary(probs)[source]

Convert 1D tensor of probabilities to dictionary of probabilities of bitstrings.

Parameters:

probs (Tensor) – Probabilities.

Returns:

Probabilities of bitstrings.

Return type:

Dict

Raises:

ValueError – If length of probs is not a power of 2.

samples_to_dictionary(samples)[source]

Convert 2D tensor of samples to dictionary of probabilities of bitstrings.

Parameters:

samples (Tensor) – Samples.

Returns:

Probabilities of bitstrings.

Return type:

Dict

Raises:

ValueError – If samples not a Tensor of integers.

all_bin_sequences(n)[source]

Generates all possible binary sequences of length n.

Parameters:

n (int) – The length of the binary sequences.

Returns:

A list of all binary sequences of length n, represented as a list of integers.

Return type:

List[List[int]]

parities_outcome(bitstring, H)[source]

Compute the measurement outcome for a given bit string and Hamiltonian. Only works for Hamiltonians with identity and Pauli Z.

Parameters:
  • bitstring (string: str) – Input bit string.

  • H (Observable) – Hamiltonian.

Returns:

Real-valued outcome.

Return type:

float

Raises:

ValueError – If number of qubits does not match or operators other than I or Z are detected.

parities_outcome_probs(probs, H)[source]

Compute (real-valued) outputs with corresponding probabilities.

Parameters:
  • probs (Dict) – Dictionary of probabilities of bitstrings.

  • H (Observable) – Hamiltonian determening the outcome.

Returns:

Values with corresponding probabilities.

Return type:

Dict