Serialization
Serialization
SerializationModel(d=dict())
dataclass
A serialization model class to serialize data from QuantumModel
s,.
torch.nn.Module
and similar structures. The data included in the
serialization logic includes: the AbstractBlock
and its children
classes, QuantumCircuit
, Register
, and sympy
expressions
(including Parameter
class from qadence.parameters
).
A children class must define the value
attribute type and how to
handle it, since it is the main property for the class to be used
by the serialization process. For instance:
@dataclass
class QuantumCircuitSerialization(SerializationModel):
value: QuantumCircuit = dataclass_field(init=False)
def __post_init__(self) -> None:
self.value = (
QuantumCircuit._from_dict(self.d)
if isinstance(self.d, dict)
else self.d
)
deserialize(d, as_torch=False)
Supported Types:
AbstractBlock | QuantumCircuit | QuantumModel | Register | torch.nn.Module Deserializes a dict to one of the supported types.
PARAMETER | DESCRIPTION |
---|---|
d |
A dict containing a serialized object.
TYPE:
|
as_torch |
Whether to transform to torch for the deserialized object.
TYPE:
|
Returns: AbstractBlock, QuantumCircuit, QuantumModel, Register, torch.nn.Module.
Examples:
import torch
from qadence import serialize, deserialize, hea, hamiltonian_factory, Z
from qadence import QuantumCircuit, QuantumModel
n_qubits = 2
myblock = hea(n_qubits=n_qubits, depth=1)
block_dict = serialize(myblock)
print(block_dict)
## Lets use myblock in a QuantumCircuit and serialize it.
qc = QuantumCircuit(n_qubits, myblock)
qc_dict = serialize(qc)
qc_deserialized = deserialize(qc_dict)
assert qc == qc_deserialized
## Finally, let's wrap it in a QuantumModel
obs = hamiltonian_factory(n_qubits, detuning = Z)
qm = QuantumModel(qc, obs, backend='pyqtorch', diff_mode='ad')
qm_dict = serialize(qm)
qm_deserialized = deserialize(qm_dict)
# Lets check if the loaded QuantumModel returns the same expectation
assert torch.isclose(qm.expectation({}), qm_deserialized.expectation({}))
{'type': 'ChainBlock', 'qubit_support': (0, 1), 'tag': 'HEA', 'blocks': [{'type': 'ChainBlock', 'qubit_support': (0, 1), 'tag': None, 'blocks': [{'type': 'KronBlock', 'qubit_support': (0, 1), 'tag': None, 'blocks': [{'type': 'RX', 'qubit_support': (0,), 'tag': None, 'parameters': {'_name_dict': {'parameter': ('533dbc7b-7a8e-4acf-b10f-91213474124d', {'name': 'theta_0', 'expression': "Parameter('theta_0')", 'symbols': {'theta_0': {'name': 'theta_0', 'trainable': 'True', 'value': '0.6084912281332678'}}})}}, 'noise': None}, {'type': 'RX', 'qubit_support': (1,), 'tag': None, 'parameters': {'_name_dict': {'parameter': ('fa1b0d60-19d3-49ea-8267-64432a986f84', {'name': 'theta_1', 'expression': "Parameter('theta_1')", 'symbols': {'theta_1': {'name': 'theta_1', 'trainable': 'True', 'value': '0.8684500387338262'}}})}}, 'noise': None}]}, {'type': 'KronBlock', 'qubit_support': (0, 1), 'tag': None, 'blocks': [{'type': 'RY', 'qubit_support': (0,), 'tag': None, 'parameters': {'_name_dict': {'parameter': ('81b83019-5222-44ae-a4ab-560e3999ef5b', {'name': 'theta_2', 'expression': "Parameter('theta_2')", 'symbols': {'theta_2': {'name': 'theta_2', 'trainable': 'True', 'value': '0.292065869419318'}}})}}, 'noise': None}, {'type': 'RY', 'qubit_support': (1,), 'tag': None, 'parameters': {'_name_dict': {'parameter': ('30623e79-d68b-4420-9209-5419dc386e18', {'name': 'theta_3', 'expression': "Parameter('theta_3')", 'symbols': {'theta_3': {'name': 'theta_3', 'trainable': 'True', 'value': '0.9227456102096557'}}})}}, 'noise': None}]}, {'type': 'KronBlock', 'qubit_support': (0, 1), 'tag': None, 'blocks': [{'type': 'RX', 'qubit_support': (0,), 'tag': None, 'parameters': {'_name_dict': {'parameter': ('5b1e97b4-e0b5-48d0-bbb8-ad64a8160d7a', {'name': 'theta_4', 'expression': "Parameter('theta_4')", 'symbols': {'theta_4': {'name': 'theta_4', 'trainable': 'True', 'value': '0.5292873285428984'}}})}}, 'noise': None}, {'type': 'RX', 'qubit_support': (1,), 'tag': None, 'parameters': {'_name_dict': {'parameter': ('02362c6d-88a9-4269-8439-77933940fabb', {'name': 'theta_5', 'expression': "Parameter('theta_5')", 'symbols': {'theta_5': {'name': 'theta_5', 'trainable': 'True', 'value': '0.9014234308376707'}}})}}, 'noise': None}]}]}, {'type': 'ChainBlock', 'qubit_support': (0, 1), 'tag': None, 'blocks': [{'type': 'KronBlock', 'qubit_support': (0, 1), 'tag': None, 'blocks': [{'type': 'CNOT', 'qubit_support': (0, 1), 'tag': None, 'blocks': [{'type': 'X', 'qubit_support': (1,), 'tag': None, 'noise': None}], 'noise': None}]}]}]}
Source code in qadence/serialization.py
load(file_path, map_location='cpu')
Same as serialize/deserialize but for storing/loading files.
Supported types: AbstractBlock | QuantumCircuit | QuantumModel | Register Loads a .json or .pt file to one of the supported types.
PARAMETER | DESCRIPTION |
---|---|
file_path |
The name of the file.
TYPE:
|
map_location |
In case of a .pt file, on which device to load the object (cpu,cuda).
TYPE:
|
Returns: A object of type AbstractBlock, QuantumCircuit, QuantumModel, Register.
Examples:
import torch
from pathlib import Path
import os
from qadence import save, load, hea, hamiltonian_factory, Z
from qadence import QuantumCircuit, QuantumModel
n_qubits = 2
myblock = hea(n_qubits=n_qubits, depth=1)
qc = QuantumCircuit(n_qubits, myblock)
# Lets store the circuit in a json file
save(qc, '.', 'circ')
loaded_qc = load(Path('circ.json'))
qc == loaded_qc
os.remove('circ.json')
## Let's wrap it in a QuantumModel and store that
obs = hamiltonian_factory(n_qubits, detuning = Z)
qm = QuantumModel(qc, obs, backend='pyqtorch', diff_mode='ad')
save(qm, folder= '.',file_name= 'quantum_model')
qm_loaded = load('quantum_model.json')
os.remove('quantum_model.json')
Source code in qadence/serialization.py
parse_expr_fn(code)
A parsing expressions function that checks whether a given code is valid on.
the parsing grammar. The grammar is defined to be compatible with sympy
expressions, such as Float('-0.33261030434342942', precision=53)
, while
avoiding code injection such as 2*3
or __import__('os').system('ls -la')
.
PARAMETER | DESCRIPTION |
---|---|
code |
code to be parsed and checked.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
|
Boolean indicating whether the code matches the defined grammar or not. |
Source code in qadence/serialization.py
save(obj, folder, file_name='', format=SerializationFormat.JSON)
Same as serialize/deserialize but for storing/loading files.
Supported types: AbstractBlock | QuantumCircuit | QuantumModel | Register | torch.nn.Module Saves a qadence object to a json/.pt.
PARAMETER | DESCRIPTION |
---|---|
obj |
TYPE:
|
file_name |
The name of the file.
TYPE:
|
format |
The type of file to save.
TYPE:
|
Returns: None.
Examples:
import torch
from pathlib import Path
import os
from qadence import save, load, hea, hamiltonian_factory, Z
from qadence import QuantumCircuit, QuantumModel
n_qubits = 2
myblock = hea(n_qubits=n_qubits, depth=1)
qc = QuantumCircuit(n_qubits, myblock)
# Lets store the circuit in a json file
save(qc, '.', 'circ')
loaded_qc = load(Path('circ.json'))
qc == loaded_qc
os.remove('circ.json')
## Let's wrap it in a QuantumModel and store that
obs = hamiltonian_factory(n_qubits, detuning = Z)
qm = QuantumModel(qc, obs, backend='pyqtorch', diff_mode='ad')
save(qm, folder= '.',file_name= 'quantum_model')
qm_loaded = load('quantum_model.json')
os.remove('quantum_model.json')
Source code in qadence/serialization.py
serialize(obj, save_params=False)
Supported Types:
AbstractBlock | QuantumCircuit | QuantumModel | torch.nn.Module | Register | Module Serializes a qadence object to a dictionary.
PARAMETER | DESCRIPTION |
---|---|
obj |
TYPE:
|
Returns: A dict.
Examples:
import torch
from qadence import serialize, deserialize, hea, hamiltonian_factory, Z
from qadence import QuantumCircuit, QuantumModel
n_qubits = 2
myblock = hea(n_qubits=n_qubits, depth=1)
block_dict = serialize(myblock)
print(block_dict)
## Lets use myblock in a QuantumCircuit and serialize it.
qc = QuantumCircuit(n_qubits, myblock)
qc_dict = serialize(qc)
qc_deserialized = deserialize(qc_dict)
assert qc == qc_deserialized
## Finally, let's wrap it in a QuantumModel
obs = hamiltonian_factory(n_qubits, detuning = Z)
qm = QuantumModel(qc, obs, backend='pyqtorch', diff_mode='ad')
qm_dict = serialize(qm)
qm_deserialized = deserialize(qm_dict)
# Lets check if the loaded QuantumModel returns the same expectation
assert torch.isclose(qm.expectation({}), qm_deserialized.expectation({}))
{'type': 'ChainBlock', 'qubit_support': (0, 1), 'tag': 'HEA', 'blocks': [{'type': 'ChainBlock', 'qubit_support': (0, 1), 'tag': None, 'blocks': [{'type': 'KronBlock', 'qubit_support': (0, 1), 'tag': None, 'blocks': [{'type': 'RX', 'qubit_support': (0,), 'tag': None, 'parameters': {'_name_dict': {'parameter': ('bc400449-ea4f-4e2b-acdc-45987ce0249e', {'name': 'theta_0', 'expression': "Parameter('theta_0')", 'symbols': {'theta_0': {'name': 'theta_0', 'trainable': 'True', 'value': '0.2915895318800006'}}})}}, 'noise': None}, {'type': 'RX', 'qubit_support': (1,), 'tag': None, 'parameters': {'_name_dict': {'parameter': ('995a6223-04f7-4f21-b18e-c5b5e0f20aa7', {'name': 'theta_1', 'expression': "Parameter('theta_1')", 'symbols': {'theta_1': {'name': 'theta_1', 'trainable': 'True', 'value': '0.22961349503211292'}}})}}, 'noise': None}]}, {'type': 'KronBlock', 'qubit_support': (0, 1), 'tag': None, 'blocks': [{'type': 'RY', 'qubit_support': (0,), 'tag': None, 'parameters': {'_name_dict': {'parameter': ('ce566430-e3a6-444f-a6c0-59736ac0f82e', {'name': 'theta_2', 'expression': "Parameter('theta_2')", 'symbols': {'theta_2': {'name': 'theta_2', 'trainable': 'True', 'value': '0.024175203816877877'}}})}}, 'noise': None}, {'type': 'RY', 'qubit_support': (1,), 'tag': None, 'parameters': {'_name_dict': {'parameter': ('03fbb49b-4ace-43d5-ad66-baca0bd7bb90', {'name': 'theta_3', 'expression': "Parameter('theta_3')", 'symbols': {'theta_3': {'name': 'theta_3', 'trainable': 'True', 'value': '0.5927265369193969'}}})}}, 'noise': None}]}, {'type': 'KronBlock', 'qubit_support': (0, 1), 'tag': None, 'blocks': [{'type': 'RX', 'qubit_support': (0,), 'tag': None, 'parameters': {'_name_dict': {'parameter': ('fdff4997-c3fb-4992-a4c6-19761ba2af49', {'name': 'theta_4', 'expression': "Parameter('theta_4')", 'symbols': {'theta_4': {'name': 'theta_4', 'trainable': 'True', 'value': '0.6333931490419303'}}})}}, 'noise': None}, {'type': 'RX', 'qubit_support': (1,), 'tag': None, 'parameters': {'_name_dict': {'parameter': ('ea27e52d-dc01-41d8-bfa0-e18465f62995', {'name': 'theta_5', 'expression': "Parameter('theta_5')", 'symbols': {'theta_5': {'name': 'theta_5', 'trainable': 'True', 'value': '0.5438656578238705'}}})}}, 'noise': None}]}]}, {'type': 'ChainBlock', 'qubit_support': (0, 1), 'tag': None, 'blocks': [{'type': 'KronBlock', 'qubit_support': (0, 1), 'tag': None, 'blocks': [{'type': 'CNOT', 'qubit_support': (0, 1), 'tag': None, 'blocks': [{'type': 'X', 'qubit_support': (1,), 'tag': None, 'noise': None}], 'noise': None}]}]}]}