Quantum models
QuantumModel(circuit, observable=None, backend=BackendName.PYQTORCH, diff_mode=DiffMode.AD, measurement=None, noise=None, mitigation=None, configuration=None)
Bases: Module
The central class of qadence that executes QuantumCircuit
s and make them differentiable.
This class should be used as base class for any new quantum model supported in the qadence framework for information on the implementation of custom models see here.
Example:
import torch
from qadence import QuantumModel, QuantumCircuit, RX, RY, Z, PI, chain, kron
from qadence import FeatureParameter, VariationalParameter
theta = VariationalParameter("theta")
phi = FeatureParameter("phi")
block = chain(
kron(RX(0, theta), RY(1, theta)),
kron(RX(0, phi), RY(1, phi)),
)
circuit = QuantumCircuit(2, block)
observable = Z(0) + Z(1)
model = QuantumModel(circuit, observable)
values = {"phi": torch.tensor([PI, PI/2]), "theta": torch.tensor([PI, PI/2])}
wf = model.run(values)
xs = model.sample(values, n_shots=100)
ex = model.expectation(values)
print(wf)
print(xs)
print(ex)
tensor([[ 1.0000e+00+0.0000e+00j, -1.2246e-16+0.0000e+00j,
0.0000e+00+1.2246e-16j, 0.0000e+00-1.4998e-32j],
[ 4.9304e-32+0.0000e+00j, 2.2204e-16+0.0000e+00j,
0.0000e+00-2.2204e-16j, 0.0000e+00-1.0000e+00j]])
[OrderedCounter({'00': 100}), OrderedCounter({'11': 100})]
tensor([[ 2.],
[-2.]], requires_grad=True)
Initialize a generic QuantumModel instance.
PARAMETER | DESCRIPTION |
---|---|
circuit
|
The circuit that is executed.
TYPE:
|
observable
|
Optional observable(s) that are used only in the
TYPE:
|
backend
|
A backend for circuit execution.
TYPE:
|
diff_mode
|
A differentiability mode. Parameter shift based modes work on all backends. AD based modes only on PyTorch based backends.
TYPE:
|
measurement
|
Optional measurement protocol. If None, use exact expectation value with a statevector simulator.
TYPE:
|
configuration
|
Configuration for the backend.
TYPE:
|
noise
|
A noise model to use.
TYPE:
|
RAISES | DESCRIPTION |
---|---|
ValueError
|
if the |
Source code in qadence/model.py
device
property
Get device.
RETURNS | DESCRIPTION |
---|---|
device
|
torch.device |
in_features
property
Number of inputs.
num_vparams
property
The number of variational parameters.
out_features
property
Number of outputs.
vals_vparams
property
Dictionary with parameters which are actually updated during optimization.
vparams
property
Variational parameters.
assign_parameters(values)
Return the final, assigned circuit that is used in e.g. backend.run
.
PARAMETER | DESCRIPTION |
---|---|
values
|
Values dict which contains values for the parameters.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
Any
|
Final, assigned circuit that is used in e.g. |
Source code in qadence/model.py
circuit(circuit)
Get backend-converted circuit.
PARAMETER | DESCRIPTION |
---|---|
circuit
|
QuantumCircuit instance.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
ConvertedCircuit
|
Backend circuit. |
expectation(values={}, observable=None, state=None, measurement=None, noise=None, mitigation=None, endianness=Endianness.BIG)
Compute expectation using the given backend.
Given an input state \(|\psi_0 \rangle\), a set of variational parameters \(\vec{\theta}\) and the unitary representation of the model \(U(\vec{\theta})\) we return \(\langle \psi_0 | U(\vec{\theta}) | \psi_0 \rangle\).
PARAMETER | DESCRIPTION |
---|---|
values
|
Values dict which contains values for the parameters.
TYPE:
|
observable
|
Observable part of the expectation.
TYPE:
|
state
|
Optional input state.
TYPE:
|
measurement
|
Optional measurement protocol. If None, use exact expectation value with a statevector simulator.
TYPE:
|
noise
|
A noise model to use.
TYPE:
|
mitigation
|
A mitigation protocol to use.
TYPE:
|
endianness
|
Storage convention for binary information.
TYPE:
|
RAISES | DESCRIPTION |
---|---|
ValueError
|
when no observable is set. |
RETURNS | DESCRIPTION |
---|---|
Tensor
|
A torch.Tensor of shape n_batches x n_obs |
Source code in qadence/model.py
forward(*args, **kwargs)
Calls run method with arguments.
RETURNS | DESCRIPTION |
---|---|
Tensor
|
A torch.Tensor representing output.
TYPE:
|
load(file_path, as_torch=False, map_location='cpu')
classmethod
Load QuantumModel.
PARAMETER | DESCRIPTION |
---|---|
file_path
|
File path to load model from.
TYPE:
|
as_torch
|
Load parameters as torch tensor. Defaults to False.
TYPE:
|
map_location
|
Location for loading. Defaults to "cpu".
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
QuantumModel
|
QuantumModel from file_path. |
Source code in qadence/model.py
load_params_from_dict(d, strict=True)
Copy parameters from dictionary into this QuantumModel.
Unlike :meth:~qadence.QuantumModel.from_dict
, this method does not create a new
QuantumModel instance, but rather loads the parameters into the same QuantumModel.
The behaviour of this method is similar to :meth:~torch.nn.Module.load_state_dict
.
The dictionary is assumed to have the format as saved via
:meth:~qadence.QuantumModel.to_dict
PARAMETER | DESCRIPTION |
---|---|
d
|
The dictionary
TYPE:
|
strict
|
Whether to strictly enforce that the parameter keys in the dictionary and
in the model match exactly. Default:
TYPE:
|
Source code in qadence/model.py
observable(observable, n_qubits)
Get backend observable.
PARAMETER | DESCRIPTION |
---|---|
observable
|
Observable block.
TYPE:
|
n_qubits
|
Number of qubits
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
Any
|
Backend observable. |
Source code in qadence/model.py
overlap()
Overlap of model.
RAISES | DESCRIPTION |
---|---|
NotImplementedError
|
The overlap method is not implemented for this model. |
reset_vparams(values)
Reset all the variational parameters with a given list of values.
Source code in qadence/model.py
run(values=None, state=None, endianness=Endianness.BIG)
Run model.
Given an input state \(| \psi_0 \rangle\), a set of variational parameters \(\vec{\theta}\) and the unitary representation of the model \(U(\vec{\theta})\) we return \(U(\vec{\theta}) | \psi_0 \rangle\).
PARAMETER | DESCRIPTION |
---|---|
values
|
Values dict which contains values for the parameters.
TYPE:
|
state
|
Optional input state to apply model on.
TYPE:
|
endianness
|
Storage convention for binary information.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
Tensor
|
A torch.Tensor representing output. |
Source code in qadence/model.py
sample(values={}, n_shots=1000, state=None, noise=None, mitigation=None, endianness=Endianness.BIG)
Obtain samples from model.
PARAMETER | DESCRIPTION |
---|---|
values
|
Values dict which contains values for the parameters.
TYPE:
|
n_shots
|
Observable part of the expectation.
TYPE:
|
state
|
Optional input state to apply model on.
TYPE:
|
noise
|
A noise model to use.
TYPE:
|
mitigation
|
A mitigation protocol to use.
TYPE:
|
endianness
|
Storage convention for binary information.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
list[Counter]
|
A list of Counter instances with the sample results. |
Source code in qadence/model.py
save(folder, file_name='quantum_model.pt', save_params=True)
Save model.
PARAMETER | DESCRIPTION |
---|---|
folder
|
Folder where model is saved.
TYPE:
|
file_name
|
File name for saving model. Defaults to "quantum_model.pt".
TYPE:
|
save_params
|
Save parameters if True. Defaults to True.
TYPE:
|
RAISES | DESCRIPTION |
---|---|
FileNotFoundError
|
If folder is not a directory. |
Source code in qadence/model.py
to(*args, **kwargs)
Conversion method for device or types.
RETURNS | DESCRIPTION |
---|---|
QuantumModel
|
QuantumModel with conversions. |