Domain-Agnostic Neural Architecture for Class Incremental Continual Learning in Document Processing Platform
Year: 2023

Abstract:
Production deployments in complex systems require ML architectures to be highly efficient and usable against multiple tasks. Particularly demanding are classification problems in which data arrives in a streaming fashion and each class is presented separately. Recent methods with stochastic gradient learning have been shown to struggle in such setups or have limitations like memory buffers, and being restricted to specific domains that disable its usage in realworld scenarios. For this reason, we present a fully differentiable architecture based on the Mixture of Experts model, that enables the training of high-performance classifiers when examples from each class are presented separately. We conducted exhaustive experiments that proved its applicability in various domains and ability to learn online in production environments. The proposed technique achieves SOTA results without a memory buffer and clearly outperforms the reference methods.

heading: 1 Introduction
text: Solutions based on deep neural networks have already found their applications in almost every domain that can be automated. An essential part of them is NLP, the development of which has gained particular momentum with the beginning of the era of transformers (Vaswani et al., 2017). Complex and powerful models made it possible to solve problems such as text classification with a previously unattainable accuracy. However, exploiting the capabilities of such architectures in real-world systems requires online learning after deployment. This is especially difficult in dynamically changing environments that require the models to be frequently retrained due to domain or class setup shifts. An example of such environment is Alphamoon Workspace1 where the presented architecture will be deployed as a model for document
1https://alphamoon.ai/
classification since we noticed the emerging need for online learning. We observed that the users’ data in document classification process is changing frequently and such shifts often decrease the model accuracy. As a result, we have to retrain the models manually ensuing a time-consuming process. Our goal was to design an effective approach to incremental learning that will be used in a continual learning module of our system (Figure 1).
Recently, neural architectures have become effective and widely used in classification problems (Devlin et al., 2018; Rawat and Wang, 2017). The parameter optimization process based on gradient descent works well when the data set is sufficiently large and fully available during the training process. Otherwise, the catastrophic forgetting (French, 1999) may occur, which makes neural networks unable to be trained incrementally. Continual learning aims to develop methods that enable accumulating new knowledge without forgetting previously learnt one.
In this paper, we present a domain-agnostic architecture for online class incremental continual learning called DE&E (Deep Encoders and Ensembles). Inspired by the E&E method (Shanahan et al., 2021), we proposed a method that increases its accuracy, provides full differentiability, and, most
527
importantly, can effectively solve real-world classification problems in production environments. Our contribution is as follows: 1) we introduced a differentiable KNN layer (Xie et al., 2020) into the model architecture, 2) we proposed a novel approach to aggregate classifier predictions in the ensemble, 3) we performed exhaustive experiments showing the ability to learn incrementally and real-world usability, 4) we demonstrate the effectiveness of the proposed architecture by achieving SOTA results on various data sets without a memory buffer.

heading: 2 Related work

heading: 2.1 Continual Learning

heading: 2.1.1 Methods
text: Currently, methods with a memory buffer such as GEM (Lopez-Paz and Ranzato, 2017), A-GEM (Chaudhry et al., 2019a) or DER (Buzzega et al., 2020) usually achieve the highest performance in all continual learning scenarios (Mai et al., 2022). Such methods store part of the data in the memory and this data is successively replayed during training on new, unseen examples. However, the requirement to store data in memory disqualifies these methods in many practical applications due to privacy policies or data size (Salem et al., 2018). This forces attention toward other approaches, such as parameter regularization. The most popular methods in this group include EWC (Kirkpatrick et al., 2016) and LWF (Li and Hoiem, 2017). When receiving a new dose of knowledge, these methods attempt to influence the model parameter updating procedure to be minimally invasive. As research shows (Van de Ven and Tolias, 2019), regularization-based methods fail in class incremental scenarios making them ineffective in many real-world cases.

heading: 2.1.2 Approaches for NLP
text: Almost all prior works focus on the development of continual learning methods in the computer vision domain (Delange et al., 2021). Research on continual learning for NLP is limited and, as Biesialska et al. (2020) observed, the majority of current NLP methods are task-specific. Moreover, these methods often use a memory buffer (de Masson D’Autume et al., 2019) or relate to the language model itself (Ke et al., 2021). To address this niche, domain-agnostic approaches have to become much more prevalent in the near future.

heading: 2.2 Ensemble methods
text: Ensemble methods are widespread in the world of machine learning (Zhang and Ma, 2012). By using predictions of multiple weak learners, it is possible to get a model that performs surprisingly well overall. Broad adoption of methods (Cao et al., 2020; Li and Pan, 2022; Yang et al., 2021) demonstrates the effectiveness of ensemble techniques in a wide variety of tasks. Ensembles have also been used successfully in the field of continual learning, as evidenced by the BatchEnsemble (Wen et al., 2020) or CN-DPM (Lee et al., 2020). Other contributions present in literature (Doan et al., 2022) tend to focus strongly on improving model performance rather than increasing model efficiency. Furthermore, ensemble approaches can also be used indirectly through dropout (Srivastava et al., 2014) or weights aggregation (Wortsman et al., 2022).

heading: 2.3 Mixture of Experts
text: Mixture of Experts (ME) (Jacobs et al., 1991) is a technique based on the divide and conquer paradigm. It assumes dividing the problem space between several specialized models (experts). Experts are supervised by the gating network that selects them based on the defined strategy. The difference between the ensembles is that ME methods focus on selecting a few experts rather than combining predictions of all available models. ME techniques have found many applications in various domains (Masoudnia and Ebrahimpour, 2014), including continual learning (Shanahan et al., 2021), and even nowadays such approaches are widely used in NLP (Gao et al., 2022; Ravaut et al., 2022).

heading: 2.4 Real-world NLP systems
text: Over the last few years, the amount of real-world NLP applications has grown rapidly (Sarker, 2022). Despite major successes in the real-world application of language technologies such as Google Translate, Amazon Alexa, and ChatGPT, production deployment and maintenance of such models still remain a challenge. Researchers have shown (Nowakowski et al., 2022; Karakanta et al., 2021), that there are several issues related to maintaining NLP models, including technical limitations, latency, and performance evaluation. However, the crucial problem is the shift of data domain that forces models to be retrained and deployed again over time (Hu et al., 2020). It is a major limitation in dynamically changing environments where users
expect models to quickly adapt to them. Currently, this problem has been tackled in several systems (Afzal et al., 2019; Hancock et al., 2019), but many of the solutions preclude maintaining model accuracy when training incrementally making them insufficient.

heading: 3 Our approach

heading: 3.1 Problem formulation
text: Class incremental continual learning involves training a classification model f(·) : X 7−→ Y on a sequence of T tasks. The model is trained on each task separately (one task at a time). Each task Dt contains data points Dt = {(x1t , y1t ), . . . , (xNtt , yNtt )}, where Nt is length of Dt, x (i) t ∈ RD, and y (i) t ∈ Yt. Yt is a label set for task t and Yt ∩ Yt′ = ∅ for t ̸= t′. We want the model to keep performing well on all previous tasks after each update, and we assume to be working in the most challenging setup (Van de Ven and Tolias, 2019), where one task consists of data from one class.

heading: 3.2 Method
text: We present a flexible and effective domain-agnostic architecture that can be used to solve various classification problems. The architecture is presented in Figure 2.
Feature extractor. The first component of the proposed architecture is a multi-layer feature ex-
tractor that transforms input data into the embedding space. It can be described by the following mapping z = F (x), where x ∈ RD is an input example and z ∈ RM is a M -dimensional embedding. The approach we follow assumes the use of a pre-trained model with frozen parameters. Such a procedure makes it possible to completely prevent the extractor from forgetting knowledge by isolating feature space learning from the classification process.
Keys and classifiers. We use an ensemble of N classifiers fn(·), where each of them maps the embedding into a K-dimensional output vector ŷn = fn(z). With each classifier, there is an associated key vector kn ∈ RM with the same dimensionality as the embedding. The keys help to select the most suitable models for specialization with respect to the currently processed input example. They are initialized randomly from normal distribution. We use simple single-layer neural networks as classifiers, with fan-in variance scaling as the weight initialization strategy. The network output is activated by a hyperbolic tangent function (tanh).
Soft κ-nearest neighbors layer. The standard KNN algorithm is often implemented using ordinary sorting operations that make it impossible to determine the partial derivatives with respect to the input. It removes the ability to use KNN as part of end-to-end neural models. However, it is possible to obtain a differentiable approximation of
the KNN model by solving the Optimal Transport Problem (Peyré et al., 2019). Based on this concept, we add a differentiable layer to the model architecture. We call this layer soft κ-nearest neighbors (soft KNN). In order to determine the KNN approximation, we first compute a cosine distance vector c ∈ RN between the embedding and the keys:
cn = 1− cos(z,kn), (1)
where cos(·, ·) denotes the cosine similarity. Next, we follow the idea of a soft top-κ operator presented in (Xie et al., 2020), where κ denotes the number of nearest neighbors. Let E ∈ RN×2 be the Euclidean distance matrix with the following elements:
en,0 = (cn) 2, en,1 = (cn − 1)2. (2)
And let G ∈ RN×2 denote the similarity matrix obtained by applying the Gaussian kernel to E:
G = exp(−E/σ), (3)
where σ denotes the kernel width. The exp operators are applied elementwise to the matrix E.
We then use the Bregman method, an algorithm designed to solve convex constraint optimization problems, to compute L iterations of Bregman projections in order to approximate their stationary points:
p(l+1) = µ
Gq(l) , q(l+1) =
ν
G⊤p(l+1) , (4)
where l = 0, . . . , L − 1,µ = 1N/N , ν = [κ/N, (N − κ)/N ]⊤, q(0) = 12/2, and 1i denotes the i-element all-ones vector. Finally, let Γ denotes the optimal transport plan matrix and is given by:
Γ = diag(p(L)) ·G · diag(q(L)) (5)
As the final result γ ∈ RN of the soft κ-nearest neighbor operator, we take the second column of Γ multiplied by N i.e. γ = NΓ:,2. γ is a soft approximation of a zero-one vector that indicates which κ out of N instances are the nearest neighbors. Introducing the soft KNN enables to train parts of the model that were frozen until now.
Voting layer. We use both cn and γ to weight the predictions by giving the higher impact for classifiers with keys similar to extracted features. The obtained approximation γ has two main functionalities. It eliminates the predictions from classifiers
outside κ nearest neighbors and weights the result. Since the Bregman method does not always completely converge, the vector κ contains continuous values that are close to 1 for the most relevant classifiers. We make use of this property during the ensemble voting procedure. The higher the κ value for a single classifier, the higher its contribution toward the final ensemble decision. The final prediction is obtained as follows:
ŷ = ∑N n=1 γncnŷn∑N
n=1 cn (6)
Training To effectively optimize the model parameters, we follow the training procedure presented in (Shanahan et al., 2021). It assumes the use of a specific loss function that is the inner product between the ensemble prediction and the onehot coded label:
L(y, ŷ) = −y⊤ŷ (7) Optimizing this criterion yields an advantage of using a tanh activation function, significantly reducing catastrophic forgetting (Shanahan et al., 2021). Following the reference method, we also use an optimizer that discards the value of the gradient and uses only its sign to determine the update direction. As a result, the parameters are being changed by a fixed step during the training.

heading: 4 Experiments

heading: 4.1 Setup
text: In order to ensure experiment’s reproductivity, we evaluated our method on the popular and publicly available data sets.
Data sets We use three common text classification data sets with different characteristics - Newsgroups (Lang, 2008), BBC News (Greene and Cunningham, 2006), and Consumer Finance Complaints2. The goal of the experiments was to evaluate our method on tasks with with different dif-
2Source: https://huggingface.co/datasets/ consumer-finance-complaints
Table 2: Accuracy (%) and standard deviation for methods evaluated on various data sets. Speech Commands data set was evaluated with 64 classifiers in ME, the remaining models have 128 classifiers. Regularization-based methods completely failed on the difficult data sets due to the recency bias phenomenon (Mai et al., 2022).
Text Image Audio Model Mem. NG BBC Compl. MNIST CIFAR-10 Sp. Comm. Naive × 5.25±0.03 21.65±2.56 9.56±0.33 11.29±3.05 10.00±0.01 21.54±3.78 LwF × 5.20±0.05 18.60±2.03 10.04±0.20 11.47±2.75 10.00±0.01 20.61±3.88 EWC × 5.13±0.13 21.97±2.14 10.16±0.31 11.19±2.70 10.00±0.01 32.93±4.92 SI × 5.27±0.01 19.43±2.96 10.00±0.62 14.90±6.52 10.00±0.01 9.99±0.27 CWR* × 4.63±0.60 22.98±1.20 10.13±0.33 10.40±0.54 10.00±0.01 10.32±0.26 GEM ✓ 35.89±3.80 70.99±7.68 33.74±2.50 52.27±5.20 23.40±2.71 21.01±2.06 A-GEM ✓ 9.44±7.14 59.10±17.52 9.20±0.01 65.37±4.53 26.43±5.27 17.45±6.90 Replay ✓ 22.45±3.09 59.61±3.17 16.46±4.62 69.02±4.90 32.93±4.56 12.23±1.28 E&E × 46.07±2.91 75.87±3.88 44.80±1.62 87.10±0.21 53.97±1.31 79.15±0.60 Ours × 47.27±3.63 78.49±3.92 44.97±0.86 87.62±0.14 56.27±1.21 80.11±1.30
ficulty levels. We also conducted experiments for audio classification using Speech Commands (Warden, 2018) data set. For the evaluation purposes, we selected the 10 most representative classes from the Newsgroups, Complaints and Speech Commands. Finally, we also conducted experiments on the popular MNIST and CIFAR-10 data sets as image domain representatives. The data set summary is presented in Table 1. In all experiments we used a train set to train model incrementally, and afterward we performed a standard evaluation using a test set.
Feature extractors For all text data sets, we used a Distilbert (Sanh et al., 2019), a light but still very effective alternative for large language models. Next, for Speech Commands, we utilized Pyannote (Bredin et al., 2020), a pretrained model for producing meaningful audio features. For image data sets, we used different extractors. MNIST features were produced by the pretrained VAE and CIFAR-10 has a dedicated BYOL model (see A.4 for more details).

heading: 4.2 Results
text: The results of the evaluation are presented in Table 2. For all setups evaluated, our model performed best improving results of the main reference method (E&E) by up to 3 percent points (pp.). The improvement scale varies across the data sets. We also observed a significant difference in achieved accuracy between the DE&E and the standard continual learning methods. Simple regularizationbased methods completely fail in the class incremental scenario. It shows how demanding training
Figure 3: Number of parameters in DE&E architecture (64, 128, 1024 classifiers) and achieved accuracy (%). We calculated the number of parameters as the sum of the parameters for all classifiers in the ME. Each mark is the test accuracy averaged across 5 runs.
the model incrementally is when a set of classes is not fixed, which often takes place in real-world scenarios. Furthermore, our method achieved these results without replaying training examples seen in the past, making it more practical relative to the SOTA memory-based methods (GEM, A-GEM, Replay) that store samples from every class. For the ensemble of 128 classifiers and Speech Commands data set, our architecture achieved an accuracy of more than 59 pp. higher than the best method with a memory buffer.
One of the most important hyperparameters of the model is the number of classifiers (experts). To investigate how it affects accuracy, we evaluated our architecture in three variants: small - 64, normal - 128, and large - 1024 classifiers. The evaluation results are presented in Figure 3. We observed that increasing the ensemble size trans-
lates to higher accuracy, and gain depends on the setup and data characteristics. The most significant improvement was observed on BBC and CIFAR10 where the large model achieved an accuracy of about 20pp. better than the small one. For the remaining data sets and the analogous setup, the gain was up to 5pp. We explain this phenomenon as the effect of insufficient specialization level achieved by smaller ensembles. If experts are forced to solve tasks that are too complicated they make mistakes often. Increasing the number of experts allows for dividing feature space into simpler sub-tasks. However, such a procedure has natural limitations related to the feature extractor. If features have low quality, increasing the number of experts will be ineffective. To select the optimal ensemble size we suggest using the elbow rule which prevents the model from being overparameterized and ensures reasonable accuracy. However, in general, we recommend choosing larger ensembles that are better suited for handling real-world cases.
Since real-world environments require deployed models to quickly adapt to domain shifts, we tested our method in a domain incremental scenario. In such setup, each data batch can provide examples from multiple classes that can be either known or new (Van de Ven and Tolias, 2019). This way, the model needs to learn incrementally, being prone to frequent domain shifts. As shown in Table 3, the proposed method handles both scenarios with comparable accuracy. We observed improved accuracy for BBC News, but reduced for the remaining data sets. Such property can be beneficial when there is limited prior knowledge about the data or the stream is imbalanced (Aguiar et al., 2022).
We have also investigated the importance of the presented expert selection method. We trained the DE&E method and for each training example, we allowed it to choose random experts (rather than the most relevant ones) with fixed probability p. As shown in Figure 4, the selection method has a
strong influence on the model performance. Accuracy decreases proportionally to the p over all data sets studied. The proper expert selection technique is crucial for the presented method. It is worth noting that relatively easier data sets suffer less from loss of accuracy than hard ones because even randomly selected experts can still classify the data by learning simple general patterns. In more difficult cases like Newsgroups and Complaints data sets, model performance is comparable to random guessing when p > 0.5.

heading: 5 Conclusions
text: In this paper, we proposed a domain-agnostic architecture for continual learning with a training procedure specialized in challenging class incremental problems. The presented architecture is based on the Mixture of Experts technique and handles many practical issues related to the deployment of text classification models in non-trivial real-world systems. As our main contribution, we introduced a fully differentiable soft KNN layer and a novel prediction weighting strategy. By conducting exhaustive experiments, we showed improvement in accuracy for all the cases studied and achieved SOTA results without using a memory buffer. This enables an effective and secure training, especially when working with sensitive textual data. The presented architecture is highly flexible, can effectively solve classification problems in many domains, and can be applied to real-world machine learning systems requiring continuous improvement. Such work enables researchers to make further steps toward overrunning many of the current challenges related to language technology applications.
Limitations
The main limitations of the proposed architecture are related to the presence of the frozen feature extractor. The accuracy of the classification module is proportional to the quality of features. Since the ensemble weak learners are single-layer neural networks, the entire feature extraction process relies on a pre-trained model that strongly limits the upper bound of classification accuracy. Such approach reduces the method complexity, but also makes it prone to errors when embeddings have low quality. Achieving accuracy at a satisfactory level, which is crucial in real world systems, requires the use of high quality feature extractors. Currently, plenty of pretrained SOTA models are available for free in domains such as text or image classification, but if such extractor is not available, does not produce reasonable features or is too expensive to use, our architecture may not be the best choice.
Another issue is relatively long training time comparing to the reference methods (see A.3). The introduction of a differentiable soft KNN layer resulted in additional computational effort that clearly impacted the model complexity. This limits the use in low latency systems with machine learning models trained online.
Ethics Statement
The authors foresee no ethical concerns with the work presented in this paper, in particular concerning any kind of harm and discrimination. Since the presented architecture can have a wide range of usages, the authors are not responsible for any unethical applications of this work.

heading: Acknowledgements
text: The research was conducted under the Implementation Doctorate programme of Polish Ministry of Science and Higher Education and also partially funded by Department of Artificial Intelligence, Wroclaw Tech and by the European Union under the Horizon Europe grant OMINO (grant number 101086321). It was also partially co-funded by the European Regional Development Fund within the Priority Axis 1 “Enterprises and innovation”, Measure 1.2. “Innovative enterprises, sub-measure 1.2.1. “Innovative enterprises – horizontal competition” as part of ROP WD 2014-2020, support contract no. RPDS.01.02.01-02-0063/20-00.

heading: A Appendix
text: A.1 Code Code is currently available as a Github repository https://github.com/mateusz-wojcik-97/ domain-agnostic-architecture.
A.2 Computing resources The machine we used had 128 GB RAM, an Intel Core i9-11900 CPU, and an NVIDIA GeForce RTX 3060 GPU with 12GB VRAM. Every experiment was performed using the GPU.
A.3 Time complexity
The comparison in training time between E&E and DE&E models is shown in Table 4. For all evaluated data sets, the training time of our model was higher than the time to train the reference method. The results vary between data sets. The introduction of a differentiable soft KNN layer resulted in additional computational effort that clearly impacted the time complexity of the model.
A.4 Implementation details We use PyTorch to both reproduce the E&E results and implement the DE&E method. For text classification we used pretrained Distilbert 3 model and for audio classification we used pretrained Pyannote 4 model, both from the Huggingface repository. We used a pre-trained ResNet-50 model as the feature extractor for the CIFAR-10 data set. The model is available in the following GitHub repository,
3https://huggingface.co/distilbert-base-uncased 4https://huggingface.co/pyannote/embedding
https://github.com/yaox12/BYOL-PyTorch, and is used under MIT Licence. For MNIST, we trained a variational autoencoder on the Omniglot data set and utilized encoder part as our feature extractor. We based our implementation of the soft KNN layer on the code provided with https:// proceedings.neurips.cc/paper/2020/hash/ ec24a54d62ce57ba93a531b460fa8d18-Abstract. html. All data sets used are public.
Baselines We use Naive, LwF (Li and Hoiem, 2017), EWC (Kirkpatrick et al., 2016), SI (Zenke et al., 2017), CWR* (Lomonaco and Maltoni, 2017), GEM (Lopez-Paz and Ranzato, 2017), A-GEM (Chaudhry et al., 2019a) and Replay (Chaudhry et al., 2019b) approaches as baselines to compare with our method. We utilize the implementation from Avalanche (https://avalanche. continualai.org/), a library designed for continual learning tasks. The main purpose of this comparison was to determine how the proposed method performs against classical approaches and, in particular, against the methods with memory buffer, which gives a significant advantage in class incremental problems. The recommended hyperparameters for each baseline method vary across usages in literature, so we chose them based on our own internal experiments. For a clarity, we keep hyperparameter naming nomenclature from the Avalnache library. For EWC we use lambda = 10000. The LwF model was trained with alpha = 0.15 and temperature = 1.5. For SI strategy, we use lambda = 5e7 and eps = 1e − 7. The hyperparameters of the memory based approach GEM were set as follows: memory_strength = 0.5, patterns_per_exp = 5, which implies that with every task, 5 examples will be accumulated. This has a particular importance when the number of classes is large. With this setup and 10 classes
in data set, memory contains 50 examples after training on all tasks. Having a large memory buffer makes achieving high accuracy much easier. For the A-GEM method, use the same number of examples in memory and sample_size = 20. All models were trained using Adam optimizer with a learning_rate of 0.0005 and batch_size of 60. We chose cross entropy as a loss function and performed one training epoch for each experience. To fairly compare baseline methods with ensembles, as a backbone we use neural network with a similar number of parameters (as in ensemble). Network architectures for each experimental setup are shown in Table 5. All baseline models were trained by providing embeddings produced by feature extractor as an input.
Ensembles. We used E&E (Shanahan et al., 2021) as the main reference method. It uses an architecture similar to that of a classifier ensemble, however the nearest neighbor selection mechanism itself is not a differentiable component and the weighting strategy is different. In order to reliably compare the performance, the experimental results of the reference method were fully reproduced. Both the reference method and the proposed method used exactly the same feature extractors. Thus, we ensured that the final performance is not affected by the varying quality of the extractor, but only depends on the solutions used in the model architecture and learning method.
Both E&E and our DE&E were trained with the same set of hyperparameters (excluding hyperparameters in the soft KNN layer for the DE&E). We use ensembles of sizes 64, 128 and 1024. Based on the data set, we used different hyperparameter sets for the ensembles (Table 6).
The keys for classifiers in ensembles were randomly chosen from the standard normal distribution and normalized using the L2 norm. The same normalization was applied to encoded inputs during lookup for matching keys.
Soft KNN. We use the Sinkhorn algorithm to perform the forward inference in soft KNN. The Sinkhorn algorithm is useful in entropy-regularized optimal transport problems thanks to its computational effort reduction. The soft KNN has O(n) complexity, making it scalable and allows us to safely apply it to more computationally expensive problems.
The values of soft KNN hyperparameters were
σ = 0.0005 and L = 400. We utilize the continuous character of an output vector to weight the ensemble predictions. It is worth noting that we additionally set the threshold of the minimum allowed soft KNN score to 0.3. It means every element in γ lower than 0.3 is reduced to 0. We reject such elements because they are mostly the result of nonconverged optimization and do not carry important information. In this way, we additionally secure the optimization result to be as representative as possible.

heading: Future Work
text: To address this niche, domain-agnostic approaches have to become much more prevalent in the near future