Passed
Push — upgrade-to-connexion3 ( e417e0...5d7ec9 )
by Juho
09:39 queued 05:10
created

NNEnsembleBackend._fit_model()   B

Complexity

Conditions 5

Size

Total Lines 25
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Importance

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