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)
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: torch.device
property
Get device.
RETURNS | DESCRIPTION |
---|---|
device
|
torch.device |
in_features: int
property
Number of inputs.
num_vparams: int
property
The number of variational parameters.
out_features: int | None
property
Number of outputs.
vals_vparams: Tensor
property
Dictionary with parameters which are actually updated during optimization.
vparams: OrderedDict
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
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. |
Source code in qadence/model.py
Bases: QuantumModel
Quantum neural network model for n-dimensional inputs.
Examples:
import torch
from qadence import QuantumCircuit, QNN, Z
from qadence import hea, feature_map, hamiltonian_factory, kron
# create the circuit
n_qubits, depth = 2, 4
fm = kron(
feature_map(1, support=(0,), param="x"),
feature_map(1, support=(1,), param="y")
)
ansatz = hea(n_qubits=n_qubits, depth=depth)
circuit = QuantumCircuit(n_qubits, fm, ansatz)
obs_base = hamiltonian_factory(n_qubits, detuning=Z)
# the QNN will yield two outputs
obs = [2.0 * obs_base, 4.0 * obs_base]
# initialize and use the model
qnn = QNN(circuit, obs, inputs=["x", "y"])
y = qnn(torch.rand(3, 2))
Initialize the QNN.
The number of inputs is determined by the feature parameters in the input quantum circuit while the number of outputs is determined by how many observables are provided as input
PARAMETER | DESCRIPTION |
---|---|
circuit |
The quantum circuit to use for the QNN.
TYPE:
|
observable |
The observable.
TYPE:
|
backend |
The chosen quantum backend.
TYPE:
|
diff_mode |
The differentiation engine to use. Choices 'gpsr' or 'ad'.
TYPE:
|
measurement |
optional measurement protocol. If None, use exact expectation value with a statevector simulator
TYPE:
|
noise |
A noise model to use.
TYPE:
|
configuration |
optional configuration for the backend
TYPE:
|
inputs |
List that indicates the order of variables of the tensors that are passed
to the model. Given input tensors
TYPE:
|
input_diff_mode |
The differentiation mode for the input tensor.
TYPE:
|
Source code in qadence/ml_tools/models.py
forward(values=None, state=None, measurement=None, noise=None, endianness=Endianness.BIG)
Forward pass of the model.
This returns the (differentiable) expectation value of the given observable
operator defined in the constructor. Differently from the base QuantumModel
class, the QNN accepts also a tensor as input for the forward pass. The
tensor is expected to have shape: n_batches x in_features
where n_batches
is the number of data points and in_features
is the dimensionality of the problem
The output of the forward pass is the expectation value of the input
observable(s). If a single observable is given, the output shape is
n_batches
while if multiple observables are given the output shape
is instead n_batches x n_observables
PARAMETER | DESCRIPTION |
---|---|
values |
the values of the feature parameters
TYPE:
|
state |
Initial state.
TYPE:
|
measurement |
optional measurement protocol. If None, use exact expectation value with a statevector simulator
TYPE:
|
noise |
A noise model to use.
TYPE:
|
endianness |
Endianness of the resulting bit strings.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
Tensor
|
a tensor with the expectation value of the observables passed in the constructor of the model
TYPE:
|
Source code in qadence/ml_tools/models.py
from_configs(register, obs_config, fm_config=FeatureMapConfig(), ansatz_config=AnsatzConfig(), backend=BackendName.PYQTORCH, diff_mode=DiffMode.AD, measurement=None, noise=None, configuration=None, input_diff_mode=InputDiffMode.AD)
classmethod
Create a QNN from a set of configurations.
PARAMETER | DESCRIPTION |
---|---|
register |
The number of qubits or a register object.
TYPE:
|
obs_config |
The configuration(s) for the observable(s).
TYPE:
|
fm_config |
The configuration for the feature map. Defaults to no feature encoding block.
TYPE:
|
ansatz_config |
The configuration for the ansatz. Defaults to a single layer of hardware efficient ansatz.
TYPE:
|
backend |
The chosen quantum backend.
TYPE:
|
diff_mode |
The differentiation engine to use. Choices are 'gpsr' or 'ad'.
TYPE:
|
measurement |
Optional measurement protocol. If None, use exact expectation value with a statevector simulator.
TYPE:
|
noise |
A noise model to use.
TYPE:
|
configuration |
Optional backend configuration.
TYPE:
|
input_diff_mode |
The differentiation mode for the input tensor.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
QNN
|
A QNN object. |
RAISES | DESCRIPTION |
---|---|
ValueError
|
If the observable configuration is not provided. |
Example:
import torch
from qadence.ml_tools.config import AnsatzConfig, FeatureMapConfig
from qadence.ml_tools import QNN
from qadence.constructors import ObservableConfig
from qadence.operations import Z
from qadence.types import (
AnsatzType, BackendName, BasisSet, ObservableTransform, ReuploadScaling, Strategy
)
register = 4
obs_config = ObservableConfig(
detuning=Z,
scale=5.0,
shift=0.0,
transformation_type=ObservableTransform.SCALE,
trainable_transform=None,
)
fm_config = FeatureMapConfig(
num_features=2,
inputs=["x", "y"],
basis_set=BasisSet.FOURIER,
reupload_scaling=ReuploadScaling.CONSTANT,
feature_range={
"x": (-1.0, 1.0),
"y": (0.0, 1.0),
},
)
ansatz_config = AnsatzConfig(
depth=2,
ansatz_type=AnsatzType.HEA,
ansatz_strategy=Strategy.DIGITAL,
)
qnn = QNN.from_configs(
register, obs_config, fm_config, ansatz_config, backend=BackendName.PYQTORCH
)
x = torch.rand(2, 2)
y = qnn(x)
Source code in qadence/ml_tools/models.py
211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 |
|