-
Notifications
You must be signed in to change notification settings - Fork 106
/
model.py
185 lines (145 loc) · 5.49 KB
/
model.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
# Copyright 2021-2022 Cambridge Quantum Computing Ltd.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Model
=====
Module containing the base class for a lambeq model.
"""
from __future__ import annotations
from abc import ABC, abstractmethod
from collections.abc import Collection
import os
from typing import Any, Union
from discopy.tensor import Diagram
from sympy import default_sort_key, Symbol as SymPySymbol
from lambeq.ansatz.base import Symbol
from lambeq.training.checkpoint import Checkpoint
_StrPathT = Union[str, 'os.PathLike[str]']
class Model(ABC):
"""Model base class.
Attributes
----------
symbols : list of symbols
A sorted list of all :py:class:`Symbols <.Symbol>` occuring in
the data.
weights : Collection
A data structure containing the numeric values of
the model's parameters.
"""
def __init__(self) -> None:
"""Initialise an instance of :py:class:`Model` base class."""
self.symbols: list[Union[Symbol, SymPySymbol]] = []
self.weights: Collection = []
def __call__(self, *args: Any, **kwds: Any) -> Any:
return self.forward(*args, **kwds)
@abstractmethod
def initialise_weights(self) -> None:
"""Initialise the weights of the model."""
@classmethod
def from_checkpoint(cls,
checkpoint_path: _StrPathT,
**kwargs: Any) -> Model:
"""Load the weights and symbols from a training checkpoint.
Parameters
----------
checkpoint_path : str or PathLike
Path that points to the checkpoint file.
Other Parameters
----------------
backend_config : dict
Dictionary containing the backend configuration for the
:py:class:`TketModel`. Must include the fields `'backend'`,
`'compilation'` and `'shots'`.
"""
model = cls(**kwargs)
checkpoint = Checkpoint.from_file(checkpoint_path)
model._load_checkpoint(checkpoint)
return model
@abstractmethod
def _load_checkpoint(self, checkpoint: Checkpoint) -> None:
"""Load the model weights and symbols from a lambeq
:py:class:`.Checkpoint`.
Parameters
----------
checkpoint : Checkpoint
:py:class:`.Checkpoint` containing the model weights,
symbols and additional information.
"""
@abstractmethod
def _make_checkpoint(self) -> Checkpoint:
"""Create checkpoint that contains the model weights and symbols.
Returns
-------
Checkpoint
:py:class:`.Checkpoint` containing the model weights,
symbols and additional information.
"""
def save(self, checkpoint_path: _StrPathT) -> None:
"""Create a lambeq :py:class:`.Checkpoint` and save to a path.
Example:
>>> from lambeq import PytorchModel
>>> model = PytorchModel()
>>> model.save('my_checkpoint.lt')
Parameters
----------
checkpoint_path : str or PathLike
Path that points to the checkpoint file.
"""
checkpoint = self._make_checkpoint()
checkpoint.to_file(checkpoint_path)
def load(self, checkpoint_path: _StrPathT) -> None:
"""Load model data from a path pointing to a lambeq checkpoint.
Checkpoints that are created by a lambeq :py:class:`Trainer`
usually have the extension `.lt`.
Parameters
----------
checkpoint_path : str or PathLike
Path that points to the checkpoint file.
"""
checkpoint = Checkpoint.from_file(checkpoint_path)
self._load_checkpoint(checkpoint)
@abstractmethod
def get_diagram_output(self, diagrams: list[Diagram]) -> Any:
"""Return the diagram prediction.
Parameters
----------
diagrams : list of :py:class:`~discopy.tensor.Diagram`
The tensor or circuit diagrams to be evaluated.
"""
@abstractmethod
def forward(self, x: list[Any]) -> Any:
"""The forward pass of the model."""
@classmethod
def from_diagrams(cls, diagrams: list[Diagram], **kwargs: Any) -> Model:
"""Build model from a list of
:py:class:`Diagrams <discopy.tensor.Diagram>`.
Parameters
----------
diagrams : list of :py:class:`~discopy.tensor.Diagram`
The tensor or circuit diagrams to be evaluated.
Other Parameters
----------------
backend_config : dict
Dictionary containing the backend configuration for the
:py:class:`TketModel`. Must include the fields `'backend'`,
`'compilation'` and `'shots'`.
use_jit : bool, default: False
Whether to use JAX's Just-In-Time compilation in
:py:class:`NumpyModel`.
"""
model = cls(**kwargs)
model.symbols = sorted(
{sym for circ in diagrams for sym in circ.free_symbols},
key=default_sort_key)
return model