Passed
Push — issue784-fix-nn-ensemle-model-... ( 7a1cfe )
by Juho
03:50
created

NNEnsembleBackend.initialize()   B

Complexity

Conditions 5

Size

Total Lines 23
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

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