{'fraction_non_alphanumeric': 0.033776638359237304, 'fraction_numerical': 0.007755167441115206, 'mean_word_length': 5.055889772947797, 'pattern_counts': {'":': 0, '<': 0, '<?xml version=': 0, '>': 0, 'https://': 1, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 4, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
Adversarially Robust and Explainable Model Compression with On-Device Personalization for Text Classification

On-device Deep Neural Networks (DNNs) have recently gained more attention due to the increasing computing power of the mobile devices and the number of applications in Computer Vision (CV), Natural Language Processing (NLP), and Internet of Things (IoTs). Unfortunately, the existing efficient convolutional neural network (CNN) architectures designed for CV tasks are not directly applicable to NLP tasks and the tiny Recurrent Neural Network (RNN) architectures have been designed primarily for IoT applications. In NLP applications, although model compression has seen initial success in on-device text classification, there are at least three major challenges yet to be addressed: adversarial robustness, explainability, and personalization. Here we attempt to tackle these challenges by designing a new training scheme for model compression and adversarial robustness, including the optimization of an explainable feature mapping objective, a knowledge distillation objective, and an adversarially robustness objective. The resulting compressed model is personalized using on-device private training data via fine-tuning. We perform extensive experiments to compare our approach with both compact RNN (e.g., FastGRNN) and compressed RNN (e.g., PRADO) architectures in both natural and adversarial NLP test settings.


I. INTRODUCTION
As the improved hardware and increased availability of mobile apps are expected to provide personalized user experience, protect users' privacy, and offer minimum latency, mobile Artificial Intelligence (AI) finds application in a wide range of domains, including image classification, healthcare, and speech recognition recent years. Even with the rapid improvements of mobile hardware, the main obstacles in deploying the standard DNNs on mobile devices are the high computational and memory requirements during both training and inference processes. Recently, several model compression techniques have been applied to develop compact DNNs for mobile deployment [1], [2]. An array of lightweight CNN architectures has been designed specially for CV tasks [3], [4]. In addition, the compact RNN architectures are mostly developed and applied in lightweight (IoTs) applications, to learn from on-device sequential/temporal data. Despite the initial success, the development of on-device NLP applications has lagged behind applications in other domains. Only a small number of compressed RNN models are available for resourcehungry NLP applications [5].
Up-to-date, the vast majority of mobile AI applications focus on inference since the more computationally intense on-device training has not been demonstrated as a feasible task. In addition to the computational challenge, a trustworthy compressed RNN model needs to tackle the following major challenges: (1) information loss in model compression, (2) adversarial robustness, and (3) lack of explainability and personalization. Systematically addressing these challenges would significantly promote the wide adoption of the compressed RNN models in NLP applications.
In this work, we design a novel training scheme ( Figure 1) to address the above challenges via building the adversarial robustness and explainability in our compressed RNN model during the training process, followed by on-device personalization. Thus, our approach avoids the post-hoc adversarial training and attribution based explanation. Although we only demonstrate impressive performance against several adversarial attacks towards text classification tasks, our training scheme is applicable to other RNN-based NLP tasks.
Specifically, our major contributions are: (1) we tackle the information loss in model compression by minimizing the layer-wise feature mapping loss and label distillation loss during the training process, (2) we employ an adversarial robust objective function to enhance model robustness via encouraging the predicted probabilities of false classes to be equally distributed in both the full and compressed models, (3) we enable the model explainability via an explainable aspectbased feature mapping. Furthermore, we retain model personalization via fine-tuning the on-device compressed model using the on-device training data, and (4) our extensive experiments demonstrate the effectiveness of our approach by comparing with baseline compact and compressed RNNs in multiple text classification tasks.

II. RELATED WORK A. Adversarial Attacks and Defense
Both white-box and black-box adversarial attacks [6] generate crafted adversarial examples to fool DNNs into making wrong predictions. In the former, the attacks have complete access to the target model (e.g., model architecture and parameters) and generate adversarial samples exploiting the guidance of the model's gradients [7]. In the latter, the attacks are only allowed to test the target classifiers without any access to the target model [8]. We select three strong attack methods [9]- [11] covering both black-box and white-box attacks, as will be described in the Experiment Setup section.
Recently, an array of defense techniques has been proposed to counter these adversarial attacks. As an alternative to the traditional natural training, which is vulnerable to carefully crafted attacks, adversarial training is a technique that allows DNNs to correctly classify both clean and adversarial examples [7]. However, most existing adversarial training approaches are based on one specific type of adversarial attacks, leading to a compromised generalization of defense capability on adversarial examples from other attacks [12]. Besides, the high computing cost in generating strong adversarial examples makes the standard adversarial training computationally prohibitive [13], especially on large-scale NLP datasets.
In tackling these problems, efficient approaches have been proposed [14] to improve the adversarial robustness of DNNs via learning discriminative features through minimizing welldesigned loss functions. [15] proposed a novel loss objective called Complement Objective Training (COT) that achieved good robustness against single-step adversarial attacks via maximizing the likelihood of the ground-truth classes while neutralizing the probabilities of the complementary (false) classes using two different loss objectives. However, these two loss objectives did not have a coordination mechanism to work together efficiently. In order to reconcile the competition between them, a new approach called Guided Complement Entropy (GCE) has been recently proposed [16] for CV applications. Specifically, GCE adds a "guided" term to maintain the balance between the true class and the false classes, which helps improve the adversarial robustness. Without loss of generality, we employ GCE to extract adversarially robust features from large-scale NLP datasets and demonstrate the improvement of the adversarial robustness of our models against various adversarial attacks. To the best of our knowledge, we are among the first to leverage a well-designed loss function to enable the adversarial robustness of model compression for NLP applications.

B. Compressed RNN Models
Several model compression techniques have been demonstrated to achieve compactness, e.g., designing tailor-made lightweight architectures [3] and generating compressed models via automatic Neural Architecture Search [17]. Quantization [1] and network pruning [2] reduce the model size at the expense of reduced prediction accuracy. Knowledge distillation [18] is used to improve the performance of the lightweight models by transferring the knowledge from a large teacher network to a lightweight student network.
In order to deal with on-device text classification tasks, [5] proposed a new architecture that jointly trains a full neural network and a simpler projection network leveraging random projections to transform inputs or intermediate representations into bits. The projection network encoded lightweight and efficient computing operations in bit space to reduce memory footprint. Since then, a few more advanced projection networks have been proposed to achieve better performance. Self-Governing Neural Network (SGNN) [19] was proposed to learn compact projection vectors with local sensitive hashing, which surmounted the need for pre-trained word embeddings with huge parameters in complex networks. [20] proposed a novel projection attention neural network named PRADO combing trainable projections with attention and convolutions. The compressed 200-Kilobytes model had achieved good performance on multiple text classification tasks.
However, most of the above approaches overlook the important issue of adversarial robustness in NLP applications. Recent literature has focused on the trade-off between adversarial robustness and neural network compression with application in CV. [21] investigated the extent to which adversarial samples are transferable between uncompressed and compressed DNNs. [22] proposed a novel Adversarially Trained Model Compression (ATMC) framework that obtains a remarkably favorable trade-off among model size, accuracy, and robustness. [23] proposed a framework of concurrent adversarial training and weight pruning that enables model compression while still preserving the adversarial robustness. Different from all the above state-of-the-art solutions, we tailor-made model compression training scheme for NLP to enable adversarially robust, explainable, and personalized ondevice applications.

C. Compact RNN Models
RNN models have achieved significant success in learning complex patterns for temporal/sequential data (e.g., sensor signal, natural language). Beyond the classical LSTM and GRU architectures, more sophisticated RNNs with skip connections and residual blocks [24] and those combined with CNNs have been developed to allow the RNNs to go 'deeper' and achieve better performance. Despite the state-of-the-art performance, these heavyweight RNN models are resource-hungry and not suitable for on-device deployment.
More recently, tiny RNNs with small parameter sizes (e.g., 10K or less), have received increasing attention due to their high application potential to on-device deployment in IoT environment. [25] proposed FastRNN/FastGRNN by adding residual connections and gating on the standard RNNs, which outperformed LSTM and GRU in prediction accuracy with fewer parameters (10K versus 30K). AntisymmetricRNN [26] is designed based on ordinary differential equations (ODEs); this model achieves comparable performance with both LSTM and GRU with a much smaller number of parameters (10K). iRNN [27] is a similar model based on ODEs, which is designed to facilitate the RNN training with identity gradient. It achieves a better performance than GRU and a comparable performance to LSTM with only 7.80K model parameters. Despite the impressive performance in IoT applications, thus

III. METHOD
A. Training Scheme Figure 1 illustrates our training scheme, which is composed of a new compression technique to minimize information loss, aspect-based feature mapping to ensure explainability, and on-device fine-tuning to enable personalization. Specifically, we design feature mapping and label distillation layers to minimize information loss during model compression. Additionally, the aspect-based feature mapping method enables the model explainability via minimizing the interpretable loss during training. Finally, the compressed model is fine-tuned with different values of hyper-parameter T in the label distillation layer, leveraging on-device training data for personalization.
We denote an input text as {w 1 , . . . , w i , . . . , w n }, where i is the index and n is the number of words. The first layer in most models designed for NLP tasks applies an embedding layer with trainable parameters W e ∈ R d×V to map each word w i to a fixed-length d-dimension vector e i ∈ R d , where V denotes the vocabulary size. The embedded word vectors e are then processed by the remaining layers. To retain sufficient embedding information, most models use a large vocabulary size V (ranging between hundreds of thousands to millions) and a high embedding dimension d (e.g., 100 or higher), leading to a huge number of parameters in W e . As there is a minimum required vocabulary size to achieve a specific performance [28], we set the embedding layer to a low dimension (e.g., 5, 10, and 20) in the compressed model to decrease the number of parameters in W e . In order to minimize the embedding information loss, we design a feature mapping method that allows the compressed model to learn embedding information from the pre-trained full model by minimizing the difference between the two embedded features. Specifically, we first employ an autoencoder to compress the high dimension embedding feature e f in the full model into the low dimensionê f embedding feature. We then minimize the distance ||ê f − e c || 2 ensuringê f ≈ e c during training. f and c indicate the full and compressed models, respectively.
As shown in Figure 1, following the embedding layer is a recurrent neural network layer, e.g., Long Short-Term Memory (LSTM). The number of parameters in LSTM layer can be calculated as: 4 × H × ((d + 1) + H) [29], where H is the size of latent feature and d is the input size. So the latent feature size H can greatly affect the number of parameters. As such, we set a small hidden state size in LSTM hidden layer without using attentions, short-cut connections, or other sophisticated additions to reduce the number of parameters in the compressed model. We employ another autoencoder to encode the high dimension latent features h f into the low dimensionĥ f . Then we minimize the distance ||ĥ f − h c || 2 to ensureĥ f ≈ h c . Additionally, we design an aspect-based feature mapping in this layer to enable the explainability of the model, which is explained in more detail in the next section.
The third layer in our training scheme exploits label distillation, which enforces the compressed model to mimic the prediction behavior of the full model by training the former with more informative soft labels generated by the latter [18]. Furthermore, [30] has demonstrated that a good manipulation of temperature T can push the softmax scores of in-and outof-distribution (OOD) images further apart from each other, making the OOD images more distinguishable. Inspired by this, we fine-tune the compressed model on each user's device with personalized training data with different values of hyper- parameter T to achieve on-device personalization.

B. Explainable Feature Mapping
Our aspect-based feature mapping ( Figure 2) enables the explainability of the model compression leveraging the ubiquitous aspect information, which is an additional input feature of our models. Aspect-based explainable models have been developed to solve problems in collaborative filtering and sentiment analysis [31]. For example, food, price, service, and ambience are aspects in Restaurant domain to explain the sentiment polarities of the user reviews, and genres are used as aspects in Movie domain for recommendation. We first apply one-hot encoding to represent a particular aspect domain, then embed these aspect one-hot vectors into an aspect-guided latent space with the same embedding dimension d in the embedding layer, denoted as a = {a 1 , . . . , a j , . . . , a m }, where j is the index and m is the number of the aspects. Then, we map the latent features h from the LSTM layer into the same space with these aspect features, and get the aspect attention weights through a self-attention mechanism, where α j = Softmax(h) is the attention weight for j-th aspect. In this way, we derive a new aspect-based latent features h a by combining the aspect features a with the aspect attention weights α as: h a = m j=1 α j a j . Then, h a is passed to the following fully connected layers. Our goal here is to minimize the distances between the general feature and the aspect-based features (i.e., ||h a − h|| 2 ) to ensure the similarity between them (i.e., h ≈ h a ). Therefore, our approach makes the model explanation intrinsically and can really answer "how" the compressed model generates corresponding predictions supervised by the novel interpretable loss objective [32]. In the experiments, we employ a novel metric (hit-ratio) as a quantitative evaluation of our model intrinsic explainability, as will be described in the Results and Discussion section.

C. Training Objective
We select different loss functions for the components in our training scheme according to the different training objectives. We employ a well-designed loss function GCE [16] instead of the traditional CrossEntropy (CE) not only to improve the adversarial robustness of the full model and the compressed model but also to maximize the transfer of robustness from the full model to the compressed model. Thus, the text classification task loss is denoted L T = GCE(y,ŷ). We minimize the Mean Square Errors (MSE) between the high-dimension features from the full model and the low-dimension features from the compressed model aiming to assimilate them in the two feature mapping layers: L EM = MSE(ê f , e c ) and L LM = MSE(ĥ f , h c ), respectively. Additionally, we minimize the Kullback-Leibler (KL) divergence loss, denoted as L LD = KLDiv(Softmax(o f /T ), Softmax(o c /T )), between the output label probability distributions in the label distillation layer. For the two autoencoders used in the feature mapping layers, we minimize MSE between the inputs and the reconstructed outputs to derive a better feature mapping: L AE = MSE(e f , e r ) + MSE(h f , h r ), e r and h r here are the reconstructed outputs. We also use MSE as the model interpretable loss: L INT = MSE(h a , h) to derive explainable feature mapping.
The general training objective function consists of several components, formally: L = λ 1 L T + λ 2 (L EM + L LM + L LD ) + λ 3 L AE + λ 4 L INT , where λ 1 , λ 2 , λ 3 , and λ 4 are tuning hyperparameters to leverage the relative importance of different loss objectives. With that, the compressed model is duly regularized by the pre-trained full model. We note the general loss objective is sufficiently flexible that each loss objective can be retained/dropped according to the real-world need.

IV. EXPERIMENT SETUP
Our experiments are conducted with multiple text classification tasks, such as sentiment analysis (Amazon and Yelp), news categorization (AG's News), and topic classification (Yahoo). In particular, we want to answer the following questions through the experiments: (1) Can the compressed model achieve a competitive performance with the cloudbased model through our new training scheme? (2) Does the compressed model ensure adversarial robustness against strong adversarial attacks? (3) Is the compressed model explainable for on-device deployment?

A. Datasets
Statistics of the text classification datasets used in our experiments are listed in Table I. We conduct our explainable feature mapping experiments on Rest-2014 dataset, which is from SemEval 2014 [33] containing reviews of restaurant domains together with some aspect features such as food, price, service, and ambience. We select Senti140 from LEAF [34] to evaluate the performance of our on-cloud model compression and ondevice personalization. Specifically, we randomly select 5,000 different users from the Senti140 dataset, including 18,400 positive samples and 16,200 negative samples, to train the oncloud model and compress the on-device model. After this, we select the user devices containing the most abundant training samples to fine-tune the compressed models for further improving the performance and retaining model personality.

B. Adversarial Attacks
Most strong adversarial attacks [6] target on the pre-trained embedding matrix (e.g., [35]). Others (e.g., [36]) need to apply additional meta-data such as SentiWordNet [37]. Both methods iteratively search through the embedding matrix requiring a long time to find the effective perturbations, representing a substantial obstacle for attacking in real-time. Furthermore, their performance on the transferred attacks decrease dramatically compared to that on the original architecture and data, demonstrating a poor generalization ability [6]. Therefore, we select two strong one-off attacks, i.e., Replaceone [10] and Gradient [9], which are more efficient and with the minimal alteration that is more suitable for real-world applications. We also choose another strong attack, i.e., probability weighted word saliency (PWWS) [11], which makes the perturbations not only unperceivable but also preserves maximal semantic similarity. We use the same settings as in [10], [11] for our experiments. In more detail: Replaceone. [10] applied several different black-box scoring functions and word transformation methods to generate adversarial samples with minimum word changes. We use Replaceone, a more efficient yet effective scoring function, to find the most important words then swap two adjacent letters to generate new words in the adversarial samples. Gradient. [9] proposed a white-box attack that first used gradients to identify salient words in the original samples and then modified these words to generate adversarial samples. PWWS. [11] proposed a greedy algorithm based white-box attack using a new word replacement order determined by both the word saliency and the classification probability to generate adversarial samples with lexical/grammatical correctness and semantic similarity.

C. The Compared Methods
Our goal is to develop adversarially robust model compression for NLP tasks, which not only achieves competitive performance in classifying both clean and adversarial samples but also satisfies the on-device resource constraints. Although our compressed model is intended for on-device deployment, we compare with some on-cloud baseline models that are designed to exploit the full extent of cloud resources, i.e., bag-ofwords TF-IDF, N-grams TF-IDF, char-level CNN, word-level CNN, and LSTM [38] to demonstrate our competencies. We also compare our compressed models with other compressed and compact models designed for on-device applications. We compare with two existing on-device compressed neural network models for NLP applications (i.e., SGNN [19] and PRADO [20]) in terms of the test performance using clean samples only since (1) they are not designed for defending against adversarial attacks and (2) there are no source codes available. Moreover, we compare with the compact model, FastGRNN [25], which is originally designed for IoT applications and recently demonstrated promising performance in NLP applications. We discuss the comparison results in Table  IV. We provide more implementation details and our hyperparameters tuning in Table III. We will release our code in future proceedings.

D. Evaluation Metrics
In our experiments, we not only consider the performance of the compressed models trained with clean texts but also their adversarial robustness towards various adversarial attacks. We evaluate the models' performance in terms of accuracy (Acc) and macro-F1 scores (F1) for text classification tasks. We also test our model robustness on thousands of adversarial examples generated from different adversarial attacks separately. We report the adversarial accuracy (AdvAcc) and adversarial macro-F1 score (AdvF1) to evaluate the adversarial robustness of the models. In addition, we design a novel hit-ratio to evaluate our model explainability. Table II shows the performance and adversarial robustness of the compressed models, either trained in a conventional way or in the proposed training scheme (ours). It is observed that our compressed models achieve an overall better performance on all the evaluation metrics. As our new training scheme exploits feature mapping and label distillation to enable the compressed models to learn information from the pre-trained full models, it is capable of reducing the information loss during model compression, leading to marked improvement on clean sample accuracy and macro-F1 scores. In addition, the compressed models trained with GCE loss improve the adversarial robustness compared to the ones trained with the CE loss in a vast majority of comparisons, highlighting the advantage of adversarially robust model compression.

A. Performance Comparison
We further compare the performance of our compressed models with the other compressed, compact models and full models in Table IV in both clean and adversarial example settings (wherever applicable). Note the results of PRADO [20] and SGNN [19] are cited directly from the original papers since no source codes are made available. Therefore, we only compare the clean sample accuracy with these two compressed RNN models since they are not designed for mitigating adversarial attacks and hence not adversarially robust. In Table  IV, our compressed model achieves a better performance than SGNN. Moreover, it maintains a comparable clean sample accuracy with PRADO yet demonstrates impressive adversarial robustness, which is one of the unique features of our model compression technique.
We also compare our compressed RNN model with a manually designed compact RNN model named FastGRNN    [25]. Specifically, we re-implemented the algorithm based on the package released in the original paper (https://pypi. org/project/edgeml-pytorch/). We keep the same settings of adversarial attack methods to make a fair comparison in terms of adversarial robustness between our compressed model and the compact FastGRNN. From Table IV we observe better performance of our compressed model on both clean and adversarial examples than FastGRNN. Both clean and adversarial accuracies are critical for on-device NLP applications. For example, in cybersecurity, detection of business email compromise (BEC) and email account compromise (EAC) scams has become a rising challenge since it does not contain malware but only social engineering messages. As such, the on-device NLP app needs to look into emails' text contents to perform the adversarial attack detection. Finally, we show that our models outperform a number of competing full models in terms of both clean and adversarial accuracies.

B. Model Explainability
In Method section, we describe our explainable aspect-based feature mapping as an optional component of model compression training scheme. We first calculate attention weights score j for j-th aspect by adding them up for each token in texts, formally: score j = n i=1 α ji . Then we identify the aspect as the one with the highest attention weight denoted as A H , and compare with the ground truth aspect coded in the one-hot vector A. Note A H and A here are the index values. If these two are consistent, formally: A H = A, we consider it as a successful hit, demonstrating that the model is explainable in terms of this aspect. Thus, we calculate a hit-ratio for the test set (i.e., the number of successful hits divided by the number of samples). A large hit-ratio indicates the compressed model generates the predictions based on the pivotal aspect with larger attention wights demonstrating the model achieves better explainability.
As shown in Figure 3 and Table IV, our compressed model achieves a comparable performance with the full model in both clean and adversarial sample settings. In addition, compared to the conventionally trained compressed models (Figure 3), our model achieves a better performance in terms of both accuracy and explainability (hit-ratio +12%). This improvement is mainly due to the fact that the features of our compressed model are derived from the full model via an interpretable feature mapping guided by the pivotal aspects.

C. Model Personalization
As it is hard to get a non-trivial number of data samples on users' devices to train a personal model, we propose a twostep strategy to retain the model personality. We first train a global model on a global dataset collected from 5000 users. Then we fine-tune it on each user's private training data while deploying it on-device. Additionally, we find it effective to leverage the hyper-parameters T in the label distillation layer while training the global model to achieve better performance on the local data. As shown in Figure 4, each on-device model achieves its best performance with a different value of T . In more details, in devices such as User 1, the fine-tuned personal model achieves a better model performance than the global model, probably due to the higher quality of the private training data. Otherwise, we use the global model instead of  [20]. the fine-tuned personal model (e.g. User 3) and get improved accuracy (69.6→75.1) and F1 score (66.5→68.5).

D. Model Size Selection and Ablation Study
In Table V, we investigate the effect of embedding dimension (d) and latent feature size (H) on the model compression performance. We set both d and H values at 100 for our full model, resulting in the model size of 2 million (2M) parameters. Whereas for the three compressed models, we set both d and H values at 5, 10, or 20, resulting in the model sizes of 100K, 200K, and 400K parameters, respectively. The compressed models with larger d and H achieve better performance due to lower information loss. In Table  VI, we show an ablation study to examine the effectiveness of the key components (e.g., embedding feature mapping layer, latent feature mapping layer, and label distillation layer) using three different datasets. The compressed models with all the components achieve the best performance in both clean and adversarial sample accuracy and macro-F1 score. The importance of a layer component increases as it gets closer to the output.

VI. CONCLUSIONS AND FUTURE WORK
In this work, we design a new training scheme for model compression ensuring adversarial robustness, explainability,   and personalization for NLP applications. Our novel aspectbased feature mapping and label distillation minimize the information loss and maximize the explainability of model compression, and the new training objective ensures model's adversarial robustness. The performance can be further improved via on-device personalization. Unlike the adversarial training that is computationally prohibitive and limited to the known attacks, our training scheme is sufficiently flexible, effective, and robust for on-device NLP applications. In future work, we will generalize our training scheme to other on-device NLP tasks, such as Question Answering, Reading Comprehension, and Neural Machine Translation. Furthermore, transformerbased models (e.g BERT [39]) gain a lot of attention dealing with NLP tasks recently. There are several recent studies on compressing BERT models, e.g., MobileBERT [40] and TinyBERT [41]. These approaches mainly focus on model compression, while none of them deals with model adversarial robustness and explainability. We will extend our training scheme to the widely used transformer-based models.