-
Notifications
You must be signed in to change notification settings - Fork 106
/
quantum_model.py
154 lines (120 loc) · 4.49 KB
/
quantum_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
# 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.
"""
QuantumModel
============
Module containing the base class for a quantum lambeq model.
"""
from __future__ import annotations
from abc import abstractmethod
from typing import Any, TYPE_CHECKING, Union
from discopy.tensor import Diagram, Tensor
import numpy as np
if TYPE_CHECKING:
from jax import numpy as jnp
from lambeq.training.checkpoint import Checkpoint
from lambeq.training.model import Model
class QuantumModel(Model):
"""Quantum Model base class.
Attributes
----------
symbols : list of symbols
A sorted list of all :py:class:`Symbols <.Symbol>` occurring in
the data.
weights : array
A data structure containing the numeric values of the model
parameters
SMOOTHING : float
A smoothing constant
"""
weights: np.ndarray
SMOOTHING = 1e-9
def __init__(self) -> None:
"""Initialise a :py:class:`QuantumModel`."""
super().__init__()
self._training = False
self._train_predictions : list[Any] = []
def _log_prediction(self, y: Any) -> None:
"""Log a prediction of the model."""
self._train_predictions.append(y)
def _clear_predictions(self) -> None:
"""Clear the logged predictions of the model."""
self._train_predictions = []
def _normalise_vector(self, predictions: np.ndarray) -> np.ndarray:
"""Normalise the vector input.
Does not normalise scalar values; instead, returns the absolute
value of scalars.
"""
backend = Tensor.get_backend()
ret: np.ndarray
if not predictions.shape:
ret = backend.abs(predictions)
else:
smoothed_predictions = backend.abs(predictions) + self.SMOOTHING
ret = smoothed_predictions / smoothed_predictions.sum()
return ret
def initialise_weights(self) -> None:
"""Initialise the weights of the model.
Raises
------
ValueError
If `model.symbols` are not initialised.
"""
if not self.symbols:
raise ValueError('Symbols not initialised. Instantiate through '
'`from_diagrams()`.')
self.weights = np.random.rand(len(self.symbols))
def _load_checkpoint(self, checkpoint: Checkpoint) -> None:
"""Load the model weights and symbols from a lambeq
:py:class:`.Checkpoint`.
Parameters
----------
checkpoint : :py:class:`.Checkpoint`
Checkpoint containing the model weights, symbols and
additional information.
"""
self.symbols = checkpoint['model_symbols']
self.weights = checkpoint['model_weights']
def _make_checkpoint(self) -> Checkpoint:
"""Create checkpoint that contains the model weights and symbols.
Returns
-------
:py:class:`.Checkpoint`
Checkpoint containing the model weights, symbols and
additional information.
"""
checkpoint = Checkpoint()
checkpoint.add_many({'model_symbols': self.symbols,
'model_weights': self.weights})
return checkpoint
@abstractmethod
def get_diagram_output(self, diagrams: list[Diagram]) -> Union[jnp.ndarray,
np.ndarray]:
"""Return the diagram prediction.
Parameters
----------
diagrams : list of :py:class:`~discopy.tensor.Diagram`
The :py:class:`Circuits <discopy.quantum.circuit.Circuit>`
to be evaluated.
"""
def __call__(self, *args: Any, **kwargs: Any) -> Any:
out = self.forward(*args, **kwargs)
if self._training:
self._log_prediction(out)
return out
@abstractmethod
def forward(self, x: list[Diagram]) -> Any:
"""Compute the forward pass of the model using
`get_model_output`
"""