Passed
Push — issue703-python-3.11-support ( f59527...05d52a )
by Juho
04:06 queued 14s
created

NNEnsembleBackend.initialize()   A

Complexity

Conditions 4

Size

Total Lines 17
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 14
nop 2
dl 0
loc 17
rs 9.7
c 0
b 0
f 0
1
"""Neural network based ensemble backend that combines results from multiple
2
projects."""
3
from __future__ import annotations
4
5
import os.path
6
import shutil
7
from io import BytesIO
8
from typing import TYPE_CHECKING, Any
9
10
import joblib
11
import lmdb
12
import numpy as np
13
import tensorflow.keras.backend as K
14
from scipy.sparse import csc_matrix, csr_matrix
15
from tensorflow.keras.layers import Add, Dense, Dropout, Flatten, Input, Layer
16
from tensorflow.keras.models import Model, load_model
17
from tensorflow.keras.utils import Sequence
18
19
import annif.corpus
20
import annif.parallel
21
import annif.util
22
from annif.exception import NotInitializedException, NotSupportedException
23
from annif.suggestion import SuggestionBatch, vector_to_suggestions
24
25
from . import backend, ensemble
26
27
if TYPE_CHECKING:
28
    from tensorflow.python.framework.ops import EagerTensor
29
30
    from annif.corpus.document import DocumentCorpus
31
32
33
def idx_to_key(idx: int) -> bytes:
34
    """convert an integer index to a binary key for use in LMDB"""
35
    return b"%08d" % idx
36
37
38
def key_to_idx(key: memoryview | bytes) -> int:
39
    """convert a binary LMDB key to an integer index"""
40
    return int(key)
41
42
43
class LMDBSequence(Sequence):
44
    """A sequence of samples stored in a LMDB database."""
45
46
    def __init__(self, txn, batch_size):
47
        self._txn = txn
48
        cursor = txn.cursor()
49
        if cursor.last():
50
            # Counter holds the number of samples in the database
51
            self._counter = key_to_idx(cursor.key()) + 1
52
        else:  # empty database
53
            self._counter = 0
54
        self._batch_size = batch_size
55
56
    def add_sample(self, inputs: np.ndarray, targets: np.ndarray) -> None:
57
        # use zero-padded 8-digit key
58
        key = idx_to_key(self._counter)
59
        self._counter += 1
60
        # convert the sample into a sparse matrix and serialize it as bytes
61
        sample = (csc_matrix(inputs), csr_matrix(targets))
62
        buf = BytesIO()
63
        joblib.dump(sample, buf)
64
        buf.seek(0)
65
        self._txn.put(key, buf.read())
66
67
    def __getitem__(self, idx: int) -> tuple[np.ndarray, np.ndarray]:
68
        """get a particular batch of samples"""
69
        cursor = self._txn.cursor()
70
        first_key = idx * self._batch_size
71
        cursor.set_key(idx_to_key(first_key))
72
        input_arrays = []
73
        target_arrays = []
74
        for key, value in cursor.iternext():
75
            if key_to_idx(key) >= (first_key + self._batch_size):
76
                break
77
            input_csr, target_csr = joblib.load(BytesIO(value))
78
            input_arrays.append(input_csr.toarray())
79
            target_arrays.append(target_csr.toarray().flatten())
80
        return np.array(input_arrays), np.array(target_arrays)
81
82
    def __len__(self) -> int:
83
        """return the number of available batches"""
84
        return int(np.ceil(self._counter / self._batch_size))
85
86
87
class MeanLayer(Layer):
88
    """Custom Keras layer that calculates mean values along the 2nd axis."""
89
90
    def call(self, inputs: EagerTensor) -> EagerTensor:
91
        return K.mean(inputs, axis=2)
92
93
94
class NNEnsembleBackend(backend.AnnifLearningBackend, ensemble.BaseEnsembleBackend):
95
    """Neural network ensemble backend that combines results from multiple
96
    projects"""
97
98
    name = "nn_ensemble"
99
100
    MODEL_FILE = "nn-model.h5"
101
    LMDB_FILE = "nn-train.mdb"
102
103
    DEFAULT_PARAMETERS = {
104
        "nodes": 100,
105
        "dropout_rate": 0.2,
106
        "optimizer": "adam",
107
        "epochs": 10,
108
        "learn-epochs": 1,
109
        "lmdb_map_size": 1024 * 1024 * 1024,
110
    }
111
112
    # defaults for uninitialized instances
113
    _model = None
114
115
    def initialize(self, parallel: bool = False) -> None:
116
        super().initialize(parallel)
117
        if self._model is not None:
118
            return  # already initialized
119
        if parallel:
120
            # Don't load TF model just before parallel execution,
121
            # since it won't work after forking worker processes
122
            return
123
        model_filename = os.path.join(self.datadir, self.MODEL_FILE)
124
        if not os.path.exists(model_filename):
125
            raise NotInitializedException(
126
                "model file {} not found".format(model_filename),
127
                backend_id=self.backend_id,
128
            )
129
        self.debug("loading Keras model from {}".format(model_filename))
130
        self._model = load_model(
131
            model_filename, custom_objects={"MeanLayer": MeanLayer}
132
        )
133
134
    def _merge_source_batches(
135
        self,
136
        batch_by_source: dict[str, SuggestionBatch],
137
        sources: list[tuple[str, float]],
138
        params: dict[str, Any],
139
    ) -> SuggestionBatch:
140
        src_weight = dict(sources)
141
        score_vectors = np.array(
142
            [
143
                [
144
                    np.sqrt(suggestions.as_vector())
145
                    * src_weight[project_id]
146
                    * len(batch_by_source)
147
                    for suggestions in batch
148
                ]
149
                for project_id, batch in batch_by_source.items()
150
            ],
151
            dtype=np.float32,
152
        ).transpose(1, 2, 0)
153
        prediction = self._model(score_vectors).numpy()
154
        return SuggestionBatch.from_sequence(
155
            [
156
                vector_to_suggestions(row, limit=int(params["limit"]))
157
                for row in prediction
158
            ],
159
            self.project.subjects,
160
        )
161
162
    def _create_model(self, sources: list[tuple[str, float]]) -> None:
163
        self.info("creating NN ensemble model")
164
165
        inputs = Input(shape=(len(self.project.subjects), len(sources)))
166
167
        flat_input = Flatten()(inputs)
168
        drop_input = Dropout(rate=float(self.params["dropout_rate"]))(flat_input)
169
        hidden = Dense(int(self.params["nodes"]), activation="relu")(drop_input)
170
        drop_hidden = Dropout(rate=float(self.params["dropout_rate"]))(hidden)
171
        delta = Dense(
172
            len(self.project.subjects),
173
            kernel_initializer="zeros",
174
            bias_initializer="zeros",
175
        )(drop_hidden)
176
177
        mean = MeanLayer()(inputs)
178
179
        predictions = Add()([mean, delta])
180
181
        self._model = Model(inputs=inputs, outputs=predictions)
182
        self._model.compile(
183
            optimizer=self.params["optimizer"],
184
            loss="binary_crossentropy",
185
            metrics=["top_k_categorical_accuracy"],
186
        )
187
        if "lr" in self.params:
188
            self._model.optimizer.learning_rate.assign(float(self.params["lr"]))
189
190
        summary = []
191
        self._model.summary(print_fn=summary.append)
192
        self.debug("Created model: \n" + "\n".join(summary))
193
194
    def _train(
195
        self,
196
        corpus: DocumentCorpus,
197
        params: dict[str, Any],
198
        jobs: int = 0,
199
    ) -> None:
200
        sources = annif.util.parse_sources(self.params["sources"])
201
        self._create_model(sources)
202
        self._fit_model(
203
            corpus,
204
            epochs=int(params["epochs"]),
205
            lmdb_map_size=int(params["lmdb_map_size"]),
206
            n_jobs=jobs,
207
        )
208
209
    def _corpus_to_vectors(
210
        self,
211
        corpus: DocumentCorpus,
212
        seq: LMDBSequence,
213
        n_jobs: int,
214
    ) -> None:
215
        # pass corpus through all source projects
216
        sources = dict(annif.util.parse_sources(self.params["sources"]))
217
218
        # initialize the source projects before forking, to save memory
219
        self.info(f"Initializing source projects: {', '.join(sources.keys())}")
220
        for project_id in sources.keys():
221
            project = self.project.registry.get_project(project_id)
222
            project.initialize(parallel=True)
223
224
        psmap = annif.parallel.ProjectSuggestMap(
225
            self.project.registry,
226
            list(sources.keys()),
227
            backend_params=None,
228
            limit=None,
229
            threshold=0.0,
230
        )
231
232
        jobs, pool_class = annif.parallel.get_pool(n_jobs)
233
234
        self.info("Processing training documents...")
235
        with pool_class(jobs) as pool:
236
            for hits, subject_set in pool.imap_unordered(
237
                psmap.suggest, corpus.documents
238
            ):
239
                doc_scores = []
240
                for project_id, p_hits in hits.items():
241
                    vector = p_hits.as_vector()
242
                    doc_scores.append(
243
                        np.sqrt(vector) * sources[project_id] * len(sources)
244
                    )
245
                score_vector = np.array(doc_scores, dtype=np.float32).transpose()
246
                true_vector = subject_set.as_vector(len(self.project.subjects))
247
                seq.add_sample(score_vector, true_vector)
248
249
    def _open_lmdb(self, cached, lmdb_map_size):
250
        lmdb_path = os.path.join(self.datadir, self.LMDB_FILE)
251
        if not cached and os.path.exists(lmdb_path):
252
            shutil.rmtree(lmdb_path)
253
        return lmdb.open(lmdb_path, map_size=lmdb_map_size, writemap=True)
254
255
    def _fit_model(
256
        self,
257
        corpus: DocumentCorpus,
258
        epochs: int,
259
        lmdb_map_size: int,
260
        n_jobs: int = 1,
261
    ) -> None:
262
        env = self._open_lmdb(corpus == "cached", lmdb_map_size)
263
        if corpus != "cached":
264
            if corpus.is_empty():
265
                raise NotSupportedException(
266
                    "Cannot train nn_ensemble project with no documents"
267
                )
268
            with env.begin(write=True, buffers=True) as txn:
269
                seq = LMDBSequence(txn, batch_size=32)
270
                self._corpus_to_vectors(corpus, seq, n_jobs)
271
        else:
272
            self.info("Reusing cached training data from previous run.")
273
        # fit the model using a read-only view of the LMDB
274
        self.info("Training neural network model...")
275
        with env.begin(buffers=True) as txn:
276
            seq = LMDBSequence(txn, batch_size=32)
277
            self._model.fit(seq, verbose=True, epochs=epochs)
278
279
        annif.util.atomic_save(self._model, self.datadir, self.MODEL_FILE)
280
281
    def _learn(
282
        self,
283
        corpus: DocumentCorpus,
284
        params: dict[str, Any],
285
    ) -> None:
286
        self.initialize()
287
        self._fit_model(
288
            corpus, int(params["learn-epochs"]), int(params["lmdb_map_size"])
289
        )
290