id
stringlengths
10
10
title
stringlengths
26
192
abstract
stringlengths
172
1.92k
authors
stringlengths
7
591
published_date
stringlengths
20
20
link
stringlengths
33
33
markdown
stringlengths
269
344k
2307.07603
Gastrointestinal Disease Classification through Explainable and Cost-Sensitive Deep Neural Networks with Supervised Contrastive Learning
Gastrointestinal diseases pose significant healthcare chall-enges as they manifest in diverse ways and can lead to potential complications. Ensuring precise and timely classification of these diseases is pivotal in guiding treatment choices and enhancing patient outcomes. This paper introduces a novel approach on classifying gastrointestinal diseases by leveraging cost-sensitive pre-trained deep convolutional neural network (CNN) architectures with supervised contrastive learning. Our approach enables the network to learn representations that capture vital disease-related features, while also considering the relationships of similarity between samples. To tackle the challenges posed by imbalanced datasets and the cost-sensitive nature of misclassification errors in healthcare, we incorporate cost-sensitive learning. By assigning distinct costs to misclassifications based on the disease class, we prioritize accurate classification of critical conditions. Furthermore, we enhance the interpretability of our model by integrating gradient-based techniques from explainable artificial intelligence (AI). This inclusion provides valuable insights into the decision-making process of the network, aiding in understanding the features that contribute to disease classification. To assess the effectiveness of our proposed approach, we perform extensive experiments on a comprehensive gastrointestinal disease dataset, such as the Hyper-Kvasir dataset. Through thorough comparisons with existing works, we demonstrate the strong classification accuracy, robustness and interpretability of our model. We have made the implementation of our proposed approach publicly available at https://github.com/dibya404/Gastrointestinal-Disease-Classification-through-Explainable-and-Cost-Sensitive-DNN-with-SCL
Dibya Nath, G. M. Shahariar
2023-07-14T19:56:30Z
http://arxiv.org/abs/2307.07603v1
Gastrointestinal Disease Classification through Explainable and Cost-Sensitive Deep Neural Networks with Supervised Contrastive Learning ###### Abstract Gastrointestinal diseases pose significant healthcare challenges as they manifest in diverse ways and can lead to potential complications. Ensuring precise and timely classification of these diseases is pivotal in guiding treatment choices and enhancing patient outcomes. This paper introduces a novel approach on classifying gastrointestinal diseases by leveraging cost-sensitive pre-trained deep convolutional neural network (CNN) architectures with supervised contrastive learning. Our approach enables the network to learn representations that capture vital disease-related features, while also considering the relationships of similarity between samples. To tackle the challenges posed by imbalanced datasets and the cost-sensitive nature of misclassification errors in healthcare, we incorporate cost-sensitive learning. By assigning distinct costs to misclassifications based on the disease class, we prioritize accurate classification of critical conditions. Furthermore, we enhance the interpretability of our model by integrating gradient-based techniques from explainable artificial intelligence (AI). This inclusion provides valuable insights into the decision-making process of the network, aiding in understanding the features that contribute to disease classification. To assess the effectiveness of our proposed approach, we perform extensive experiments on a comprehensive gastrointestinal disease dataset, such as the Hyper-Kvasir dataset. Through thorough comparisons with existing works, we demonstrate the strong classification accuracy, robustness and interpretability of our model. We have made the implementation of our proposed approach publicly available1. Footnote 1: [https://github.com/dibya404/Gastrointestinal-Disease-Classification-through-Explainable-and-Cost-Sensitive-DNN-with-SCL](https://github.com/dibya404/Gastrointestinal-Disease-Classification-through-Explainable-and-Cost-Sensitive-DNN-with-SCL) Keywords:CNN, HyperKvasir, Contrastive Learning, Cost-sensitive learning, Explainable AI, Medical imaging, disease classification ## 1 Introduction The gastrointestinal (GI) tract is prone to numerous diseases and anomalies that can significantly impact an individual's health and well being. The International Agency for Research on Cancer has reported that the incidence of gastrointestinal cancer globally in 2018 was estimated at 4.8 million new cases, which accounted for 26% of all cancer cases worldwide and the number of deaths associated with gastrointestinal cancer was estimated to be 35% of all cancer-related deaths globally [1]. Certain conditions can be life-threatening and require prompt detection and intervention to increase the chances of successful treatment and full recovery. But it is unfortunate that certain gastrointestinal diseases pose challenges in their detection or may create ambiguity during medical screening due to the presence of image noise that masks important details [2]. Endoscopy and colonoscopy are currently the standard procedures for performing investigations of the GI tract. Endoscopy and colonoscopy are intrusive procedures that involve the insertion of a tube, with a small camera attached to it, either orally or rectally which requires thorough examination by a doctor to inspect the interior of the GI tract organs and investigate for any anomalies such as polyps (small, benign growths), ulcers or cancer. The ability to identify polyps influences the likelihood of developing cancer. Up to 20% of the polyps can be undetected during examination [3]. Furthermore, the subjective interpretation of endoscopy images can be time-intensive and minimally repetitive, potentially leading to an inaccurate diagnosis [2]. Given the potential for inaccuracies in diagnosis by human professionals, as a result of human error and other limitations, the utilization of a computer-aided automated system could be advantageous in detecting gastrointestinal polyps in their early stages of cancer. Deep learning techniques, the representation of an alternative form of machine learning methods, have been applied in multiple aspects of gastrointestinal endoscopy, that include colorectal polyp detection and classification, analysis of endoscopic images for diagnosis of helicobacter pylori infection detection and depth assessment of early gastric cancer, and detection of various abnormalities in wireless capsule endoscopy images [4; 5; 6]. In this paper, we propose cost-sensitive pre-trained convolutional neural network (CNN) architectures (EfficientNet, DenseNet, ResNet, Xception, Inception-v3) which are fine-tuned using supervised contrastive training objective for diagnosing gastrointestinal diseases on 23 distinct classes. No prior studies have explored this combination in the context of gastrointestinal disease detection. Supervised contrastive learning [7] is a training approach that has shown improved performance compared to traditional supervised training using cross-entropy loss in classification tasks. This method involves a two-stage process for training an image classification model. Firstly, an encoder is trained to generate vector representations of input images in a way that images from the same class have higher similarity in their vector representations compared to images from different classes. Secondly, the learned representations are utilized for downstream tasks by fine-tuning a classifier while keeping the encoder frozen. To enhance the training process of our proposed approach, we employed cost-sensitive learning, which considers the costs associated with prediction errors and other potential costs when training the classifier model. The lack of transparency and interpretability in modern AI systems can be especially concerning in domains like healthcare, where AI-driven decisions can significantly impact human lives and well-being. Thus, we leveraged explainable artificial intelligence (XAI) techniques such as GradCAM, GradCAM++, faster version of ScoreCAM, LayerCAM to provide visual explanations for the classifier's decisions regarding classifying input images. The rest of the paper is organized as follows: section 2 presents some of the related works, section 3 contains a brief overview of the pre-trained models and working procedures of the cost-sensitive, contrastive learning and explainable AI techniques, the proposed methodology is detailed in section 4, performance evaluation of the proposed approach is reported in section 5, section 6 illustrates the interpretation of the proposed approach and finally, section 7 concludes the study with some future research directions. ## 2 Related Works Several prior works have explored the utilization of pre-trained convolutional neural network (CNN) architectures and transfer learning. Below, we provide a discussion of some of these relevant studies. For polyp detection, localization, and segmentation Jha et al. [8] evaluated several state-of-the-art methods on Kvasir-SEG dataset. For the detection and localization, the author proposed ColonSegNet, which displayed a comparison between mean IoU (0.81) and average precision (0.80), accompanied with 180 fps speed. ColonSegNet reached a dice coefficient of 0.8206. For the segmentation, the best average speed was 182.38 fps. Khan et al. [9] utilized a Private Stomach dataset comprising ulcer, bleeding, and healthy classes. They fine-tuned Inception-v3, DenseNet201 and AlexNet, and transformed them into SecureCNN models for feature extraction from the images and feature optimization of the network. The outcome of feature networks optimization without fine-tuning manifested as a classification accuracy, a false negative rate of respectively 92.4% and 7.6%. Upon using optimized features of fine-tuned networks, the classification accuracy improved by 4.76% to 96.8%, where the false negative rate was 3.2%. Sun et al [10] used their own dataset of gastroscopic images and applied the DenseNet-121 network as the backbone on the ImageNet dataset and applied the parameters that were pre-trained before the fully-connected layers. They added a non-local block into DenseNet and through extensive experimentation they achieved an accuracy, a recall and an F1-score of respectively 96.79%, 94.92%, and 94.70% utilizing proposed improved DenseNet. The authors compared their method with Xception, Inception, ResNet-101, and DenseNet-121 models to demonstrate the superior achievement of the introduced method. Shin et al. [11] employed polyp-frame datasets that are publicly available, and two colonoscopy video databases to apply a region-based CNN model, using Inception ResNet model as transfer learning with the purpose of identifying polyps automatically in colonoscopy images and videos. As the dataset is small and the detection task is challenging, four different image augmentation strategies were designed and examined for training deep networks. The Aug-I based method correctly detects 3137 out of 3856 polyps, but the false positives number was 1145, resulting in a recall, a precision of respectively 81.4% and 73.3%. For polyp detection purposes Ribeiro et al. [12] performed binary classification and applied a transfer learning approach wherein the selected architectures were: ResNet-34, ResNet-50, ResNet-152, MobileNetV2, and VGG16_bn. Upon observing the performance, ResNet-152 was elected superior with 96.60% accuracy, 94.30% precision, 94.30% recall and 0.90 f1 score. ## 3 Background Study **(a) Pre-trained Convolutional Neural Networks:** Convolutional Neural Networks (CNNs) are a type of artificial neural network outlined to handle data such as images or videos, that incorporates a grid-like structure. They consist of several layers that perform a series of operations on the input data, including convolution, pooling, and activation functions. These layers work together to extricate and learn pertinent features from the input data, allowing the network to recognize complex objects and patterns. **ResNet50**: Residual Network (ResNet) is a deep learning architecture proposed by He et al. [13]. One of the major advancements introduced by ResNet is the incorporation of skip connections. These skip connections enable the network to bypass certain layers and directly connect earlier layers to later ones, allowing for the flow of information to traverse more easily. ResNet50, a specific variant of ResNet, is particularly notable as it comprises 50 layers within the architecture. This specific configuration of ResNet50 has gained significant popularity and has been extensively utilized for various image classification and computer vision tasks. **EfficientNet**: EfficientNet is a deep learning architecture designed for image classification tasks, which was introduced by Tan and Le [14]. The authors proposed a novel approach called compound scaling, which aims to balance the depth, width, and resolution factors of convolutional neural networks (CNNs). By carefully scaling the different dimensions of the network, EfficientNet achieves an optimal balance between model size and computational efficiency, resulting in highly effective image classification capabilities. **DenseNet**: Dense Convolutional Network (DenseNet) was proposed by Huang et al. [15]. The assessment of their proposed architecture on CIFAR-10, CIFAR-100, SVHN, and ImageNet revealed DenseNets as out-performer among the existing state-of-the-art models on most of these benchmarks while achieving high accuracy with reduced computational requirements. The primary innovation of DenseNet is its use of dense \(L(L+1)/2\) direct connectivity between layers where in traditional CNN, \(L\) layers have \(L\) connections. **Inception**: Inception was introduced by Szegedy et al. [16].The key innovation of Inception is the use of a multi-branch architecture allowing the network to capture features using filters of different sizes at different scales. Other deep learning models, such as Inception-v3 were derived from Inception architecture. **Xception**: Xception is a deep learning architecture that was introduced by Francois Chollet [17]. The key innovation of Xception lies in its utilization of depthwise separable convolutions, which differ from traditional convolutions. By employing this novel convolutional technique, Xception achieves improved efficiency and effectiveness in capturing spatial and channel-wise dependencies within the network, leading to enhanced classification capabilities. **(b) Supervised Contrastive Learning:** The primary objective of supervised contrastive learning [7] is to bring images belonging to the same class closer together in the embedding space, while simultaneously creating greater separation between images of different classes. By doing so, it enables the model to learn meaningful and compact representations that capture high-level semantic information. Contrastive learning relies on the use of positive and negative pairs of images. Positive pairs are formed by taking two augmented variations of an identical image, whereas negative pairs are composed of images belonging to distinct classes. The aim is to maximize the separation between negative pairs and minimize the proximity between positive pairs. To encourage the model to learn robust and invariant representations, strong data augmentation strategies such as random cropping, rotation, color jittering are applied to both images in a pair to capture diverse perspectives of the same object. A similarity metric, such as cosine similarity or Euclidean distance, is employed to quantify the similarity between image representations in the embedding space. One of the main components of supervised contrastive learning is the contrastive training objective. The aim is to enhance similarity between positive pairs of images and decrease similarity between negative pairs in order to improve the quality of image embeddings. several training objectives, such as the TripletMargin loss, MaxMargin loss, Npairs loss, and infoNCE loss can be used to achieve this objective. **(c) Cost-Sensitive Learning:** Cost-sensitive learning refers to a subfield of machine learning that involves incorporating the costs associated with prediction errors while training a machine learning model. This is an area closely linked to imbalanced learning, which deals with classification in datasets where the class distribution is heterogeneous. The primary objective of cost-sensitive learning for imbalanced classification is to assign various costs to the sort of misclassification errors that might occur. Machine learning algorithms designed for classification largely assume that the number of examples contained in each observed class is balanced. However, in real-world scenarios, a dataset that is known as an imbalanced classification problem, may exhibit skewed class distributions. The assumption of uniformity of the costs related with misclassification, such as false positives and false negatives are also often made by the majority of classifiers. A notable example is the diagnosis of cancer, where misclassification of a cancer case as negative carries far more severe consequences than a false positive diagnosis. Because indeed, patients may suffer and lose their lives due to delays in treatment resulting from a missed diagnosis. **(d) Explainable Artificial Intelligence (XAI):** Conventional machine learning models and algorithms often function in a manner that makes it challenging to comprehend the underlying process by which they generate predictions, decisions, or recommendations. In the past few years, there has been a notable increase in the prevalence of intricate decision systems, such as Deep Neural Networks (DNNs), which exhibit a high level of opacity and complexity. The reason behind the success of these models is their large parameter space and efficient learning algorithms, which comprise multiple layers and millions of parameters. Such complexity has made them known as complex black box models that are difficult to interpret. As the use of these black box machine learning models becomes more common in critical scenarios, stakeholders are demanding transparency in their decision-making process. To balance between the high learning performance of current AI systems and the need for transparency, the field of explainable AI (XAI) has emerged. In the field of image processing, two commonly employed explainable artificial intelligence (XAI) techniques are gradient-based methods like GradCAM [18], GradCAM++ [19], faster version of ScoreCAM [20], LayerCAM [21] and perturbation-based methods like LIME [22]. These techniques offer valuable insights into the inner workings of image processing models, aiding in the interpretability and understanding of their predictions. ## 4 Proposed Methodology Figure 1showcases the schematic representation of our proposed methodology. We describe each step below in details. **Step 1) Data augmentation**: Initially, we employed various data augmentation techniques to augment the training data and introduce more diversity. These techniques included random cropping, flipping, color dropping, and color jittering. By applying these augmentation strategies, we aimed to enhance the Figure 1: Schematic diagram of the proposed methodology. variability in the training dataset, allowing the model to learn robust and generalized representations of the data. **Step 2) Image processing**: During this step, we standardized the dimensions of all the images by resizing them to a resolution of 224 \(\times\) 224. This resizing process ensured that all the images had consistent dimensions, enabling compatibility and uniformity throughout the dataset. By reshaping the images to this specific resolution, we prepared them for further processing and analysis in subsequent steps of our workflow. **Step 3) Contrastive training**: We trained a pre-trained CNN architecture (Xception which performed best in our study) using MaxMargin contrastive loss. The pre-trained CNN architecture served as the base encoder in our approach. On top of the encoder, we added two dense layers along with the ReLU activation function to form the projection head. The objective was to minimize the distance between images belonging to the same class within a batch, while maximizing otherwise. **Step 4) Classifier with frozen encoder**: The encoder model was specifically designed to take an image as input and produce a feature vector with multiple dimensions. On top of the frozen encoder, we constructed a classifier comprising a fully-connected layer and a softmax layer for the target classes. During fine-tuning, the classifier was trained using cross-entropy loss while keeping the weights of the trained encoder frozen. Only the weights of the fully-connected layers with softmax were optimized in this process. We fine-tune the classifier model two ways: (a) without cost-sensitive learning and (b) with cost-sensitive learning. To automatically compute the class weights in cost-sensitive learning we used sklearn2 library. Footnote 2: [https://scikit-learn.org/stable/modules/generated/sklearn.utils.class_weight.comp](https://scikit-learn.org/stable/modules/generated/sklearn.utils.class_weight.comp) **Step 5) Interpretation using XAI**: In this particular stage, we employed four XAI techniques, namely GradCAM, GradCAM++, faster version of ScoreCAM, and LayerCAM, to visually illustrate the predictions made by the classifier. These techniques were utilized to provide insights into why the classifier attributed a specific input test image to a particular class. By utilizing these XAI methods, we aimed to gain a better understanding of the decision-making process and provide visual explanations for the classifier's assigned classifications. We repeated all the steps for twelve different pre-trained CNN models including EfficientNetB0, EfficientNetB1, EfficientNetB2, EfficientNetV2B0, EfficientNetV2B1, EfficientNetV2B2, Inception-v3, Xception, ResNet50, DenseNet121, DenseNet169. ## 5 Evaluation In this section, we evaluate our proposed approach in terms of performance analysis. ### Dataset Description The HyperKvasir dataset [23] is a comprehensive collection of high-quality gastrointestinal (GI) endoscopy images and videos, designed to aid medical image analysis research. It comprises a diverse range of images, including normal and abnormal GI tract conditions, captured using different types of endoscopes. The dataset contains annotations such as lesion location and categorical labels for various abnormalities, and with thousands of images and videos, it serves as a valuable resource for tasks like lesion detection, classification, segmentation, and disease localization. The dataset promotes collaboration and supports the development of AI-based solutions for automated analysis in GI endoscopy, which can assist in the diagnosis and treatment of GI disorders. The dataset consists of a total of 110,079 images in JPEG format, out of which 10,662 images are labeled into 23 distinct classes. The images are in RGB format. ### Experiments In this study, we carried out the following two experiments: **(a) Contrastive learning**: We investigated whether training pre-trained CNN Figure 2: Four different contrastive training and test loss curves for ResNet50 model. architectures using supervised contrastive learning before fine-tuning them for the classification task would result in improved performance. **(b) Contrastive then cost-sensitive learning**: We explored whether the pre-trained CNN architecture, trained using contrastive learning, could be further fine-tuned using cost-sensitive cross-entropy training to achieve enhanced classification performance. ### Hyper-parameter settings All experiments were conducted using a 12 GB NVIDIA Tesla K80 GPU on Google Colaboratory. The implementations were carried out using the TensorFlow framework. A batch size of 64, AdamW optimizer, learning rate of 2e-5, and softmax activation function were used for all the experiments. The encoder in the contrastive learning phase was trained for 50 epochs. Due to limited availability of images in certain classes of the original dataset, data augmentation techniques were employed to address the class imbalance during contrastive training. The classifier, with the encoder frozen, was trained for 220 epochs using categorical cross-entropy loss. For experimental purposes, the data was divided into an 80% training set and a 20% testing set. All images were resized to a dimension of \(224\times 224\). \begin{table} \begin{tabular}{c c c c c} \hline **Training** & **Model** & **Test** & **MaxMargin** & **Weighted avg** \\ **Objective** & & **Accuracy** & **Loss** & **F1-score** \\ \hline \multirow{8}{*}{Contrastive Learning} & EfficientNetB0 & 63.61 & 0.045 & 0.56 \\ & EfficientNetB1 & 54.899 & 0.055 & 0.47 \\ & EfficientNetB2 & 60.196 & 0.056 & 0.50 \\ & EfficientNetV2B0 & 71.96 & 0.0335 & 0.66 \\ & EfficientNetV2B1 & 69.432 & 0.03 & 0.62 \\ & EfficientNetV2B2 & 68.21 & 0.047 & 0.61 \\ & ResNet50 & 79.18 & 0.024 & 0.76 \\ & DenseNet121 & 79.6 & 0.335 & 0.75 \\ & DenseNet169 & 82.46 & 0.026 & 0.83 \\ & InceptionV3 & 76.27 & 0.027 & 0.07 \\ & Xception & 83.544 & 0.027 & 0.81 \\ \hline Contrastive Learning + Cost-Sensitive & & & & \\ \hline \multicolumn{2}{c}{ResNet50} & \multirow{2}{*}{88.18} & \multirow{2}{*}{0.84} \\ & EfficientNetB7 [24] & & & \\ \hline \multicolumn{2}{c}{EfficientNet [25]} & \multirow{2}{*}{84} & \multirow{2}{*}{0.84} \\ & (teacher student framework) & & & \\ \hline \end{tabular} \end{table} Table 1: Performance comparison of different models using contrastive and cost-sensitive learning among themselves and with some existing works. ### Evaluation metrics We utilized a variety of evaluation metrics to assess the performance of the models in our study. Accuracy was employed to determine the overall correctness of the model's predictions by comparing the number of correct predictions to the total number of predictions made. Precision was used to evaluate the model's ability to correctly identify positive instances among all instances predicted as positive, thereby aiding in the identification of false positives. Recall, also known as sensitivity, measured the model's capability to accurately detect positive instances among all actual positive instances. The F1 Score, a balanced measure derived from the harmonic mean of precision and recall, provided a comprehensive evaluation of the model's overall performance, considering both metrics simultaneously. These evaluation metrics collectively contributed to a thorough assessment of the models' performance in our study. ### Experimental results & analysis This section presents the outcomes of the conducted experiments. **(a) Contrastive learning:** Initially, we employed four contrastive loss functions: MaxMargin loss, TripletMargin loss, NPairs loss, and supervised NT-XENT loss to train ResNet50 as the encoder during contrastive training. Our analysis revealed that ResNet50 exhibited superior performance in terms of train and test loss when trained with MaxMargin loss. Figure 2 illustrates the training and test loss curves for ResNet50 with the four different contrastive loss functions. Based on these results, we selected MaxMargin loss as the preferred loss function for training all the twelve pre-trained CNN architectures during contrastive training. It is evident from Table 1 that Xception model achieved the best test accuracy of around 84%. EfficientNetB1, EfficientNetB2 and EfficientNetB0 yielded the least satisfactory results with test accuracies of 54.899%, Figure 3: Training and test loss graph for Xception model with and without cost-sensitive learning. 60.196% and 63.61% respectively. While EfficientNetV2B2, EfficientNetV2B1 and EfficientNetV2B0 exhibited slightly better outcomes, their test accuracies were not in close proximity to the highest level of accuracy attained, with values of 68.21%, 69.432% and 71.96% respectively. Inception-v3 performed better than the previously mentioned models with a test accuracy of 76.27% but still fell short of the optimal performance level. The test accuracy of DenseNet121 was 79.6%, which was superior to most other models. However, the encoder test loss was significantly higher, recording 0.335%. In contrast, ResNet50 exhibited a test accuracy of 79.18% and an encoder test loss of 0.024%. **(b) Contrastive then cost-sensitive learning:** Based on the previous experiment, where we observed that the Xception model trained with contrastive learning achieved the highest test accuracy, we proceeded to investigate whether incorporating cost-sensitive learning during the fine-tuning phase of Xception as a classifier could further enhance its classification performance. The results presented in Table 1 demonstrate that the Xception model consistently outperformed the other models, achieving a classifier test accuracy of approximately \begin{table} \begin{tabular}{c c c c c c c} \cline{2-7} & \multicolumn{3}{c}{**Without cost-sensitive**} & \multicolumn{3}{c}{**With cost-sensitive**} \\ \hline **Class Name** & \multicolumn{3}{c}{**Precision Recall F1 - Score**} & \multicolumn{3}{c}{**Precision Recall F1 - Score**} \\ \hline cecum & 0.94 & 0.99 & 0.96 & 0.95 & 1.00 & 0.97 \\ ileum & 0.00 & 0.00 & 0.00 & 0.00 & 0.00 & 0.00 \\ retroflex\_rectum & 0.91 & 0.91 & 0.91 & 0.91 & 0.99 & 0.94 \\ hemorrhoids & 0.00 & 0.00 & 0.00 & 0.00 & 0.00 & 0.00 \\ polyps & 0.96 & 0.99 & 0.98 & 0.99 & 1.00 & 0.99 \\ ulcerative\_colitis\_grade\_0\_1 & 0.00 & 0.00 & 0.00 & 0.00 & 0.00 & 0.00 \\ ulcerative\_colitis\_grade\_1\_2 & 0.00 & 0.00 & 0.00 & 0.00 & 0.00 & 0.00 \\ ulcerative\_colitis\_grade\_2 & 0.52 & 0.76 & 0.62 & 0.56 & 0.94 & 0.70 \\ ulcerative\_colitis\_grade\_2\_3 & 0.00 & 0.00 & 0.00 & 0.00 & 0.00 & 0.00 \\ ulcerative\_colitis\_grade\_3 & 0.00 & 0.00 & 0.00 & 0.00 & 0.00 & 0.00 \\ bbps\_0\_1 & 0.94 & 0.96 & 0.95 & 0.96 & 0.98 & 0.97 \\ bbps\_2\_3 & 0.98 & 0.99 & 0.98 & 1.00 & 1.00 & 1.00 \\ impacted\_stool & 0.94 & 0.71 & 0.81 & 1.00 & 0.85 & 0.92 \\ dyed\_lifted\_polyps & 0.80 & 0.83 & 0.81 & 0.95 & 0.93 & 0.94 \\ dyed\_resection\_margins & 0.83 & 0.81 & 0.82 & 0.94 & 0.96 & 0.95 \\ pylorus & 0.87 & 0.88 & 0.92 & 0.93 & 1.00 & 0.97 \\ retroflex\_stomach & 0.95 & 0.99 & 0.97 & 0.99 & 0.99 & 0.99 \\ z\_line & 0.68 & 0.85 & 0.75 & 0.71 & 0.94 & 0.81 \\ barretts & 0.00 & 0.00 & 0.00 & 0.00 & 0.00 & 0.00 \\ barretts\_short\_segment & 0.00 & 0.00 & 0.00 & 0.00 & 0.00 & 0.00 \\ esophagitis\_a & 0.33 & 0.22 & 0.26 & 0.55 & 0.21 & 0.30 \\ esophagitis\_b\_d & 0.45 & 0.23 & 0.31 & 0.54 & 0.52 & 0.53 \\ \hline **Macro avg** & 0.48 & 0.49 & 0.48 & 0.52 & 0.53 & 0.52 \\ **Weighted avg** & 0.80 & 0.84 & 0.81 & 0.85 & 0.89 & 0.86 \\ \hline \end{tabular} \end{table} Table 2: Classification report for Xception model with and without cost-sensitive learning. 89%. This finding suggests that, given the imbalanced nature of the dataset with 23 classes, assigning appropriate costs to incorrect predictions can greatly benefit the classifier's performance. In Figure 3, we present the graph depicting the train and test loss of Xception with and without the utilization of cost-sensitive learning. Table 2 displays the precision, recall, and F1-scores for each class of Xception, both with and without the incorporation of cost-sensitive learning. These visualizations and metrics provide valuable insights into the performance and impact of cost-sensitive learning on the Xception model. When cost-sensitive learning was not employed for the Xception model, the weighted F1-score achieved was 81%, with precision of 80% and recall of 84%. It yielded macro-average precision, recall and F1-score of 0.48, 0.49 and 0.48 respectively. These results indicate that while the model is successful in identifying a large portion of positive instances, it may also generate more false positives. Despite using equal class weights, the outcomes were not satisfactory. Figure 3 visually depicts the accuracy of the Xception model throughout training, illustrating minimal fluctuations until convergence was reached after 60 epochs. Conversely, the Xception model with the cost-sensitive learning produced macro-average precision, recall and F1-score of 0.52, 0.53, and 0.52, respectively and weighted average precision, recall and F1-score of 0.85, 0.89 and 0.86 respectively. We can deduce that the use of the cost-sensitive learning in fine-tuning the Xception model leads to a superior classification performance. Our approach using Xception model outperformed two existing works as reported in Table 1. We believe that the integration of supervised contrastive learning and cost-sensitive learning enhances feature representation, tackles challenges related to class imbalance and misclassification costs, takes into account context-specific costs, and improves the interpretability and transparency of the methodology. As a result, we observe better outcomes in the detection of gastrointestinal diseases. ## 6 Model interpretation using XAI We utilized a neural network visualization toolkit available at 1 to implement GradCAM, GradCAM++, a faster version of ScoreCAM, and LayerCAM for visualizing the correct and incorrect classifications made by the Xception model with and without cost-sensitive learning. In Figure 4, we present two images that were correctly classified, accompanied by the corresponding XAI explanations using the four visualization techniques. Figure 5 showcases two misclassified images, again with the corresponding XAI explanations. The original image is displayed on the left side, while the XAI visualizations are presented on the right. Footnote 1: [https://github.com/keisen/tf-keras-vis](https://github.com/keisen/tf-keras-vis) Figure 4 provides visualizations of the image explanations using different XAI techniques. Both GradCAM and GradCAM++ show certain areas of interest, but they may not provide sufficient information to fully explain the model's behavior. On the other hand, Faster ScoreCAM effectively highlights the focal points of the image, indicating the model's ability to identify relevant regions of interest. Notably, LayerCAM offers a more realistic explanation by gradually clarifying the region of interest. The red marked regions in the visualizations generated by Faster ScoreCAM and LayerCAM offer clear insights into why the model made its prediction. In Figure 5, we observe two misclassified samples predicted by the Xception model. The XAI techniques provide valuable insights into why the model misclassified these images. Each technique highlights different regions, shedding light on the specific features that led to the misclassification. In the case of the top image, the red marked regions highlighted by the techniques are primarily located in the image border, which may not be reliable features for accurate classification. On the other hand, in the bottom image, there are no visible regions of interest, yet the visualization techniques still emphasize differ Figure 4: Two sample outputs of correctly classified instances by Xception with cost-sensitive learning using XAI techniques. Figure 5: Two sample outputs of misclassified instances by Xception with cost-sensitive learning using XAI techniques. ent regions, indicating the model's confusion in its decision-making process for this misclassification. ## 7 Conclusion The aim of this study was to classify the gastrointestinal diseases using pre-trained convolutional neural network (CNN) models. In order to enhance the accuracy of the model, we incorporated supervised contrastive learning. However, we noticed that the dataset had an imbalance issue, with certain classes having a significantly lower number of samples compared to others. To tackle this problem, we implemented cost-sensitive learning, which assigned higher weights to misclassifications in the minority class. Our experimental findings revealed a significant improvement in the classification accuracy of the CNN models through the combination of supervised contrastive learning and cost-sensitive learning. Additionally, to gain a deeper understanding of the CNN model's decision-making process, we employed explainable artificial intelligence (XAI) techniques. The use of XAI provided valuable insights into the interpretability of the CNN models by shedding light on their decision-making mechanisms. Some potential future research directions include exploring the integration of additional modalities, investigating transferability to other disease domains, developing incremental learning techniques, exploring ensemble methods for combining predictions, and tracking changes in gastrointestinal diseases for personalized treatment planning etc.
2307.05772
Random-Set Neural Networks (RS-NN)
Machine learning is increasingly deployed in safety-critical domains where robustness against adversarial attacks is crucial and erroneous predictions could lead to potentially catastrophic consequences. This highlights the need for learning systems to be equipped with the means to determine a model's confidence in its prediction and the epistemic uncertainty associated with it, 'to know when a model does not know'. In this paper, we propose a novel Random-Set Neural Network (RS-NN) for classification. RS-NN predicts belief functions rather than probability vectors over a set of classes using the mathematics of random sets, i.e., distributions over the power set of the sample space. RS-NN encodes the 'epistemic' uncertainty induced in machine learning by limited training sets via the size of the credal sets associated with the predicted belief functions. Our approach outperforms state-of-the-art Bayesian (LB-BNN, BNN-R) and Ensemble (ENN) methods in a classical evaluation setting in terms of performance, uncertainty estimation and out-of-distribution (OoD) detection on several benchmarks (CIFAR-10 vs SVHN/Intel-Image, MNIST vs FMNIST/KMNIST, ImageNet vs ImageNet-O) and scales effectively to large-scale architectures such as WideResNet-28-10, VGG16, Inception V3, EfficientNetB2, and ViT-Base.
Shireen Kudukkil Manchingal, Muhammad Mubashar, Kaizheng Wang, Keivan Shariatmadar, Fabio Cuzzolin
2023-07-11T20:00:35Z
http://arxiv.org/abs/2307.05772v2
# Random-Set Convolutional Neural Network (RS-CNN) ###### Abstract Machine learning is increasingly deployed in safety-critical domains where robustness against adversarial attacks is crucial and erroneous predictions could lead to potentially catastrophic consequences. This highlights the need for learning systems to be equipped with the means to determine a model's confidence in its prediction and the epistemic uncertainty associated with it, 'to know when a model does not know'. In this paper, we propose a novel Random-Set Convolutional Neural Network (RS-CNN) for classification which predicts belief functions rather than probability vectors over the set of classes, using the mathematics of _random sets_, i.e., distributions over the power set of the sample space. Based on the epistemic deep learning approach, random-set models are capable of representing the 'epistemic' uncertainty induced in machine learning by limited training sets. We estimate epistemic uncertainty by approximating the size of credal sets associated with the predicted belief functions, and experimentally demonstrate how our approach outperforms competing uncertainty-aware approaches in a classical evaluation setting. The performance of RS-CNN is best demonstrated on OOD samples where it manages to capture the true prediction while standard CNNs fail. ## 1 Introduction Despite its recent rise in popularity, in its current form, artificial intelligence (AI) cannot confidently make predictions robust enough to stand the test of data generated by processes different from those studied at training time, even by tiny details, as shown by 'adversarial' results able to fool deep neural networks [66]. While recognising this issue under different names (e.g. _overfitting_[68] or _model adaptation_[52]), traditional machine learning seems unable to address it at a fundamental level. As a result, AI systems suffer from brittle behaviour, and find it hard to operate in new situations. A major cause of this problem is the widespread presence of _epistemic uncertainty_, i.e., uncertainty about the process generating the data itself. In machine learning, this derives from the limited representativeness of the available training sets, in terms of both quantity and quality. As few samples are collected in specific domain distributions, the learnt models have no way to effectively model domain variation. The machine learning community recognises the problem. This has given rise to several proposals for estimating the uncertainty associated with network predictions, including Bayesian Dropout [35], distance-aware priors [28] and the use of random fuzzy sets [27]. An "evidential" deep learning method [70] for uncertainty quantification in classification using Dirichlet distribution and, more recently, epistemic neural networks [63] as a generalisation of Bayesian neural networks have been proposed. None of these methods, however, fully, explicitly capture the epistemic uncertainty stemming from the data issue. Some of them rely on prior knowledge [32], whereas others require setting a desired threshold on the metrics [2]. It has been argued by some that classical probability theory is, in fact, not equipped to model "second-level" uncertainty on the probabilities themselves. This has led in the past to the formulation of numerous (epistemic) uncertainty calculi [18], starting from de Finetti's pioneering work on subjective probability [21], and including possibility theory [30], probability intervals [39], credal sets [51], random sets [61] and imprecise probability [85]. In this paper, we propose to model epistemic uncertainty using a _random set_ representation [57]. As we focus on finite target spaces in a classification setting, we will model uncertainty using _belief functions_[71], the finite incarnation of random sets [17]. The theory of belief functions or theory of evidence [71] is a generalisation of Bayesian inference [79] since classical (discrete) probabilities are simply special belief functions and Bayes' rule is a special case of Dempster's rule of combination. Crucially, in the theory of evidence, priors are not needed to start the inference process, avoiding the selection bias risks that can seriously condition Bayesian reasoning [33]. An interesting geometric approach to uncertainty measures, and belief functions in particular, has been proposed by one of us [19; 10; 11; 16; 15]. To model uncertainty using belief functions, we propose a novel Random-set Convolutional Neural Network based on the principles of the epistemic deep learning concept. Epistemic deep learning [55] argues that a deep neural network producing an outcome for (selected) subsets of the target space is an intrinsically more faithful representation of the epistemic uncertainty associated with the limited quantity and quality of the training data. As they assign probability values to sets of outcomes directly, they naturally model the fact that observations almost invariably come in the form of sets. In an image classification setting, this could be interpreted as a test image being mapped to a _set_ of classes, rather than a single class, when there is uncertainty about the true class. By representing classes as sets, set-valued classification can handle imprecise data more effectively and provide a richer understanding of the underlying uncertainty. It enables the classification model to capture multiple possible interpretations or predictions for each instance, allowing for more robust decision-making and improved performance in scenarios where precise labels may not be available or appropriate. **Contributions** The following are the key contributions of our paper: * A novel _Random-set Convolutional Neural Network_ (RS-CNN) classifier for uncertainty estimation based on the principle of epistemic deep learning, outputting Belief or Mass predictions for sets of classes, training using suitable loss functions generalising classical cross-entropy. * A method for selecting a fixed budget of focal sets (sets with non-zero probability, associated with the network's output neurons) from the power set of classes, thus ensuring scalability. * A method for estimating the epistemic uncertainty of the prediction in terms of the size of the credal set (set of probability vectors) consistent with a predicted belief function. * Experimental validation demonstrating the RS-CNN model outperform other uncertainty-aware models and exhibit superior accuracy on out-of-distribution (OOD) samples compared to the standard CNN. ## 2 Related Work Researchers have recently taken some tentative steps to model uncertainty in machine learning and artificial intelligence. Scientists have adopted measures of epistemic uncertainty [43] to refuse or delay making a decision [36], take actions specifically directed at reducing uncertainty (as in active learning [1]), or exclude highly-uncertain data at decision making time [43]. Networks which abstain from making predictions [36] or the use of Gaussian processes [42] have been proposed [18]. Epistemic learning relates to both approaches which learn sets of models [7] (although differing in its rationale and the mathematics involved) and to approaches in domain adaptation which employ minimax optimisation to learn models adapted to data generated by any probability distribution within a "safe" family [92]. The Naive Credal Classifier (NCC) extends the naive Bayes classifier with imprecise probabilities represented as class sets [90; 9]. Other methods include \(\epsilon\)-contamination [73; 74], non-probabilistic uncertainty [72], and imprecise decision theory [75; 76]. Rough set-based classification approaches have also been proposed [82; 24; 31]. The use of belief functions in uncertainty estimation has been explored previously in several evidential clustering methods such as evidential c-means (ECM) [56] and neural-network based evidential clustering (NN-EVCLUS) [26], in classification fusion [53], and in evidential neural networks for classification [81] and regression [25]. These attempts to introduce concepts from uncertainty theory into machine learning have so far achieved limited impact, possibly because of the lack of a solid underlying principle. Bayesian approaches, pioneered by [6; 54; 59], have established a link between Bayesian neural networks and Gaussian processes. Approximations of full Bayesian inference have been sought using MCMC [58; 37], variational inference [38] and dropout VI [34]. Recent work has addressed challenges such as computational cost, model priors, and tractable function-space variational inference [40; 89; 20; 83; 69]. Bayesian models have been deployed in various domains, including multi-task learning in autonomous vehicles [44], histopathological image classification [67] for cancer diagnostics and medical image segmentation [87]. However, they still pose some challenges since Bayesian models assume that the true data-generating process lies within the model's hypothesis space. If the model prior is misspecified and fails to capture the true underlying process adequately, the estimated epistemic uncertainty may not be reliable. Our approach, on the other hand, does not require sampling during inference nor it requires us to choose a prior, thereby reducing the computational complexity of the model when compared to Bayesian inference and avoiding bias. ## 3 Random-set Convolutional Neural Network Based on the principles of epistemic deep learning [55] mentioned in Sec. 1, we propose the following architecture and training objectives for a novel class of models called _Random-Set convolutional neural networks_ (RS-CNN) that can be trained to output scores for sets of outcomes, and to encode the epistemic uncertainty associated with the prediction in the random set framework. ### Random sets and Belief functions Let us denote by \(\Omega\) and \(\Theta\) the sets of outcomes of two different but related problems \(Q_{1}\) and \(Q_{2}\), respectively. Given a probability measure \(P\) on \(\Omega\), we want to derive a 'degree of belief' \(Bel(A)\) that \(A\subset\Theta\) contains the correct response to \(Q_{2}\). If we call \(\Gamma(\omega)\) the subset of outcomes of \(Q_{2}\) compatible with \(\omega\in\Omega\), \(\omega\) tells us that the answer to \(Q_{2}\) is in \(A\) whenever \(\Gamma(\omega)\subset A\). The _degree of belief_\(Bel(A)\) of an event \(A\subset\Theta\) is then the total probability (in \(\Omega\)) of all the outcomes \(\omega\) of \(Q_{1}\) that satisfy the above condition [22]: \[Bel(A)=P(\{\omega|\Gamma(\omega)\subset A\})=\sum_{\omega\in\Omega:\Gamma( \omega)\subset A}P(\{\omega\}). \tag{1}\] The mapping \(\Gamma:\Omega\to 2^{\Theta}=\{A\subseteq\Theta\}\) is called a _multivalued mapping_ from \(\Omega\) to \(\Theta\). Such a mapping, together with a probability measure \(P\) on \(\Omega\), induces a _belief function_ on \(2^{\Theta}\). In Dempster's original formulation, then, belief functions are objects induced by a source probability measure in a decision space for which we do not have a probability, as long as there exists a 1-many mapping between the two. Belief functions can also be defined axiomatically on the domain of interest (_frame of discernent_) \(\Theta\), without making reference to multivalued mappings. A _basic probability assignment_ (BPA) [71] is a set function [23; 29]\(m:2^{\Theta}\rightarrow[0,1]\) s.t. \(m(\emptyset)=0\) and \(\sum_{A\subset\Theta}m(A)=1\). In Dempster's interpretation, the'mass' \(m(A)\) assigned to \(A\) is in fact the probability \(P(\{\omega\in\Omega:\Gamma(\omega)=A\})\). Shafer and Smets [77], amongst others, have supported a view of mass functions as independently defined on \(\Theta\). Subsets of \(\Theta\) whose mass values are non-zero are called _focal elements_ of \(m\). ### Architecture of Random-Set Convolutional Neural Networks Consider a simple classification neural network. A classifier \(e\) is a mapping from an input space \(X\) to a categorical target space \(Y=[N]\), where \(N\) denotes the number of classes, \(e:X\rightarrow[N]\). In set-valued classification, on the other hand, \(e\) is a mapping from \(X\) to the set of all subsets of \([N]\), the powerset \(\mathbb{P}(N)\), \(e:X\to 2^{[N]}\rightarrow\mathbb{P}(N)\). As shown in Figure 1, a Random-set CNN predicts a mass/belief function for each input data point, rather than softmax probabilities as in a traditional CNN. For \(N\) classes, a random-set CNN will have \(2^{N}\) outputs, which is not computationally feasible for large values of \(N\) due to the exponential complexity. Therefore, instead of using all the \(2^{N}\) subsets as outputs, only \(K\) relevant subsets (\(A_{K}\) focal sets) are chosen out of the \(2^{N}\) subsets available. **Budget**. To obtain these \(K\) focal subsets, given a training set, we extract a feature vector for each training sample from the penultimate layer of a trained standard CNN with \(N\) outputs in the last layer. The t-SNE (t-Distributed Stochastic Neighbor Embedding) [84] algorithm is used to reduce the dimensionality of the feature vectors to 3 dimensions. Then, a Gaussian Mixture Model (GMM) is fit to the reduced feature vectors of each class. Note that our approach is agnostic, as t-SNE could be replaced with any other dimensionality reduction technique, including autoencoders. For each class \(c\), we define an ellipsoid [80] which covers 95% data from that class \(c\) using the eigenvectors and eigenvalues of the covariance matrix \(\Sigma_{c}\) and the mean vector \(\mu_{c}\), \(\forall c\in N\)\(P_{c}\sim\mathcal{N}(x_{c};\mu_{c},\Sigma_{c})\) obtained from the GMM. The class ellipsoids are plotted in a 3-dimensional space and the overlap of each subset in the power set of \(N\) is computed. As it is computationally infeasible to compute overlap for all \(2^{N}\) subsets, we start doing so from cardinality 2 and use early stopping when increasing the cardinality further does not alter the list of most-overlapping sets of classes. We choose the top-\(K\) subsets (\(A_{K}\)) with the highest overlapping ratio, computed as the intersection over union for each subset \(A\) in \(\mathbb{P}(N)\), \(overlap(A)=\cap_{i\in A}A_{i}/\cup_{i\in A}A_{i}\,,\ A\in\mathbb{P}(N)\). These \(K\) non-singleton focal sets, along with the \(N\) singleton sets associated with the original classes, form our new set of classes. **Encoding**. Set-valued observations for random-set CNNs can be defined in two ways: (i) by encoding the belief value \(Bel(A)\) for each subset \(A\) in the power set \(\mathbb{P}(N)\) of \(N\) classes: \(\hat{y}=Bel(A),A\in\mathbb{P}(N)\), or (ii) by encoding its mass value: \(\hat{y}=m(A),A\in\mathbb{P}(N)\). In the belief value encoding, the ground truth vector is \(GT_{Bel}=\{Bel_{1},Bel_{2},\ldots,Bel_{2^{N}}\}\), where \(Bel_{i}\) is the belief value for \(i\in\mathbb{P}(N)\). In the mass value encoding, the ground truth becomes \(GT_{m}=\{m_{1},m_{2},\ldots,m_{2^{N}}\}\), where \(m_{i}\) is the mass value for \(i\in\mathbb{P}(N)\). Note that the trained random-set CNN outputs a mass/belief score for focal sets in \(A_{K}\) only. In this paper, we focus primarily on the Belief RS-CNN (B-RS-CNN) on precise data, as the belief value encoding has a more complex structure and the potential to "teach" the network the set structure. Unlike the Mass RS-CNN (M-RS-CNN), where a mass value is considered "true" when only the true class in contained in subset \(A\), the belief value \(Bel(A)\) is deemed "true" for all instances where the true class is present in subset \(A\). Consequently, the mass value encoding resembles a padded version of the original target vector in traditional CNN, with zeros introduced for all non-singleton sets. The full potential of M-RS-CNN can be demonstrated only in an imprecise data setting, where we have ambigous ground truth. We briefly report the accuracies for M-RS-CNN in Table 1 and provide the formulation of generalisation of Kullback-Leibler(KL) divergence to mass functions as loss to M-RS-CNN (proof in Appendix A.1). For the remainder of this paper, we refer to belief random-set CNN as RS-CNN. #### 3.2.1 Belief Random-Set Convolutional Neural Network The belief random-set CNN is trained on the belief-encoded ground truth representation for \(A_{K}\) subsets, where a belief value \(Bel(A)\) is 1 iff the true class is contained in the subset \(A\). This corresponds to full certainty that the element belongs to that set and there is complete confidence in this proposition. Since the belief RS-CNN mimics the structure of a multi-label classification problem, with respect to the ground truth alone, Binary Cross-Entropy (BCE) (Eq.2) is used as loss function with sigmoid activation to get independent belief functions for each subset \(A_{K}\in\mathbb{P}(N)\), \[\mathcal{L}_{BCE}=ylog(\hat{y}_{Bel})+(1-y)log(1-\hat{y}_{Bel}). \tag{2}\] Figure 1: Model architecture for random-set CNNs. This figure shows the architecture for a belief RS-CNN model that takes as input \(N\) classes, selects the top \(K\) relevant subsets \(A_{K}\) from the powerset \(\mathcal{P}(N)\), and passes the belief encoded ground truth to predict a belief function for each input data point. Mass values and pignistic probability estimates are computed from the predicted belief function. Uncertainty is estimated using the methods described in Sec. 4. The prediction of valid belief functions is facilitated by incorporating a specific term in the loss function that enforces the non-negativity of the mass functions computed using the Moebius inversion formula (Eq. 3). This term ensures that the model only learns valid belief functions, as any predicted belief function \(\hat{Bel}(A)\) with negative mass \(m(A)\) is considered invalid. The Moebius inversion formula to compute masses from belief functions is, \[m(A)=\sum_{B\subseteq A}(-1)^{|A\setminus B|}\hat{Bel}(B). \tag{3}\] Belief functions assign non-negative masses to subsets of a frame of discernment, where the sum of masses over all subsets equals \(1\). A mass sum term \(M_{s}\) and a mass regularization term \(M_{r}\) (Eq. 4), \[M_{s}=\max\left(0,\frac{1}{b_{size}}\sum_{i=1}^{b_{size}}\sum_{A}m_{i}(A)-1 \right)\,\ \ M_{r}=\frac{1}{b_{size}}\sum_{i=1}^{b_{size}}\sum_{A}\max(0,-m_{i}(A)) \tag{4}\] are thus added to \(\mathcal{L}_{BCE}\). \(M_{r}\) and \(M_{s}\) ensure that the loss function only penalizes the model for predictions with negative mass values, effectively encouraging the model to have positive mass values, and the sum of all masses computed from predicted belief functions is less than or equal to 1, respectively. Positive masses are added over the batch size in \(M_{r}\) (Eq. 4). Additionally, hyperparameters \(\alpha\) and \(\beta\) are added to the binary cross-entropy loss to control the relative importance of the BCE with respect to \(M_{r}\) and \(M_{s}\). The final loss for belief RS-CNN the becomes, \[\mathcal{L}_{B-RS}=\mathcal{L}_{BCE}+\alpha M_{r}+\beta M_{s}. \tag{5}\] ## 4 Uncertainty estimation in Random-Set CNN **Pignistic prediction**. A prediction in the form of a precise probability vector can be obtained by computing Smet's pignistic probability transform (Eq.6) [78] for each class \(c\) using the predicted masses of the focal sets in the budget. The pignistic probability, \(BetP\), of each class \(c\) is computed as the sum of the mass of the focal sets \(A\) that contain \(c\) divided by their cardinality. This transformation redistributes the mass values to assign a probability measures to each class \(c\). \[BetP(c)=\sum_{c\in\mathcal{A}}\frac{m(A)}{|A|}. \tag{6}\] The most likely class can then be extracted from the pignistic prediction, and accuracy can be calculated in the standard way. **Entropy of pignistic probability**. The Shannon entropy of the pignistic probability estimate \(BetP\) for each class \(c\) can then be used to assess the uncertainty associated with the predictions. A higher entropy value (Eq. 7) indicates greater uncertainty in the model's predictions. \[H_{RS}=-\sum_{c\in N}BetP(c)\log BetP(c). \tag{7}\] **Size of credal set**. A random-set CNN predicts a belief function (a finite random set) on the target space. A belief function, in turn, is associated with a convex set of probability distributions (a _credal set_[51, 91, 14, 3, 4, 12]) on the space of classes. The size of this credal set thus measures the extent of the epistemic uncertainty associated with the prediction. When the model is confident, the credal set will approach a single, precise probability. When uncertainty is high, the credal set will be wide. Any probability distribution \(P\) such that \(P(A)\geq Bel(A)\ \forall A\subset\Theta\), is said to be _consistent_ with \(Bel\)[49]. Each belief function \(Bel\) thus uniquely identifies a set of probabilities consistent with it, \(\mathcal{P}[Bel]=\{P\in\mathcal{P}|P(A)\geq Bel(A)\}\), where \(\mathcal{P}\) is the set of all probabilities one can define on \(\Theta\). Not all credal sets are consistent with a belief function. credal sets associated with BFs have as vertices all the distributions \(P^{\pi}\) induced by a permutation \(\pi=\{x_{\pi(1)},\ldots,x_{\pi(|\Theta|)}\}\) of the singletons of \(\Theta=\{x_{1},\ldots,x_{n}\}\) of the form [8, 13] \[P^{\pi}[Bel](x_{\pi(i)})=\sum_{A\ni x_{\pi(i)};\ A\ni x_{\pi(j)}\ \forall j<i}m(A). \tag{8}\] Such an extremal probability (8) assigns to a singleton element put in position \(\pi(i)\) by the permutation \(\pi\) the mass of all the focal elements containing it, but not containing any elements preceding it in the permutation order [86]. Eq. (8) analytically derives the finite set of vertices which identify a random-set prediction. For class \(c\), the size of the credal set is approximated by calculating the minimum and maximum (Eq. 9) of the extremal probabilities, \[P^{\pi}_{min}=\min_{P^{\pi}[Bel](x_{\pi(i)})}P^{\pi}[Bel](x_{\pi(i)})_{y_{c}}, \hskip 14.226378ptP^{\pi}_{max}=\max_{P^{\pi}[Bel](x_{\pi(i)})}P^{\pi}[Bel](x_{ \pi(i)})_{y_{c}} \tag{9}\] where \(y_{c}\) is the index of class \(c\). These minimum and maximum extremal probabilities are the upper and lower bounds of the estimated probability for class \(c\). The predicted pignistic probability estimate \(BetP\) falls within the interval of these upper and lower bounds which indicates the epistemic uncertainty associated with the prediction. Credal set width, measured as the difference between \(P^{\pi}_{max}\) and \(P^{\pi}_{min}\), is the epistemic uncertainty estimate associated with a prediction. ## 5 Experiments **Performance.** We evaluate the performance of random-set convolutional neural networks (RS-CNN) with experiments on multi-class image classification datasets MNIST [50], CIFAR10 [48], Intel Image [5] and CIFAR-100 [47], compare against state-of-the-art Bayesian and Evidential classifiers for uncertainty estimation (see Table 1). **CNN** is a standard deterministic neural network, the only model that does not include uncertainty estimation, **MCDropout**[35], **R-BNN**[46], **F-BNN**[88], **LB-BNN**[41] are Bayesian models with Monte-Carlo dropout approximation, Variational inference with Local Reparameterization Trick [45], Flipout estimation[88] and Laplace Bayesian posterior approximation respectively. **ENN**[64] is an epistemic NN classifier based on a generalisation of Bayesian method, and **EDL** is the Evidential deep classifier [70] for uncertainty estimation based on evidence theory. **M-RS-CNN** and **B-RS-CNN** are our mass and belief random-set convolutional neural networks. For fair comparison, we have used the same model architecture as RS-CNN to test all these methods. Their test accuracies are reported in Table 1. While we included Bayesian and Evidential learning models, it is important to note that comparing our models directly with methods like ensembles and Bayesian models that use priors may not be entirely appropriate. **Model architecture.** The RS-CNN architecture consists of three convolutional layers: the first layer has 32 filters of size 3x3, and the second and third layers have 64 filters of size 3x3. ReLU activation is used in all three layers. Max pooling with a pool size of (2, 2) follows the first and third convolutional layers. A dropout layer with a rate of 25% is added before the final two layers. The fully connected layer has 100 hidden units with ReLU activation, and the output layer has the same number of units as the number of focal sets, using the sigmoid activation function. In the first step, we train the RS-CNN model using the Adam optimizer with categorical cross-entropy loss over 15 epochs with learning rate \(0.001\) and batch size of 64. The feature vector \(f\) is extracted from the penultimate layer. We apply t-SNE for dimensionality reduction and map the class features to a 3D space. To expedite computation, we utilize all available CPU cores for parallel processing, which takes \(\approx\)7 minutes for CIFAR10 with 10 classes. The remaining computations are performed on a GPU (NVIDIA GeForce GTX 1080 Ti). Clusters or elliptical regions representing the 10 classes are calculated using mean, standard deviation, and eigenvectors obtained by fitting individual Gaussian Mixture Models (GMMs) to the embedded features of each class. For CIFAR10 with 10 classes (\(N=10\)), we have a total of 1024 sets of classes (\(2^{N}\)). Due to the exponential complexity of computing predictions for all 1024 sets, we select the top K most-relevant subsets, additional to \begin{table} \begin{tabular}{l l l l l} \hline \hline Datasets & MNIST & CIFAR10 & INTEL-IMAGE & CIFAR100 \\ \hline CNN & \(99.33\pm 0.05\) & \(75.29\pm 0.42\) & \(79.62\pm 0.41\) & \(\mathbf{42.88\pm 0.74}\) \\ MCDropout [35] & \(98.79\pm 0.15\) & \(62.95\pm 0.50\) & \(66.60\pm 1.13\) & \(38.42\pm 0.88\) \\ R-BNN [46, 45] & \(97.96\pm 0.07\) & \(53.28\pm 0.24\) & \(57.47\pm 0.83\) & \(27.10\pm 0.65\) \\ F-BNN [88] & \(98.27\pm 0.04\) & \(55.16\pm 0.52\) & \(60.77\pm 0.32\) & \(29.97\pm 0.98\) \\ LB-BNN [41] & \(99.25\pm 0.06\) & \(74.24\pm 0.60\) & \(79.66\pm 0.78\) & \(40.30\pm 0.44\) \\ EDL [70] & \(98.61\pm 0.77\) & \(75.87\pm 0.41\) & \(79.97\pm 0.09\) & \(37.33\pm 0.40\) \\ ENN [64] & \(99.14\pm 0.11\) & \(72.60\pm 0.50\) & \(77.93\pm 0.95\) & \(40.72\pm 0.30\) \\ **M-RS-CNN** & \(99.39\pm 0.07\) & \(75.98\pm 0.20\) & \(79.55\pm 0.37\) & \(41.50\pm 0.40\) \\ **B-RS-CNN** & \(\mathbf{99.39\pm 0.08}\) & \(\mathbf{77.63\pm 0.42}\) & \(\mathbf{81.59\pm 0.47}\) & \(39.80\pm 0.06\) \\ \hline \hline \end{tabular} \end{table} Table 1: Comparison of test accuracies (%) of uncertainty estimation classifiers with RS-CNN over 5 consecutive runs. The average and standard deviation are shown for each experiment. singletons. The overlapping ratio is estimated between all classes, and we choose K subsets with the highest overlapping ratios (Sec. 3.2). In our experiment, we set K to 20, excluding the empty set and N singletons. For example, in CIFAR10, the selected non-singleton focal sets include combinations such as {'cat', 'dog'}, {'horse', 'deer'}, {'bird', 'airplane'}, and {'cat', 'horse', 'dog'}. These 20 focal sets, along with the 10 singletons, form our new set of classes \(A\in\mathbb{P}(N)\). The belief function \(Bel(A)\) is considered "true" if the true class is present in the set. For instance, for the class 'bird', the belief functions for subsets {'bird'} and {'bird', 'airplane'} are set to 1. The model is trained using the BCE-M loss function (Eq. 5) over 50 epochs and a batch size of 64. Our experiments use \(\alpha=1\) and \(\beta=1\). The predicted belief function \(\hat{Bel}(A)\) gives the belief values for a list of classes including singletons and non-singleton focal subsets. We compute mass values from the predicted \(\hat{Bel}(A)\) using Eq. 3. The sum of predicted masses should be around 1 depending on the rate with which the model has learnt the belief values. We compute the pignistic probabilities (Sec. 4) for each original class \(N=10\) using Eq. 6. Table 2 shows the predicted belief functions, masses, and pignistic predictions for the samples. The test accuracy is calculated by comparing the pignistic prediction with the true labels. The test accuracy for Belief RS-CNN for MNIST, CIFAR10, CIFAR100 and Intel Image Classification datasets are \(99.39\%\), \(77.63\%\), \(39.80\%\) and \(81.59\%\). **Uncertainty estimation.** We calculate the predicted belief, mass and pignistic probability for both in-distribution and out-of-distribution(OOD) samples of the test data, noisy (random noise added to test set) and rotated (random degrees of rotation between -30 and 180). RS-CNN has significantly higher test accuracy than a standard CNN for noisy out-of-distribution MNIST data. Table 4 shows the test accuracies for standard CNN and RS-CNN at different scales of random noise. Table 3 shows an example of an OOD rotated MNIST image with a true label "8". The standard CNN makes a wrong prediction ("6") with \(99.95\%\) confidence and a low entropy of 0.0061. The CNN fails to perform well on OOD samples, whereas the RS-CNN predicts the belief functions for top 5 subsets {'6', '4', '8'}, {'6', '8', '1'}, {'6', '8'}, {'9', '8'}, and {'8', '3'}. It is clear from the belief prediction alone that the true element is contained in most, if not all of the subsets. We compute the mass values using Eq. 3, and the pignistic probabilities using Eq. 6. The highest pignistic probability estimate gives us a correct prediction of class "8" with a pignistic probability of 49.7% and an entropy of 2.1626. This \begin{table} \begin{tabular}{l l l l l l l} \hline \hline \multicolumn{2}{c}{**True Label = \(\text{\text demonstrates how RS-CNNs predict even the true class with a lower confidence in uncertain cases, in contrast to the standard CNN that provide incorrect classifications with high confidence. A distribution of confidence scores for belief random-set CNN are shown in Fig. 1(a) for both incorrectly classified and correctly classified samples. In Fig. 1(b), we show how a standard CNN has high confidence for incorrectly classified samples whereas RS-CNN exhibits lower confidence and higher entropy (Fig. 1(c)) for incorrectly classified samples. Fig. 1(c) displays the entropy distribution for correctly and incorrectly classified samples of CIFAR10, including in-distribution, noisy, and rotated images. Higher entropy is observed for incorrectly classified predictions across all three cases. Fig. 3(a) shows entropy-based uncertainty estimation for rotated OOD samples of the MNIST digit '\(3\)'. The RS-CNN model accurately predicts the true class at \(-30\), \(0\), and \(30\) degrees, indicating low uncertainty. As the rotation angle increases, all models predict the wrong class, with the RS-CNN showing higher entropy than LB-BNN. ENN, an ensemble method, also exhibits higher entropy. Overall, RS-CNN provides a better measure of uncertainty. To estimate the epistemic uncertainty of a prediction, we approximate the extremal probabilities that define the vertices of the associated credal set. Instead of calculating the exact vertices, which is computationally expensive due to a large number of permutations, we calculate the upper and lower bounds of the credal set using Eq. 9. This approximation allows us to visualize the uncertainty by plotting the upper and lower bounds in Fig. 3 for a subset of CIFAR10 samples. The pignistic probability estimate, \(BetP\), falls within this credal set, and the distance between the upper (\(P_{max}^{\pi}\)) and lower (\(P_{min}^{\pi}\)) bounds represents the epistemic uncertainty. Fig. 3(b) displays the estimated credal width for both correctly and incorrectly classified samples. The length of the lines reflect the epistemic uncertainty. Incorrect classifications exhibit high credal set widths, indicating higher associated uncertainty. **Choice of model architecture** We verify our approach on larger model architectures, specifically, Resnet-50 (see Table 5) and observe a higher test accuracy of 83.13% on CIFAR10, while predicting uncertainty, compared to a test accuracy of 84.21% for a standard Resnet-50. Both models were trained for 200 epochs with a varying learning rate. With better model architectures, we can achieve higher test accuracies than reported in Table 1. \begin{table} \begin{tabular}{l l l l l l l l} \hline \hline Noise (scale) & 0.2 & 0.3 & 0.4 & 0.5 & 0.6 & 0.7 & 0.8 \\ \hline Standard CNN & 93.40\% & 79.08\% & 79.15\% & 58.33\% & 40.19\% & 28.15\% & 28.59\% \\ RS-CNN & 96.90\% & 85.36\% & 85.91\% & 68.33\% & 51.46\% & 37.18\% & 38.05\% \\ \hline \hline \end{tabular} \end{table} Table 4: Test accuracies(%) for RS-CNN and standard CNN on Noisy MNIST out-of-distribution (OOD) samples. ’Scale’ represents the standard deviation of the normal distribution from which random numbers are being generated for random noise. Figure 2: (a) Confidence scores for RS-CNN on CIFAR10, Noisy CIFAR10, and Rotated CIFAR10 (b) Confidence scores of _Incorrectly Classified samples_ for RS-CNN and CNN. (c) Entropy distribution for RS-CNN on CIFAR10, Noisy CIFAR10, and Rotated CIFAR10. ## 6 Limitations A limitation of our approach is the selection of different subsets during each budgetting run. These subsets may vary across different runs, but there is some consistency with non-singleton focal sets where subsets such as {'bird', 'airplane'}, {'cat', 'dog'}, {'automobile', 'truck'}, repeat over multiple runs. Fine-tuning can be employed to mitigate the need for separate feature extraction and training stages. Our approach has potential applications in the safety-critical domain that require uncertainty estimation such as medical diagnostics, autonomous driving, and other tasks involving image classification and analysis since it is particularly effective for predicting out-of-distribution samples and would perform better with imprecise data than precise. ## 7 Conclusion This paper proposes a random-set convolutional neural network for uncertainty estimation in classification using belief functions. We compute masses and pignistic probabilities from predicted belief functions and estimate uncertainty using credal set width and entropy. Our method achieves superior test accuracy compared to state-of-the-art uncertainty estimation networks and performs comparably to traditional networks without uncertainty estimation. We provide an example illustrating how our model predicts uncertainty in rotated digits. In this paper we only discussed the target-level representation of random-set CNNs (RS-CNNs). Future work involves parameter-level representation of random-set neural networks and the extension of this concept from classification to detection tasks. Detection networks have additional heads which take care of regressing bounding box coordinates in addition to labels: the research problem then becomes one of formulating suitable localisation losses in keeping with the epistemic uncertainty principle. Moreover, applying both mass and belief random-set CNNs to imprecise data shows promise for improved performance. Figure 4: Uncertainty estimates for RS-CNN, (a) Uncertainty (entropy) of MNIST digit ’3’ rotated between -90 and 90 degrees. The blue line indicates RS-CNN estimates low uncertainty between -30 to 30, and high uncertainty for further rotations. (b) Credal set width of each prediction, the width for incorrectly classified samples (orange) is larger when compared to correct classifications (blue) indicating high uncertainty for incorrect classifications. Figure 3: Upper (\(P^{\pi}_{max}\)) and lower (\(P^{\pi}_{min}\)) bounds (dotted red) of the credal set consistent with belief functions predicted for 100 samples of CIFAR10. The pignistic probability estimate for each belief prediction is shown in solid red and the shaded region is the associated epistemic uncertainty. \begin{table} \begin{tabular}{l c c|c c c c} \hline \hline & \multicolumn{2}{c|}{Parameters (million)} & \multicolumn{4}{c}{Test Accuracy (\%)} \\ \hline Resnet50 & \(\approx 23.608\) & B-RS Resnet50 & \(\approx 23.649\) & Resnet50 & \(84.21\) & B-RS Resnet50 & \(83.13\) \\ \hline \hline \end{tabular} \end{table} Table 5: Performance of Resnet50-RS-CNN model architecture on CIFAR10
2305.02664
Study of nuclear corrections on the charged hadron fragmentation functions in a Neural Network global QCD analysis
In this work, we present a new global QCD analyses, referred to as PKHFF.23, for charged pion, kaon, and unidentified light hadrons. We utilize a Neural Network to fit the high-energy lepton-lepton and lepton-hadron scattering data, enabling us to determine parton-to-hadron fragmentation functions (FFs) at next-to-leading-order (NLO) accuracy. The analyses include all available single-inclusive $e^+e^-$ annihilation (SIA) and semi-inclusive deep-inelastic scattering (SIDIS) data from the COMPASS Collaboration for charged pions, kaons, and unidentified light hadrons. Taking into account the most recent nuclear parton distribution functions (nuclear PDFs) available in the literature, we evaluate the effect of nuclear corrections on the determination of light hadrons FFs. The Neural Network parametrization, enriched with the Monte Carlo methodology for uncertainty estimations, is employed for all sources of experimental uncertainties and the proton PDFs. Our results indicate that incorporating nuclear corrections has a marginal impact on the central values of FFs and their corresponding uncertainty bands. The inclusion of such corrections does not significantly affect the fit quality of the data as well. The study suggests that while nuclear corrections are a consideration, their impact in such QCD analysis is limited.
Maryam Soleymaninia, Hadi Hashamipour, Hamzeh Khanpour, Samira Shoeib, Alireza Mohamaditabar
2023-05-04T09:13:11Z
http://arxiv.org/abs/2305.02664v2
Nuclear corrections on the charged hadron fragmentation functions in a Neural Network global QCD analysis ###### Abstract In this work, we present the new global QCD analyses, referred to as PKHFF.23, for charged pion, kaon, and unidentified light hadrons by utilizing the Neural Network for fitting the high energy lepton-lepton and lepton-hadron scattering to determine parton-to-hadron fragmentation functions (FFs) at both next-to-leading-order (NLO) and next-to-next-to-leading-order (NNLO) accuracy. The analyses include all available single-inclusive \(e^{+}e^{-}\) annihilation (SIA) and semi-inclusive deep-inelastic scattering (SIDIS) data for charged pions, kaons, and unidentified light hadrons. Considering the most recent nuclear parton distribution functions (nuclear PDFs) available in the literature, we assess the impact of nuclear corrections on the determination of light hadrons FFs. We show that considering the nuclear corrections at both NLO and NNLO accuracy affect the central values of FFs and the associated uncertainty bands, and could improve the fit quality as well. The Neural Network parametrization enriched with the Monte Carlo methodology for uncertainty estimations is used for all sources of experimental uncertainties and the proton PDFs. ###### Contents * I Introduction * II Theoretical Setup * III Experimental Data Setup * IV Analysis setup and fitting procedure * V Numerical Results * V Nuclear effects of the kaon FFs * V Nuclear effects of the unidentified light charged hadron FFs * V Nuclear effects of the pion FFs * VI Summary and Conclusions ## I Introduction Fragmentation Functions (FFs) play an important role to study the non perturbative parton structure of hadrons at the Large Hadron Collider (LHC), and future high-precision hadron production measurements at Electron Ion Collider (EIC) [1; 2] and Future Circular Collider (FCC) [3; 4]. Hence, up-to-date methodological, experimental and theoretical developments need to be considered to calculate well-established FF sets as well. To this end, most recently, several global QCD analyses have been performed to determine the FFs of charged pion and kaon [5], and unidentified light hadrons [6] by including all available data from single inclusive electron-positron annihilation (SIA) and semi-inclusive deep-inelastic scattering (SIDIS) processes. The Neural Network (NN) as a modern optimization technique to minimize the bias of parametrization is considered. In order to obtain the probability density distribution in the fitting analysis, the Monte Carlo method has been employed. These analyses have been performed using the publicly available MontBlanc package [7]. The analysis for FFs of unidentified light charged hadrons has been extracted up to next-to-leading order (NLO), and the FFs of pion and kaon have been determined up to next-to-next-to-leading order (NNLO) accuracy. The perturbative corrections for SIA up to NNLO are available [8; 9], and recently the derivation of approximate NNLO corrections to SIDIS has been completed by expanding the resumed expressions [10]. The authors of Ref. [5] have extended the theoretical accuracy up to NNLO corrections as well. Consequently, the MontBlanc package takes advantages of these developments and could calculate the FFs for different hadrons up to NNLO by including SIA and SIDIS measurements. Although the recently reported FF sets [5; 6] take advantage of the model bias reduction in FF parametriza tion, in the propagation of the experimental data and in the proton PDFs uncertainties, the nuclear corrections have not been taken into account so far. The cross section in the SIDIS process is calculated considering only the proton PDFs set at NLO and NNLO accuracy and the analyses have been performed without considering the nuclear corrections on the PDFs in SIDIS. In this work, we mainly focus on the revisiting the analyses mentioned above for charged (\(\pi^{\pm}\)), kaon (\(K^{\pm}\)) and unidentified light hadrons (\(H^{\pm}\)) in order to consider the impact of various nuclear PDF sets in determination of FFs. To this end, we first perform the global QCD analyses for FFs of charged pion, kaon and unidentified light hadrons separately by considering the NNPDF3.1[11] proton PDF set as a baseline fit in the case of SIDIS for both NLO and NNLO accuracy. Then we repeat the analyses considering the most recent nuclear PDF sets to investigate the effects of applying the nuclear corrections. We produce three FF sets by utilizing nNNPDF3.0[12], EPPS21[13] and nCTEQ15WZ[14] nuclear PDF sets at NLO, and one FF set by utilizing nNNPDF1.0[15] nuclear PDF sets at NNLO accuracy. We study the impact of nuclear corrections in determination of FFs in the global NLO and NNLO QCD analyses, and the main results and findings are clearly presented and discussed. We show that the nuclear corrections could affect both the shape and uncertainty bands, and could improve the fit quality as well. The rest of the paper is organized as follows. In Sec. II we summarize the theoretical formalism for the SIA and SIDIS processes. The parametrization of FFs and the flavor decomposition for charged pion, kaon and unidentified light hadrons in terms of Neural Network will be detailed in this section. The SIA and SIDIS experimental data sets analyzed in this work and the kinematical cuts applied will be summarized in Sec. III. In Sec. IV we present the fitting methodology as well as the Monte Carlo method to calculate the uncertainties of FFs. Sec. V includes the detailed discussion of the numerical results in the presence of nuclear corrections. Finally, Sec. VI present the summary and conclusion. ## II Theoretical Setup According to the standard collinear factorization, the QCD cross sections can be separated into the perturbative partonic cross sections convoluted with the partonic and hadronic distribution functions as non-perturbative objects [16]. Therefore, the cross sections for SIA and SIDIS can be written as, \[\sigma^{\rm SIA} =\hat{\sigma}\otimes{\rm FF},\] \[\sigma^{\rm SIDIS} =\hat{\sigma}\otimes{\rm PDF}\otimes{\rm FF}\,. \tag{1}\] The \(\hat{\sigma}\) indicates partonic cross section as a process dependent and perturbative part of the cross sections. The universal and non-perturbative parts of the cross sections are indicated by PDFs and FFs. The details of the computation of the SIA and SIDIS cross sections can be found in the literature, and we refer the reader to Refs. [17; 6; 18] for a clear review. The NLO and NNLO corrections to the time-like DGLAP evolution equations and to the SIA coefficient functions carried out in the literature [19; 20]. The NNLO corrections to SIDIS coefficient functions are taken from Ref. [10] in which the authors have calculated the NNLO perturbative corrections by applying the threshold resummation formalism up to next-to-next-to-leading logarithmic (NNLL) order. Then the approximate NNLO corrections to unpolarized and polarized SIDIS are achievable. Accordingly, in the present paper, we investigate the impact of nuclear correction on the FFs of charged hadrons at NLO and NNLO accuracy. In the following we present the parameterization and flavor decomposition for charged pion, kaon and light hadrons at the initial scale \(\mu_{0}=5\) GeV. Since the SIA data along with SIDIS measurements are included in our analyses, the direct constrain on the FFs of light quarks and antiquarks could be provided. In the case of pions and kaons, we follow the flavor decomposition of Ref. [5] \[D_{g}^{\pi^{+}}, D_{g}^{K^{+}},\] \[D_{u}^{\pi^{+}}, D_{u}^{K^{+}},\] \[D_{d}^{\pi^{+}}, D_{s}^{K^{+}}\] \[D_{d}^{\pi^{+}}=D_{\bar{u}}^{\pi^{+}}, D_{s}^{K^{+}}=D_{\bar{u}}^{K^{+}},\] \[D_{s}^{\pi^{+}}=D_{\bar{s}}^{\pi^{+}}, D_{d}^{K^{+}}=D_{d}^{K^{+}}\] \[D_{c}^{\pi^{+}}=D_{\bar{c}}^{\pi^{+}}, D_{c}^{K^{+}}=D_{\bar{c}}^{K^{+}},\] \[D_{b}^{\pi^{+}}=D_{\bar{b}}^{\pi^{+}}, D_{b}^{K^{+}}=D_{\bar{b}}^{K^{+}}\,. \tag{2}\] In the case of unidentified light charged hadrons, we follow the flavor decomposition as our previous work [6], \[D_{g}^{H^{+}},\] \[D_{u}^{H^{+}},\] \[D_{\bar{u}}^{H^{+}}\] \[D_{d}^{H^{+}}=D_{s}^{H^{+}},\] \[D_{d}^{H^{+}}=D_{\bar{s}}^{H^{+}}\] \[D_{c}^{H^{+}}=D_{\bar{c}}^{H^{+}},\] \[D_{b}^{H^{+}}=D_{\bar{b}}^{H^{+}}\,. \tag{3}\] These FFs are obtained in the framework of Neural Networks. Corresponding to the momentum fraction \(z\), we use one input node in a one-layered feed-forward Neural Network, 20 intermediate nodes in a one hidden layer and a sigmoid activation function. Since the number of independent FFs of the positive pion, kaon and unidentified light hadrons are seven, we use 7 nodes in the output with a linear activation function. The architecture of the Neural Network is \(1-20-7\) and the number of Monte Carlo replicas is \(200\). Indeed, the uncertainty propagation has been estimated by using the Monte Carlo method. As we mentioned before, the main aim in this paper is to investigate the impact of applying the nuclear corrections to calculate the SIDIS observables. To this end, in the first step, we use the proton PDF sets NNPDF3.1[11] as input to calculate the SIDIS cross sections. In the second step, the nuclear PDF sets are taken into account for the nuclear corrections. The computation of FFs at NLO accuracy has been performed by means of various nuclear PDF sets, namely the nNNPDF3.0[12], EPPS21[13] and nCTEQ15WZ[14] at NLO accuracy. For the NNLO accuracy we use nNNPDF1.0 nuclear PDF sets [15]. We determine the charged pion, kaon and light hadron FFs in the Zero-Mass Variable-Flavor-Number Scheme (ZM-VFNS), in which the active flavors are considered to be massless. In our analysis, the masses of charm and bottom quarks are considered to be fixed at \(m_{c}=1.51\) GeV and \(m_{b}=4.92\) GeV, respectively. Finally, we should mention that we utilize the MontBlanc public package for our global QCD analyses in this project. ## III Experimental data setup The experimental data sets used in this work include both the SIA and SIDIS measurements for charged pion, kaon and unidentified light hadrons productions. In the case of SIA, the measured differential cross section is normalized to the total cross section and reported as sum of the production of positively and negatively charged hadrons. The data analyzed in this work include different experiments performed by TASSO[21; 22; 23; 24] experiment at DESY, TPC[25], BABAR[26] and SLD[27] experiment at SLAC, BELLE[28] and TOPAZ[29] at KEK, and ALEPH[30; 31], DELPHI[32] and OPAL[33; 34] experiments at CERN. In the case of SIDIS observables, the experimental data correspond to the SIDIS cross section which is normalized to the inclusive DIS cross section. The SIDIS measurements have been reported both for the production of positive and negative charged hadrons. The COMPASS experiment at CERN[35; 36] and HERMES experiment at DESY[37] are two main experiments which have reported the experimental data for SIDIS processes for pion, kaon and unidentified light hadrons productions. Considering the impact of nuclear PDF sets in SIDIS case, one should consider the nuclear PDF sets relevanted to the nuclear target. COMPASS experiment has used a muon beam and a \({}^{6}\)LiD target. The data are collected by the HERMES experiment at the HERA storage ring using electron and positron beams on a hydrogen or deuterium gas target. Since MontBlanc unable to use different PDF sets at the same time to calculate the SIDIS observables, we limit our study to the COMPASS data sets which reported 314 points for pion, kaon and unidentified light hadrons. The published HERMES data only include the 4 points and neglected in our study. The SIA and SIDIS experimental data for light charged hadron production used in our analysis follow those of our previous work [6]. We include all the charged pion and kaon data of SIA and SIDIS experiments, which are applied in recent analyses of MAPFF1.0[5]. As we mentioned earlier the HERMES data is excluded from our analysis. More detailed study on the data selection can be found in Refs. [5; 6]. The proton PDF set of NNPDF3.0 has been used for determination of SIDIS observables as our baseline fit. Hence, in order to study the nuclear corrections one need to include the nuclear PDFs for \({}^{6}\)LiD. All measured observables analyzed in this study along with their published references and the number of data points are presented in Tables. 1 and 2 for kaon, and in Tables. 3 and 4 for the unidentified light charge hadrons, and in Tables. 5 and 6 for pion. The values of individual and total \(\chi^{2}\) are presented for different PDF sets. In the case of SIA experimental data sets, the experimental data have reported as total inclusive, light-, charm-, and bottom-tagged cross sections measurements. One needs to impose kinematical cuts on small and large values of \(z\) in which the perturbative fixed-order predictions should be reliable. We follow Refs. [5; 6] to apply the kinematic cuts on the SIA and SIDIS data sets. For the SIA data points, we apply the kinematic cuts on \(z\) based on the value of a center-of-mass (CM) energy: for data points with the scale of energy less than \(M_{Z}\) we use \(0.075\leq z\leq 0.9\), and for the data points with the scale of energy equal to \(M_{Z}\) we consider \(0.02\leq z\leq 0.9\). For SIDIS, we consider the kinematical cut on the small \(Q\) and retain the experimental data points in region \(Q\geq 2\) GeV. The same kinematical cuts are applied for charged pion, kaon and unidentified light hadrons analyses. In addition, since the small-\(z\) corrections at energy scale of \(B\) factories for kaon production occur at higher value of \(z\) in comparison with pion, we adopt \(0.2\leq z\leq 0.9\) for the BABAR experiments for kaon production. ## IV Analysis setup and fitting procedure After briefly presenting the flavor decomposition of FFs and related to observables of interest, we are in a position to discuss the analysis setup and fitting procedure. We will state other theoretical choices and consider their effect on the extraction of FFs. The architecture of Neural Network used for parametrization is (1-20-7) which is quite simple but it proves to be sufficient [6] for the FFs analysis, it has 187 free parameters (weights and biases) need to be fixed from the data. To force the distributions to vanish at \(z=1\) and to be positive, value of NN at \(z=1\) (i.e. \(\mathcal{N}(1;\mathbf{\theta})\)) is subtracted from the output of the Neural Network and then the outcome is squared, so the parametrization can be written as, \[zD(z,\mu_{0})=\left(\mathcal{N}(z;\mathbf{\theta})-\mathcal{N}(1;\mathbf{\theta})\right)^{ 2}. \tag{4}\] In the equation above, the \(\mathcal{N}\) represents a Neural Network with set of parameters \(\mathbf{\theta}\), and the parametrization is assumed to be at \(\mu_{0}=5\) GeV, above bottom quark mass threshold 1. This parametrization is used for both NLO and NNLO calculation with strong coupling constant \(\alpha_{S}=0.118\) at Z boson mass scale (91.1876 GeV) together with appropriate evolution. Footnote 1: Mass thresholds considered to be, 1.51 GeV for charm and 4.92 GeV for bottom quark. As mentioned, the analysis made in this paper utilizes MontBlanc package, a C++ package dedicated to determination of collinear FFs [7]. In order to perform perturbative QCD analysis MontBlanc package uses the following packages; GSL or GNU scientific library for numerical utilities [38], yaml-cpp[39] for reading data and writing the results, LHAPDF library for reading input PDFs [40], Ceres Solver[41] for minimizing the \(\chi^{2}\) function, NNAD[42] for defining Neural Network and their derivatives, APFEL++[43] for evolution of FFs and NangaParbat[44] for calculation of observables. The \(\chi^{2}\) function minimized during analysis is defined as, \[\chi^{2}_{(k)}\equiv\left(\mathbf{T}\left(\mathbf{\theta}_{(k)}\right) -\mathbf{x}_{(k)}\right)^{T}\cdot\mathbf{C^{-1}}\cdot\left(\mathbf{T}\left(\mathbf{ \theta}_{(k)}\right)-\mathbf{x}_{(k)}\right)\,, \tag{5}\] where \(\mathbf{C^{-1}}\) is inverse of covariance matrix which includes all statistical and systematic uncertainties. The symbol \(\mathbf{x}_{(k)}\) in represents \(k\)-th replica or pseudo-data set, analogously \(\mathbf{\theta}_{(k)}\) is parameters of \(k\)-th Neural Network replica. Here \(\mathbf{T}\) represents the theoretical prediction calculated using mentioned Neural Network parameters. The symbol \(T\) indicates to the matrix transposing as usual. So far we have introduced the different parts of Eq. 5, now we are in a position to explain what we mean by replica. The method of Monte Carlo is used in this analysis to propagate experimental uncertainty to the resulting FFs. In this method a suitable ensemble of copies of data is chosen, after performing \(N_{\text{rep}}\). fits over individual (pseudo-)data sets in the ensemble, produced FFs are such that their simple statistical parameters as average and standard deviation constitute their central value and uncertainty, for more details see e.g. [6] and references therein. To consider the SIDIS data, (nuclear)PDFs are needed to calculate the cross section. In MontBlanc approach a random replica of input PDF is chosen in every fit to incorporate PDF uncertainty in the determination of FFs. In spite of the fact that this source of uncertainty is shown to be a minor one [17], we opt for including it for the sake of completeness. Most of the available nuclear PDFs presented the uncertainty using the Hessian method, and one need to convert the Hessian error sets into Monte Carlo using MCGEN code [45; 46] and then implement them in the analysis. The MCGEN creates Monte Carlo replicas using random displacement of Hessian sets and ensures that important properties of Hessian PDFs are preserved. ## V Numerical results In this section, we present the main results of this work and make a comparison between the calculated FFs with and without nuclear corrections. We first present the effect arising from nuclear corrections on our QCD analysis of kaon FFs. We discuss in details the effect on both the central values and on the error bands. Then we discuss the effect on the extracted unidentified charged hadron FFs and pion FFs as well. The impact arising from the nuclear corrections and higher-order QCD corrections on the individual and total \(\chi^{2}\) for different hadrons will be detailed. ### Nuclear effects of the kaon FFs In this section we mainly consider our results for the kaon FFs, in the presence of nuclear effects. As we discussed earlier, we consider the NNPDF3.1 proton PDFs as our baseline fit. In order to investigate the impact arising from the inclusion of the nuclear effects at NLO accuracy, we consider three different sets of nuclear PDFs available in the literature, namely the nNNPDF3.0[12], EPPS21[13], and nCTEQ15WZ[14]. In order to examine the effect of nuclear corrections at a higher-order QCD correction, we use the nNNPDF1.0[15] in which provided the nuclear PDFs up to NNLO accuracy in perturbative QCD. The global QCD analyses reported by the nNNPDF3.0, EPPS21, and nCTEQ15WZ are limited to the NLO accuracy. In the following, we present a short summary of these nuclear PDFs. The nNNPDF3.0[12] analysis presented an updated determination of nuclear PDF from a global datasets: the neutral-current (NC) nuclear fixed-target DIS measurements, the charged-current (CC) neutrino-nucleus DIS data, pPb collision at LHC for the boson production, data for CMS dijet[47], LHCb D0-meson production [48], isolated photon production [49] and fixed-target Drell-Yan (DY) measurements. The EPPS21 collaboration [13] has presented an updated nuclear PDF sets in EPPS16 by new experimental data, the LHC pPb data for dijets (Run-I), D-mesons (Run-I) and \(W^{\pm}\) bosons (Run-II). In addition, they have included Jefferson Lab measurements of DIS which probe nuclear PDFs. In EPPS21 the inclusive pion production at RHIC has been included and hence they have used a FF sets of pion in their analysis. Recently, the nCTEQ Collaboration has extended the nCTEQ15WZ and included the \(W\) and \(Z\) data from pPb collisions at the LHC [14]. In addition to the nuclear DIS, DY lepton pair production, and RHIC pion data had been employed in the earlier nCTEQ15 analysis. They referred to it as nCTEQ15WZ and the accuracy is up to NLO. We use the nNNPDF1.0 for calculation the FFs at NNLO [15]. The nNNPDF1.0 is the first determination of nuclear PDF based on the NNPDF methodology. The analysis is based on neutral-current structure functions on nuclear targets and is performed up to NNLO accuracy along with heavy quark mass effects. In Table. 1 we show the individual value of \(\chi^{2}/N_{\rm dat}\) resulting from the FF fit at NLO accuracy considering NNPDF3.1 proton PDFs, and the nuclear PDF sets from nNNPDF3.0, EPPS21 and nCTEQ15WZ as well. The total value of \(\chi^{2}/\)d.o.f. is shown at the bottom of this table. The value of \(\chi^{2}/N_{\rm dat}\) resulting from the FF fit at NNLO order by considering PDF sets of NNPDF3.1, and nuclear PDFs set from nNNPDF1.0 also shown in Table. 2. The total value for \(\chi^{2}/\)d.o.f. is shown as well. Considering the numbers presented in these tables for our kaon FFs, several comments are in order. As one can see, the most interesting finding in our kaon FFs fit is the reduction of the total \(\chi^{2}/\)d.o.f. after considering the nuclear PDFs. While the \(\chi^{2}/\)d.o.f. for the NNPDF3.1 proton PDFs is 0.792, the inclusion of the nNNPDF3.0, EPPS21 and nCTEQ15WZ reduces the \(\chi^{2}/\)d.o.f. to the 0.785, 0.749 and 0.704, respectively. The reduction of the individual \(\chi^{2}\) per data points are highlighted mostly for the case of COMPASS\(K^{+}\) and COMPASS\(K^{-}\) data sets. Another interesting finding is related to the inclusion of the higher-order QCD correction up to NNLO accuracy. As can be seen from Table. 2, considering the NNLO accuracy in the case of proton PDF sets NNPDF3.1 could reduce the total \(\chi^{2}/\)d.o.f. as expected. However, Table. 2 shows that the considering the nNNPDF1.0 NNLO nuclear PDFs could not improve the data/theory agreements. While the total \(\chi^{2}/\)d.o.f. calculated using the NNPDF3.1 proton PDF is around 0.627, considering the nuclear correction increase it to the 0.731. More importantly, the individual \(\chi^{2}\) per data points for the COMPASS\(K^{+}\) and COMPASS\(K^{-}\) data sets are increased to the 0.747 and 0.855 after the nuclear corrections are taken into account. Now we are in a position to discuss the extracted kaon FFs, both in terms of central values and uncertainty bands, in the presence of nuclear effects and high-order QCD corrections. In Figs. 1 and 2, we present the kaon FFs for different parton species at NLO and NNLO accuracy. As we discussed earlier, the NNPDF3.1 proton PDFs is considered as our baseline, and the nuclear PDF sets from nNNPDF3.0, EPPS21 and nCTEQ15WZ are taken into account to examine the nuclear effects. We present both the absolute values, and the ratio to the NNPDF3.1 proton PDFs baseline as well. As one can see, including the nuclear PDFs changes both the shape of central values and uncertainties bands of extracted kaon FFs. Such changes are more pronounced for the case of gluon, \(d\) and \(s\) FFs, at NLO accuracy. For the case of gluon and \(d\) FFs at NLO, the inclusion of nuclear effect not only affects the shape of central value, but also reduce uncertainty bands in respect to the NNPDF3.1 proton PDFs for most of regions of \(z\). For the case of \(\bar{s}\), \(c^{+}\) and \(b^{+}\) the results are almost similar, however, reduction in the uncertainties can be seen for medium value of \(z\) for the \(\bar{s}\), small value of \(z\) for the \(c^{+}\) and large value of \(z\) for the \(b^{+}\) after the inclusion of the nuclear PDFs. For the case of \(s\) and \(u\), slight changes on both shape and uncertainties bands can be seen, and the inclusion of EPPS21 and nCTEQ15WZ decreases the bands slightly, however, the nNNPDF3.0 nuclear PDFs increase the error bands in most regions of \(z\). For almost all parton species, the smallest error bands are achieved using the nCTEQ15WZ nuclear PDFs in different region of \(z\), which is more highlighted for the gluon, \(d\), \(c^{+}\), \(s\) and \(u\) FFs. The same findings as we discussed for the case of NLO, also hold for the NNLO results presented in Fig. 2. As can be seen, in terms of central values, the nuclear effects mostly affected the gluon, \(d\) and \(s\) FFs. The most noticeable changes for \(u\) and \(\bar{s}\) can be seen from medium to large \(z\) region. The behavior of central value of \(c^{+}\) are almost the same with proton PDFs and nuclear PDFs in the whole region of \(z\). The nuclear corrections also make change on \(b^{+}\) FF at medium and large region of \(z\). However, in terms of uncertainty bands, one can see that, the bands are reduced, and more importantly significant reduction for most of regions of \(z\) for gluon, \(d\), \(s\) and \(u\) FFs and just for small values of \(z\) for \(\bar{s}\) and \(b^{+}\) FFs can be observed. However, there is not any impressive changes at error bands for \(c^{+}\) FFs after considering the nuclear corrections. ### Nuclear effects of the unidentified light charged hadron FFs Our results for the unidentified light charged hadron FFs, in the presence of nuclear effects, will be presented in this section. The individual and total \(\chi^{2}\) per data points for our charged hadron FFs analysis are presented in Table. 3 for NLO, and in Table. 4 for NNLO accuracy. As can be seen, in terms of total \(\chi^{2}\), the inclusion of the EPPS21 and nNNPDF3.0 nuclear PDFs reduce the values of \(\chi^{2}\) from 1.079 to 1.030 and 1.056, respectively. However, for the case of nCTEQ15WZ nuclear PDFs, almost the same \(\chi^{2}\) value is achieved in respect to NNPDF3.1 proton PDFs. This finding also consistent with the individual \(\chi^{2}\) per data points presented in Table. 3, and more importantly for the COMPASS\(H^{+}\) and COMPASS\(H^{-}\) data sets. For the case of NNLO analysis, as can be seen from Table. 4, the inclusion of nuclear effects worsen the \(\chi^{2}\) numbers, both for the individual and total \(\chi^{2}\) per data points. This is mostly due to the increasing the value for individual \(\chi^{2}\) for both COMPASS\(H^{+}\) and COMPASS data sets. Now we are in a position to discuss the extracted charged hadron FFs from our QCD analysis, determined from NNPDF3.1 proton PDFs and the available nuclear PDFs. The results are presented in Figs. 3 and 4, for the NLO and NNLO analysis. We present both the absolute values, and the ratio to the NNPDF3.1 proton PDFs baseline as well. For the case of unidentified charged hadron FFs, inclusion of nuclear effects mostly affected the central value of the gluon, \(d\) and \(\bar{d}\) FFs. Other FFs such as \(u\) and \(\bar{u}\) are slightly affected, especially over the medium to small value of \(z\), \(c^{+}\) and \(b^{+}\) remain unchanged. As one can see, for the gluon, \(d\) and \(\bar{d}\) FFs, reduction of the error bands can be seen for medium to small value of \(z\). The smaller error bands are correspond to the nCTEQ15WZ for the gluon FFs and the EPPS21 for the case of \(d\) and \(\bar{d}\). The reduction of error bands for \(u\) and \(\bar{u}\) is very small in the some regions of \(z\). In the case of \(c^{+}\) the uncertainty bands almost do not change by considering the nuclear PDFs, although for \(b^{+}\) FFs, one can see some differences for error bands at large value of \(z\). In Fig. 4, we present our results for the unidentified light charged hadron FFs at NNLO accuracy considering the NNPDF3.1 proton PDFs, and nNNPDF1.0 nuclear PDFs. Like for the case of NLO analysis, for the \(c^{+}\) FFs, both the central value and error bands remain unchanged after considering the nuclear corrections. While the corrections affect on the \(b^{+}\) FFs from medium to large \(z\) region. All other FFs affected by the nuclear corrections, and reduction in uncertainty bands can be seen for the \(d\), \(\bar{d}\), \(u\) and \(\bar{u}\) for whole region of \(z\). From Fig. 4, one can see that the gluon FFs behaves differently. Considering the nNNPDF1.0 nuclear PDFs the bands increase in respect to the NNPDF3.1 proton PDFs almost in all region of \(z\). Although we can see the increasing of the \(\chi^{2}\) value in Table. 4 after nuclear corrections, the uncertainty bands for most of the partons decrease due to the nuclear corrections. \begin{table} \begin{tabular}{l c c c c c} \hline \hline Experiment & \(N_{\rm dat}\) & \(\frac{\chi^{2}}{N_{\rm dat}}\) (NNPDF3.1) & \(\frac{\chi^{2}}{N_{\rm dat}}\) (nNNPDF3.0) & \(\frac{\chi^{2}}{N_{\rm dat}}\) (EPPS21) & \(\frac{\chi^{2}}{N_{\rm dat}}\) (nCTEQ15WZ) \\ \hline \hline COMPASS \(K^{+}\)[35] & 156 & 0.703 & 0.674 & 0.632 & 0.632 \\ COMPASS \(K^{-}\)[35] & 156 & 0.752 & 0.582 & 0.618 & 0.596 \\ BEILE [28] & 70 & 0.522 & 0.539 & 0.532 & 0.525 \\ BAAR [26] & 28 & 0.923 & 1.131 & 0.965 & 0.838 \\ TASSO12 [21] & 3 & 0.785 & 0.779 & 0.785 & 0.791 \\ TASSO14 [22] & 9 & 1.380 & 1.422 & 1.386 & 1.344 \\ TASSO22 [22] & 6 & 0.672 & 0.636 & 0.665 & 0.712 \\ TPC [25] & 13 & 0.621 & 0.730 & 0.686 & 0.639 \\ TASSO34 [23] & 5 & 0.038 & 0.035 & 0.037 & 0.041 \\ TOPAZ [29] & 3 & 0.127 & 0.147 & 0.146 & 0.143 \\ ALEPH [30] & 18 & 0.450 & 0.470 & 0.475 & 0.474 \\ DELPHI (incl.) [32] & 23 & 0.605 & 0.639 & 0.652 & 0.650 \\ DELPHI (\(uds\) tag) [32] & 23 & 0.280 & 0.260 & 0.276 & 0.293 \\ DELPHI (\(b\) tag) [32] & 23 & 0.696 & 0.918 & 0.770 & 0.610 \\ OPAL (incl.) [33] & 10 & 0.478 & 0.496 & 0.487 & 0.474 \\ SLD (incl.) [27] & 35 & 1.532 & 1.908 & 1.683 & 1.360 \\ SLD (\(uds\) tag) [27] & 35 & 1.751 & 1.877 & 1.784 & 1.674 \\ SLD (\(b\) tag) [27] & 35 & 2.339 & 2.768 & 2.429 & 2.043 \\ \hline \hline Total \(\chi^{2}\)/d.o.f. & 651 & 0.792 & 0.785 & 0.749 & 0.704 \\ \hline \hline \end{tabular} \end{table} Table 1: The list of input data sets for the kaon production included in our kaon FFs analysis. For each data set, we have indicated the experiments, corresponding published reference and the number of data points. In the last four columns, we show the value of \(\chi^{2}/N_{\rm dat}\) resulting from the FF fit at NLO order by considering the proton PDF sets from NNPDF3.1 and nuclear PDF sets available in the literature, namely the nNNPDF3.0 [12], EPPS21 [13], and nCTEQ15WZ [14]. The total value of \(\chi^{2}\)/d.o.f. also is shown at the bottom of this table. ### Nuclear effects of the pion FFs In this section, we present the results for the pion FFs in the presence of nuclear corrections. The total and individual values for the \(\chi^{2}\) per data points are presented in Tables. 5 and 6 for the NLO and NNLO analysis, respectively. For the case of our pion FFs analysis, the results and findings are different from those of kaon and unidentified charged hadron FFs analysis. As can be seen from Table. 5, considering the nuclear PDFs from nNNPDF3.0, EPPS21 and nCTEQ15WZ do not improve the individual values for the \(\chi^{2}\) per data points. The total \(\chi^{2}\) value increases from 0.758 to 0.809, 1.456 and 0.761 for the different nuclear PDF sets. Even the \(\chi^{2}\) for the nCTEQ15WZ is very close to our baseline fit, but for the case of EPPS21 the fit leads to a large value. This is mostly due to the large \(\chi^{2}\) value for the COMPASS \(\pi^{+}\) data sets. This finding also holds for the case of our NNLO analysis, in which considering the nNNPDF1.0 NNLO nuclear PDFs does not improve the fit. Again the \(\chi^{2}\) for the COMPASS \(\pi^{+}\) is larger than those of our baseline fit. Another interesting find is related to the \(\chi^{2}\) values for the NLO and NNLO analysis. As one can see from Tables. 5 and 6, considering the higher-order QCD correction do not improve the fit quality for the pion FFs analysis. This finding also consistent with the study performed in Ref. [5] the inclusion of the NNLO corrections does not improve the fit quality. In Fig. 5, we present the QCD fits in the presence of both the NNPDF3.1 proton PDFs as our baseline and three different sets of nuclear PDFs sets, at the NLO accuracy in perturbative QCD. In Fig. 6, the same comparisons are presented, but this time for the NNLO accuracy, and limited to the NNPDF3.1 proton PDFs and the nNNPDF1.0 nuclear PDFs. We present both the absolute values, and the ratio to the NNPDF3.1 proton PDFs baseline as well. Considering the results presented in Figs. 5 and 6, several comments are in order. As one can see, including the nuclear PDFs, not only significantly change the shape of the central value of pion FFs, but also affect the error bands. In term of individual flavor component of pion FFs at NLO accuracy, one can conclude the following: The biggest changes in the central values can be found for the case of gluon and \(\bar{d}\) FFs in the region \(0.1\leq z\leq 1\). One can see slight changes for \(s\), \(u\) and \(d\) FFs in the whole region of \(z\) considering the nuclear corrections. In the case of \(c^{+}\) and \(b^{+}\) FFs the nuclear corrections affect only \begin{table} \begin{tabular}{l c c c} \hline \hline Experiment & \(N_{dat}\) & \(\frac{\chi^{2}}{N_{\rm dat}^{2}}\) (NNPDF3.1) & \(\frac{\chi^{2}}{N_{\rm dat}^{2}}\) (nNNPDF1.0) \\ \hline \hline COMPASS \(K^{+}\)[35] & 156 & 0.616 & 0.747 \\ COMPASS \(K^{-}\)[35] & 156 & 0.620 & 0.855 \\ BEILE[28] & 70 & 0.478 & 0.489 \\ BABAR [26] & 28 & 0.373 & 0.426 \\ TASS012 [21] & 3 & 0.821 & 0.818 \\ TASS014 [22] & 9 & 1.261 & 1.257 \\ TASS022 [22] & 6 & 0.800 & 0.788 \\ TPC [25] & 13 & 0.519 & 0.485 \\ TASS034 [23] & 5 & 0.047 & 0.046 \\ TOPAZ [29] & 3 & 0.140 & 0.128 \\ ALEPH [30] & 18 & 0.454 & 0.500 \\ DELPHI (incl.) [32] & 23 & 0.774 & 0.745 \\ DELPHI (\(uds\) tag) [32] & 23 & 0.332 & 0.323 \\ DELPHI (\(b\) tag) [32] & 23 & 0.383 & 0.316 \\ OPAL (incl.) [33] & 10 & 0.386 & 0.437 \\ SLD (incl.) [27] & 35 & 0.705 & 0.709 \\ SLD (\(uds\) tag) [27] & 35 & 1.602 & 1.488 \\ SLD (\(b\) tag) [27] & 35 & 1.307 & 1.247 \\ \hline \hline Total \(\chi^{2}/\)d.o.f. & 651 & 0.627 & 0.731 \\ \hline \hline \end{tabular} \end{table} Table 2: Same as Table. 1 but this time for our kaon FFs at NNLO accuracy. The NNPDF3.1 proton PDFs are considered as our baseline fit, and the NNLO nuclear PDF set from nNNPDF1.0 also considered to study the nuclear corrections. the large \(z\) region. For all partons of pion FFs one can not find any improvement for error bands by applying these three nuclear PDF sets. The error uncertainties of inclusion of nCTEQ15WZ are smaller than nNNPDF3.0 and EPPS21 except in the small region of \(z\). These results are consistent with the total \(\chi^{2}\) numbers reported in Table. 5. For the case of our NNLO pion results presented in Fig.6, the biggest changes can be seen for the gluon, \(\vec{d}\), and \(u\) FFs. One can see minor changes in the central value of \(d\), \(s\), \(c^{+}\) and \(b^{+}\) by applying the nuclear PDF nNNPDF1.0. The improvements on the error bands upon inclusion of the nuclear effects can be found for the gluon, \(d\), \(\vec{d}\), and \(s\) FFs for the large value of \(z\). For the case of \(u\) FFs, an improvement in the bands can be seen only for the small region of FFs. Overall speaking, nuclear corrections by utilizing the nNNPDF1.0 at NNLO accuracy could not reduce the uncertainties which and the number of total \(\chi^{2}\) after considering nuclear PDFs in Table. 6. ## VI Summary and Conclusions In this work, we have presented the new global QCD analyses of FFs for pion, kaon and unidentified light charged hadrons, entitled as PKHFF.23, at NLO and NNLO accuracy in perturbative QCD. The experimental data from SIA and SIDIS processes are analyzed, and very recent studies presented in Refs. [5; 6] are revisited to examine the nuclear corrections on the SIDIS observables and on the newly extracted FFs. In this work, we have used Neural Network parametrization enriched with the Monte Carlo methodology for the uncertainty studies. This framework reduces the model bias as much as possible and the uncertainties of the experimental data and proton PDF sets properly propagate into the extracted FFs. We have performed our QCD analyses which include NNPDF3.1 proton PDF set as baseline, and very recent determination of nuclear PDF sets available in literature namely the nNNPDF3.0, EPPS21, nCTEQ15WZ at NLO, and nNNPDF1.0 at NNLO to study the nuclear corrections. \begin{table} \begin{tabular}{l c c c c c} \hline \hline Experiment & \(N_{dat}\) & \(\frac{\chi^{2}}{N_{dat}}\) (NNPDF3.1) & \(\frac{\chi^{2}}{N_{dat}}\) (nNPDF3.0) & \(\frac{\chi^{2}}{N_{dat}}\) (EPPS21) & \(\frac{\chi^{2}}{N_{dat}}\) (nCTEQ15WZ) \\ \hline \hline COMPASS \(H^{+}\)[36] & 157 & 1.338 & 1.316 & 1.225 & 1.379 \\ COMPASS \(H^{-}\)[36] & 157 & 0.907 & 0.801 & 0.941 & 0.907 \\ TAS5014 [22] & 14 & 1.791 & 1.820 & 1.805 & 1.734 \\ TAS5022 [22] & 14 & 1.254 & 1.211 & 1.238 & 1.187 \\ TPC [25] & 21 & 0.659 & 0.605 & 0.613 & 0.508 \\ TAS5044 [23] & 14 & 2.912 & 2.591 & 2.778 & 2.629 \\ ALEPH [31] & 32 & 0.825 & 0.822 & 0.830 & 0.817 \\ DELPHI (incl.) [32] & 21 & 0.610 & 0.602 & 0.594 & 0.592 \\ DELPHI (\(uds\) tag) [32] & 21 & 0.380 & 0.373 & 0.378 & 0.377 \\ DELPHI (\(b\) tag) [32] & 21 & 1.028 & 1.009 & 1.008 & 0.998 \\ OPAL (incl.) [34] & 19 & 1.821 & 1.824 & 1.774 & 1.785 \\ OPAL (\(uds\) tag) [34] & 19 & 0.794 & 0.788 & 0.798 & 0.787 \\ OPAL (\(c\) tag) [34] & 19 & 0.599 & 0.591 & 0.611 & 0.604 \\ OPAL (\(b\) tag) [34] & 19 & 0.299 & 0.278 & 0.287 & 0.281 \\ SLD (incl.) [27] & 34 & 1.047 & 1.044 & 1.086 & 1.086 \\ SLD (\(uds\) tag) [27] & 34 & 0.946 & 0.952 & 0.929 & 0.939 \\ SLD (\(c\) tag) [27] & 34 & 1.034 & 0.991 & 1.168 & 1.109 \\ SLD (\(b\) tag) [27] & 34 & 1.102 & 1.060 & 1.085 & 1.098 \\ \hline \hline Total \(\chi^{2}\)/d.o.f. & 684 & 1.079 & 1.030 & 1.056 & 1.080 \\ \hline \hline \end{tabular} \end{table} Table 3: The list of input data sets for our unidentified light charged hadrons production included in our charged hadron FFs analysis. For each data set, we have indicated the experiments, corresponding published reference and the number of data points. In the last four columns, we show the value of \(\chi^{2}/N_{dat}\) resulting from the FF fit at NLO order by considering proton PDF sets from NNPDF3.1 and nuclear PDF sets available in the literature, namely nNNPDF3.0 [12], EPPS21 [13], and nCTEQ15WZ [14]. The total value of the total \(\chi^{2}\)/d.o.f. also is shown at the bottom of the table. We show that utilizing the nuclear PDFs instead of proton PDF at NLO could reduce the individual \(\chi^{2}\) per data points of COMPASS and the total \(\chi^{2}\)/d.o.f. value as well for charged kaon and unidentified light hadrons, and hence, could improve the fit quality. However, one can not see any improvement in the value of total \(\chi^{2}\)/d.o.f. for the case of pion. In addition we have found that inclusion of the nuclear corrections changes both the shape of central values and uncertainties bands of extracted charged kaon, pion and unidentified light hadron for gluon and different quark species at NLO and NNLO accuracy. In the case of kaon, for almost all parton species, the smaller error bands are achieved using the nCTEQ15WZ nuclear PDFs over different region of \(z\) at NLO accuracy. We have shown that the error bands for kaon are reduced at NNLO accuracy as well. In the case of unidentified light charged hadrons, by considering the nuclear corrections, for some of the partons, the error bands reduce, and for some others remained unchanged at both NLO and NNLO accuracy. In the case of pion, the inclusion of nuclear corrections, specially the nCTEQ15WZ, improves the error bands at NLO accuracy. The improvements on the error bands can be found for the large value of \(z\) at NNLO accuracy using the nNNPDF1.0 which is based only on the neutral-current nuclear DIS structure functions. However the reduction of the individual \(\chi^{2}\) of positive and negative COMPASS SIDIS data and the total \(\chi^{2}\)/d.o.f. can not be seen clearly. Overall speaking, in the case of NLO accuracy, the most promising results in terms of reduction of the values of individual \(\chi^{2}\) of positive and negative COMPASS SIDIS data, the total \(\chi^{2}\)/d.o.f and the error bands of various parton species are extracted considering the nCTEQ15WZ sets. In the case of NNLO accuracy, although the nuclear PDF sets of nNNPDF1.0 can not reduce the individual \(\chi^{2}\) of positive and negative COMPASS SIDIS data and the total \(\chi^{2}/d.o.f\), one can see the reduction of the uncertainty bands of extracted FFs. ###### Acknowledgements. The authors gratefully acknowledge many helpful discussions and comments by Valerio Bertone. Authors thank the School of Particles and Accelerators, Institute \begin{table} \begin{tabular}{l c c c} \hline \hline Experiment & \(N_{dat}\) & \(\frac{\chi^{2}}{N_{dat}}\) (NNPDF3.1) & \(\frac{\chi^{2}}{N_{dat}}\) (nNNPDF1.0) \\ \hline \hline COMPASS \(H^{+}\)[36] & 157 & 1.711 & 2.340 \\ COMPASS \(H^{-}\)[36] & 157 & 1.301 & 2.455 \\ TASS014 [22] & 14 & 2.167 & 2.073 \\ TASS022 [22] & 14 & 1.241 & 1.218 \\ TPC [25] & 21 & 0.741 & 0.801 \\ TASS044 [23] & 14 & 2.466 & 2.491 \\ ALEPH [31] & 32 & 0.802 & 0.797 \\ DELPHI (incl.) [32] & 21 & 0.598 & 0.597 \\ DELPHI (\(uds\) tag) [32] & 21 & 0.374 & 0.407 \\ DELPHI (\(b\) tag) [32] & 21 & 1.030 & 1.068 \\ OPAL (incl.) [34] & 19 & 1.838 & 1.812 \\ OPAL (\(uds\) tag) [34] & 19 & 0.830 & 0.821 \\ OPAL (\(c\) tag) [34] & 19 & 0.603 & 0.610 \\ OPAL (\(b\) tag) [34] & 19 & 0.312 & 0.369 \\ SLD (incl.) [27] & 34 & 0.944 & 0.960 \\ SLD (\(uds\) tag) [27] & 34 & 0.941 & 0.922 \\ SLD (\(c\) tag) [27] & 34 & 1.115 & 1.156 \\ SLD (\(b\) tag) [27] & 34 & 1.225 & 1.330 \\ \hline \hline Total \(\chi^{2}\)/d.o.f. & 684 & 1.305 & 1.826 \\ \hline \hline \end{tabular} \end{table} Table 4: Same as Table. 3 but this time for our unidentified light charged hadrons FFs at NNLO accuracy. The NNPDF3.1 proton PDFs are considered as out baseline fit, and the NNLO nuclear PDF set from nNNPDF1.0 also considered to study the nuclear corrections. for Research in Fundamental Sciences (IPM) for financial support of this project. Maryam Soleymaninia is thankful to the Iran Science Elites Federation for the financial support. Hamzeh Khanpour also is thankful to the Physics Department of University of Udine, and International Centre for Theoretical Physics (ICTP) for the financial support provided for this research. \begin{table} \begin{tabular}{l c c c c c} \hline \hline Experiment & \(N_{dat}\) & \(\frac{\chi^{2}}{N_{\mathrm{dat}}^{2}}\) (UNDPF3.1) & \(\frac{\chi^{2}}{N_{\mathrm{dat}}^{2}}\) (nNDPF3.0) & \(\frac{\chi^{2}}{N_{\mathrm{dat}}^{2}}\) (EPPS21) & \(\frac{\chi^{2}}{N_{\mathrm{dat}}^{2}}\) (aCTEQ15WZ) \\ \hline \hline COMPASS \(\pi^{+}\)[36] & 157 & 0.601 & 0.731 & 3.176 & 0.593 \\ COMPASS \(\pi^{-}\)[36] & 157 & 0.417 & 0.422 & 0.471 & 0.430 \\ BELLE[28] & 70 & 0.093 & 0.092 & 0.095 & 0.093 \\ BABAR [26] & 39 & 1.286 & 1.300 & 1.284 & 1.375 \\ TASSO12 [21] & 4 & 0.976 & 0.975 & 0.976 & 0.977 \\ TASSO14 [22] & 9 & 1.376 & 1.389 & 1.380 & 1.374 \\ TASSO22 [22] & 8 & 1.853 & 1.915 & 1.847 & 1.838 \\ TPC [25] & 13 & 0.223 & 0.229 & 0.226 & 0.223 \\ TASSO30 [21] & 2 & 0.337 & 0.347 & 0.330 & 0.336 \\ TASSO34 [23] & 9 & 1.190 & 1.353 & 1.189 & 1.165 \\ TASSO44 [23] & 6 & 1.165 & 1.247 & 1.149 & 1.164 \\ TOPAZ [29] & 5 & 0.264 & 0.319 & 0.257 & 0.260 \\ ALEPH [30] & 23 & 1.121 & 1.139 & 0.990 & 1.164 \\ DELPHI (incl.) [32] & 21 & 1.312 & 1.311 & 1.407 & 1.305 \\ DELPHI (\(uds\) tag) [32] & 21 & 2.532 & 2.573 & 2.302 & 2.517 \\ DELPHI (\(b\) tag) [32] & 21 & 1.731 & 1.785 & 1.672 & 1.756 \\ OPAL (incl.) [33] & 24 & 1.629 & 1.674 & 1.561 & 1.661 \\ SLD (incl.) [27] & 34 & 1.102 & 1.096 & 0.950 & 1.087 \\ SLD (\(uds\) tag) [27] & 34 & 1.601 & 1.694 & 1.397 & 1.463 \\ SLD (\(b\) tag) [27] & 34 & 0.568 & 0.604 & 0.586 & 0.598 \\ \hline \hline Total \(\chi^{2}/\mathrm{d.o.f.}\) & 691 & 0.758 & 0.809 & 1.456 & 0.761 \\ \hline \hline \end{tabular} \end{table} Table 5: The list of input data sets for the pion production included in our pion FFs analysis. For each data set, we have indicated the experiments, corresponding published reference and the number of data points. In the last four columns, we show the value of \(\chi^{2}/N_{\mathrm{dat}}\) resulting from the FF fit at NLO order by considering proton PDF sets from NNPDFF3.1 and nuclear PDF sets available in the literature, nNDPF3.0 [12], EPPS21 [13], and nCTEQ15WZ [14]. The total value of the total \(\chi^{2}/\mathrm{d.o.f.}\) also is shown at the bottom of the table. Figure 1: Comparison of kaon FFs extracted from NNPDF3.1 proton PDF sets as our baseline, and the nuclear PDF sets from nNPDF3.0, EPPS21 and nCTEQ15WZ. We present both the absolute values, and the ratio to the NNPDF3.1 proton PDFs baseline as well. The results presented for the NLO accuracy at \(Q=5\) GeV. Figure 2: Same as Fig. 1 but this time for the NNLO accuracy. The NNPDF3.1 proton PDF sets are considered as our baseline fit, and the NNLO nuclear PDF sets from nNNPDF1.0 also considered to study the nuclear corrections. Figure 3: Comparison of charged hadron FFs extracted from NNPDF3.1 proton PDF sets as our baseline, and the nuclear PDF sets from nNPDF3.0, EPPS21 and nCTEQ15WZ. We present both the absolute values, and the ratio to the NNPDF3.1 proton PDFs baseline as well. The results presented for the NLO accuracy at \(Q=5\) GeV. Figure 4: Same as Fig. 3 but this time for the NNLO accuracy. The NNPDF3.1 proton PDF sets are considered as our baseline fit, and the NNLO nuclear PDF sets from nNNPDF1.0 also considered to study the nuclear corrections. \begin{table} \begin{tabular}{l c c c} \hline \hline Experiment & \(N_{dat}\) & \(\frac{\chi^{2}}{N_{dat}}\) (NPDFS.1) & \(\frac{\chi^{2}}{N_{dat}}\) (nNPDFS1.0) \\ \hline \hline COMPASS \(\pi^{+}\)[36] & 157 & 0.989 & 1.208 \\ COMPASS \(\pi^{-}\)[36] & 157 & 0.564 & 0.640 \\ BELIE[28] & 70 & 0.096 & 0.095 \\ BABAR[26] & 39 & 1.012 & 1.073 \\ TASS012[21] & 4 & 0.972 & 0.973 \\ TASS014[22] & 9 & 1.387 & 1.386 \\ TASS022[22] & 8 & 1.931 & 1.900 \\ TPC[25] & 13 & 0.265 & 0.267 \\ TASS030[21] & 2 & 0.354 & 0.352 \\ TASS034[23] & 9 & 1.494 & 1.431 \\ TASS044[23] & 6 & 1.360 & 1.364 \\ TPDAZ[29] & 5 & 0.360 & 0.355 \\ ALEPH[30] & 23 & 1.306 & 1.228 \\ DELPHI (incl.)[32] & 21 & 1.281 & 1.295 \\ DELPHI (\(uds\) tag)[32] & 21 & 2.745 & 2.669 \\ DELPHI (\(b\) tag)[32] & 21 & 1.812 & 1.824 \\ OPAL (incl.)[33] & 24 & 1.739 & 1.733 \\ SLD (incl.)[27] & 34 & 1.039 & 1.008 \\ SLD (\(uds\) tag)[27] & 34 & 1.968 & 1.870 \\ SLD (\(b\) tag)[27] & 34 & 0.678 & 0.651 \\ \hline \hline Total \(\chi^{2}/\)d.o.f. & 691 & 0.935 & 1.008 \\ \hline \hline \end{tabular} \end{table} Table 6: Same as Table. V but this time for our pion FFs at NNLO accuracy. The NNPDF3.1 proton PDFs are considered as our baseline fit, and the NNLO nuclear PDF set from nNPDF1.0 also considered to study the nuclear corrections. Figure 5: Comparison of pion FFs extracted from NNPDF3.1 proton PDF sets as our baseline, and the nuclear PDF sets from nNPDF3.0, EPPS21 and nCTEQ15WZ. We present both the absolute values, and the ratio to the NNPDF3.1 proton PDFs baseline as well. The results presented for the NLO accuracy at \(Q=5\) GeV. Figure 6: Same as Fig. 5 but this time for the NNLO accuracy. The NNPDF3.1 proton PDF sets are considered as our baseline fit, and the NNLO nuclear PDF sets from nNNPDF1.0 also considered to study the nuclear corrections.
2306.06146
Hidden Classification Layers: Enhancing linear separability between classes in neural networks layers
In the context of classification problems, Deep Learning (DL) approaches represent state of art. Many DL approaches are based on variations of standard multi-layer feed-forward neural networks. These are also referred to as deep networks. The basic idea is that each hidden neural layer accomplishes a data transformation which is expected to make the data representation "somewhat more linearly separable" than the previous one to obtain a final data representation which is as linearly separable as possible. However, determining the appropriate neural network parameters that can perform these transformations is a critical problem. In this paper, we investigate the impact on deep network classifier performances of a training approach favouring solutions where data representations at the hidden layers have a higher degree of linear separability between the classes with respect to standard methods. To this aim, we propose a neural network architecture which induces an error function involving the outputs of all the network layers. Although similar approaches have already been partially discussed in the past literature, here we propose a new architecture with a novel error function and an extensive experimental analysis. This experimental analysis was made in the context of image classification tasks considering four widely used datasets. The results show that our approach improves the accuracy on the test set in all the considered cases.
Andrea Apicella, Francesco Isgrò, Roberto Prevete
2023-06-09T10:52:49Z
http://arxiv.org/abs/2306.06146v2
Hidden Classification Layers: a study on Data Hidden Representations with a Higher Degree of Linear Separability between the Classes ###### Abstract In the context of classification problems, Deep Learning (DL) approaches represent state of art. Many DL approaches are based on variations of standard multi-layer feed-forward neural networks. These are also referred to as deep networks. The basic idea is that each hidden neural layer accomplishes a data transformation which is expected to make the data representation "somewhat more linearly separable" than the previous one to obtain a final data representation which is as linearly separable as possible. However, determining the appropriate neural network parameters that can perform these transformations is a critical problem. In this paper, we investigate the impact on deep network classifier performances of a training approach favouring solutions where data representations at the hidden layers have a higher degree of linear separability between the classes with respect to standard methods. To this aim, we propose a neural network architecture which induces an error function involving the outputs of all the network layers. Although similar approaches have already been partially discussed in the past literature, here we propose a new architecture with a novel error function and an extensive experimental analysis. This experimental analysis was made in the context of image classification tasks considering four widely used datasets. The results show that our approach improves the accuracy on the test set in all the considered cases. keywords: neural networks; hidden layers, hidden representations, linearly separable + Footnote †: journal: Pattern Recognition Letters ## 1 Introduction Nowadays, the success of Deep Learning (DL) approaches has led to an increase in interest in Multi-Layer Feed-Forward (MLFF) neural networks (LeCun et al., 2015) insofar as a successful class of deep neural networks consists of MLFF networks with more than one hidden layer and possibly some specific architectural choices. In the rest of the paper we will refer to such Deep Neural Networks as DNNs. In a nutshell, DNN networks are computational architectures organised as \(L\) consecutive layers or levels of elementary computing units, called _neurons_. The last layer \(L\) is the _output_ layer, and the remaining layers are usually called _hidden_ or _internal_ layers. In a DNN network each hidden layer \(l\) performs a non-linear functional map \(\Phi_{\theta_{l}}^{l}\) from the output of the previous layer \(\mathbf{z}^{l-1}\) (and possibly other previous layers) to the output of the layer itself. Where \(\theta_{l}\) are the weights associated to the connections incoming into the layer \(l\), plus the biases of the layer. By contrast, the output layer may also perform a linear transformation. In other words, the whole computation of a DNN can be viewed as a non-linear parametric functional mapping \(\mathbf{y}=M(\mathbf{x};\theta)\) from a \(d\)-dimensional space to a \(c\)-dimensional space, where \(d\) is the number of input variables and \(c=m_{L}\) is the number of neurons in the output layer. The parameters \(\theta\) are the weights and biases of the network, and \(\mathbf{y}\) are the output values of the output layer. Although from a theoretical point of view the DNNs capability of being universal approximators has been extensively discussed (Cohen et al., 2016; Huang et al., 2000; Longstaff and Cross, 1987), together with the inducted hidden feature representation spaces (Lerner et al., 1999), it is important to notice that the difficult to effectively find the most suitable \(\theta\) remains. In particular, when DNNs are applied in the context of classification problems, one has to find the parameters \(\theta_{l}\) such that the composition of \(L-1\) non-linear transformations \(\mathbf{z}^{L-1}=\Phi_{L-1}\big{(}\Phi_{L-2}(\ldots\Phi_{1}(\mathbf{x}))\big{)}\) maps each input \(\mathbf{x}\) from a _non-linearly_ separable space into a _linearly separable_ one. In fact, in the context of classification problems, one of the main goals is to find a suitable data representation which allows to obtain a linearly separable classification problem. Plausibly, when a DNN is used, each internal representation \(\mathbf{z}_{l}\) can be expected to make the representations of \(\mathbf{x}\) "somewhat more linearly separable" than the previous one \(\mathbf{z}_{l-1}\). We underline that the complexity of a classification problem can be measured with respect different aspects, however class separability is a key aspect and different levels of class separability can be quantified (Loreena et al., 2019). In particular, in (Schilling et al., 2021) the Generalized Discrimination Value (GDV) to measure the separability between two dataset is introduced. The GDV is defined as the gap between the mean intra-cluster and the mean inter-cluster distances, computed on a set of labeled data represented in some space. More in detail, the GDV compares in a quantitative way the degree of class separability between two data representations. Since GDV can be computed on different types of representations, it can be also used to compare the separability of the same data represented in different spaces, such as the different representations returned by different neural networks' layers. However, we again emphasise that how to determine the appropriate parameters \(\theta\) from a data set by a supervised learning process minimizing an error (or loss) function is still a critical problem. We notice that error functions usually depend on the final network output values only, without taking care about the results obtained in the hidden layers. Thus, starting from the previous considerations, in this paper we investigate the possibility to achieve a supervised learning approach which favours solutions where \(\mathbf{x}\)'s representations at the hidden levels have a higher degree of linear separability between the classes with respect to standard approaches. To this aim, we propose a DNN architecture which induces an error function involving the output values of all the network layers. More specifically, as we will discuss in more detail in Section 2, the output of each hidden layer \(l\) is sent to an additional linear output layer which is trained to classify the input \(x\) on the basis of the input representation encoding in the layer \(l\) (see Figure 1). From now on, we named this architecture Hidden Classification Layer network (HCL). We investigated the impact of this type of solution in a series of experimental scenarios as we will discuss in more detail in Section 3. Although similar approaches have already been partially discussed in the past literature (see, for example, (Lee et al., 2015)), here we propose both a different version in terms of both neural architecture and error function, and a more extensive experimental analysis (see Sections 2 and 3). In particular, in (Lee et al., 2015) the supervision of the hidden layer was made by SVMs instead of linear neural layers as in our case. In (Wang et al., 2020) a cascade of Convolutional Neural Networks (C-CNN) was proposed. C-CNN is composed of hidden layers combined together through dilated convolutions and trained using a proposed progress optimisation algorithm. Also in this case, our approach proposes a simpler architecture to favour hidden representations with a higher degree of class separability. The rest of the paper is organised as follow: in Section 2 the proposed method is described; Section 3 describes the experimental setup and the evaluation methods; in Section 4 the results are reported and discussed; finally, Section 5 contains final remarks. ## 2 Model description A neural network, as reminded before, is structured in L layers of neurons. Each neuron \(i\) belonging to the \(l\)-th layer, achieves a two-step computation (see (Bishop and Nasrabadi, 2006), chapter 4): a linear combination \(a_{i}^{l}\) of the neuron's inputs is computed first, and then the neuron output \(z_{i}^{l}\) is computed by an activation function \(f_{l}(\cdot)\), i.e., \(z_{i}^{l}=f_{l}(a_{i}^{l})\). Usually, activation functions are nonlinear function (see (Apicella et al., 2021) for a review). The activation function input \(a_{i}^{l}\) is usually computed on the basis of real values, said _weights_, associated with the connections coming from the neurons belonging to the layer \(l-1\) (and possibly from other previous layers) and a bias value associated to the neuron \(i\). Each layer \(l\) is composed of \(m_{l}\) neurons, and the flow of computation proceeds from the the first hidden layer to the output layer in a forward-propagation fashion. In this research work, we focus on \(C\)-classes classification problems, with \(C\geq 2\). In this context, Cross-Entropy (CE) loss (Wang et al., 2022) is one of the most common loss function to be optimised. Given a dataset of N samples, DS=\(\{(\mathbf{x}^{n},\mathbf{t}^{n})\}_{n=1}^{N}\), CE for the n-th sample can be expressed as follows: \[CE^{(n)}(\theta;\mathbf{y}^{n},\mathbf{t}^{n})=-\sum_{c=1}^{C}t_{c}^{n}\log(y _{c}^{n})\] where \(\mathbf{t}^{n}\in\{0,1\}^{C}\) is the one-hot encoding representation of the class label of the \(n\)-th sample of the dataset, and \(\mathbf{y}^{n}=\mathbf{y}(\mathbf{x}^{n};\theta)\) is the output of the neural network when it is fed with the input \(\mathbf{x}^{n}\). Finally, \(\theta\) corresponds to all the network parameters. The total CE loss is equal to the sum of the single \(CE^{(n)}\) over the dataset samples, i.e., \(CE=\sum\limits_{n=1}^{N}CE^{(n)}\). As previously said, this loss formulation takes into account only the classification reported by the final layer of the network, without considering how the intermediate network levels affect the final classification scores. By contrast, in our model, HCL network, the data representation corresponding to the output of each hidden layer is used as input of a linear classifier so as to favour a data representation for each level as separable as possible. More formally, given a DNN composed of \(l_{1},l_{2},\ldots,l_{L-1}\) hidden layers and a final layer \(l_{L}\) having \(C\) neurons, we connect each hidden layer \(l_{j},\ 1\leq j\leq L-2\) with a new layer \(\overline{l}_{j}\) acting as an independent classifier. Adopting a proper loss function to train each classifier \(\overline{l}_{j}\), we expect that the features learned by the associate layer \(l_{j}\) are the most discriminating as possible. In other words, additional \(L-2\) layers \(\{\overline{l}_{1},\overline{l}_{2},\ldots\overline{l}_{L-2}\}\) composed of \(C\) neurons are added, and each \(\overline{l}_{j}\) layer receives connections from the hidden layer \(l_{j}\) only, making each \(\overline{l}_{j}\) as an independent linear classifier. Therefore, given a DNN \(M\), we obtain an HCL network \(\overline{M}\) which will be composed of two distinct sets of layers: i) standard neural network layers \(\{l_{1},l_{2},\ldots,l_{L}\}\), composing M, and ii) _hidden classification layers_\(\{\tilde{l}_{1},\tilde{l}_{2},\ldots,\tilde{l}_{L-2}\}\), composing a set of layers where each layer \(\overline{l}_{i}\) favours more separable data representations in the respective hidden layer \(l_{i}\), independently from the subsequent layers. Each hidden classification layer \(\tilde{l}_{i}\) has a set of parameters \(\theta^{i}\). Each \(\theta^{i}\) is composed of a set of distinct parameters, corresponding to the connections incoming in the layer \(\tilde{l}_{i}\), and a set of shared parameters with the other \(\theta^{i}\), with \(j<i\), which correspond to the parameters of the DNN \(M\) down to the layer \(l_{i}\). In figure 1 a general scheme of the proposed approach is reported. Denoting with \(\overline{\mathbf{z}}^{n,j}\) the scores returned by the hidden classification layer \(\overline{l}_{j}\) on the \(n\)-th input sample, we propose the following Weighted Cross Entropy (WCE) loss formulation: \[WCE^{(n)}(\theta;\mathbf{y}^{n},\mathbf{t}^{n})=CE^{(n)}(\theta _{M};\mathbf{y}^{n},\mathbf{t}^{n})+\\ +\sum\limits_{j=1}^{L-1}\lambda_{j}\cdot CE^{(n)}(\theta^{j}; \overline{\mathbf{z}}^{n,j},\mathbf{t}^{n}) \tag{1}\] where \(\mathbf{y}^{n}\) is the score returned by the final layer of the classifier \(M,\overline{\mathbf{z}^{n,j}}\) is the score returned by the hidden classification layer \(\overline{l}_{j}\) tied to the \(l_{j}\) layer, \(\theta^{M}\) are the parameters of the model \(M\), and \(\{\lambda_{1},\lambda_{2},\ldots,\lambda_{L}\}\) is a set of regularisation coefficients greater than or equal to 0. Setting \(\lambda_{1}=\lambda_{2}=\cdots=\lambda_{L-1}=0\) results in standard CE loss applied to the final classification layer only, while different values give different weights to the hidden classification layers \(\{\tilde{l}_{j}\}_{j=1}^{L-1}\). ## 3 Experimental assessment ### Data and neural network models The performance of the HCM network architecture is assessed on image classification tasks considering four well-known datasets: _MNIST_, _Fashion MNIST_, _CIFAR 10_, and _CIFAR 100_. The MNISTLeCun et al. (1998) dataset consists of 70,000 grayscale images at a resolution of \(28\times 28\) representing 10 different classes (the digits from 0 to 9). It is divided in two sets: the former composed of 60,000 images usually used as training samples and the latter of the remaining 10,000 images usually used as test samples. Fashion-MNIST is a dataset of images representing fashion articles Xiao et al. (2017). Fashion-MNIST was proposed as a replacement for the original MNIST dataset for benchmarking machine learning algorithms, sharing the same image size and structure of training and testing splits. Indeed, it provides a training set of 60,000 examples and a test set of 10,000 examples. Each example is a 28x28 grayscale image, representing one of the following items: T-shirt/top, Trouser, Pullover, Dress, Coat, Sandal, Shirt, Sneaker, Bag, Ankle boot. CIFAR-10 dataset consists of 60,000 colour images of 10 different classes, that are _airplane_, _automobile_, _bird_, _cat_, _deer_, _dog_, _frog_, _horse_, _ship_, and _truck_. The dataset provides 50,000 training images and 10,000 test images at a resolution of \(32\times 32\). Concerning the neural network models which are used as baseline to evaluate the classification enhancement of HCL network architecture, we considered LeNet-5 LeCun et al. (1998), Hinton network Hinton et al. (2012), and ResNet18 He et al. (2016). They are among the most famous networks exploiting convolutional layers for image classification. In its standard formulation, LeNet-5 is composed of a sequence of 3 convolutional layers interspersed by 2 sub-sampling layers, followed by 2 final full-connected layers (the latest one for classification). Instead, Hinton network is composed of three convolutional hidden layers interleaved with three maxpooling layers. Finally, the main characteristic of a ResNet is the presence of shortcuts between non-consecutive layers that allows deep networks to be easily trained. In this work, we use the 18 layer residual network (ResNet18) described in He et al. (2016). Figure 1: a scheme of the proposed approach. Each hidden layer \(l^{l}\) of the main branch of the network produces an output \(vec_{l}^{l}\), and the final classification layer \(l^{L}\) produces the output \(vec_{l}\). For each hidden layer \(\vec{l}^{l}\), \(1\leq i<L\), a further classification layer \(\vec{l}^{l}\) is added. Each \(\vec{l}^{l}\) is fed with the respective \(\mathbf{z}^{l}\), producing an output \(\mathbf{\bar{z}}^{l}\). Therefore, all outputs \(\mathbf{\bar{z}}^{l}\), \(\forall 1\leq i<L\), are used together with the network classification output \(\mathbf{y}\) to compute the final WCE loss. ### Evaluation Each model is evaluated on both the original version (_vanilla_) proposed in their respective works and on its modified instance as described in Section 2. All the models were trained using the same experimental setup reported in their reference papers, except for Learning Rate \(LR\), the number of Max Epochs \(ME\), and the Patience Epochs \(PE\), which can be strongly dependent by the network architecture. \(ME\) and \(PE\) are experimentally set to 1000 and 200 respectively, since we experimentally noticed that these values are enough to converge in all the analysed cases, while optimal \(LR\) and \(\lambda\) values are found through a grid-search approach. For the \(LR\), the search space was \(LR\in[10^{-5},10^{-1}]\), instead different combinations are considered for \(\lambda\) parameters. Experiments on ResNet involving CIFAR 10 and CIFAR 100 dataset were made both considering only original data and augmented data, using 4 pixels zero padding, corner cropping, and random flipping. Importantly, in order to experimentally show that the proposed method leads toward more easily separable data representations we computed Generalized Discrimination Value (GDV) measure Schilling et al. (2021) for each vanilla network's layer and its corresponding version equipped with hidden classification layers. We expect that, as the depth of the network increases, the data representations obtained with the proposed network's layout are more easily separable respect to the representations obtained by the respective models without additional layers. Note that GDV is a measure of how well different data classes separate.GDV values result 0.0 for data points with randomly shuffled classes, and \(-1.0\) in the case of perfectly separable classes. More in detail, GDV on a data representation \(\mathbf{z}\) is defined as \[GDV(\mathbf{z})=\frac{1}{\sqrt{D}}\Big{(}\frac{1}{L}\sum_{c=1}^ {C}d^{intra}(\mathbf{z}_{c})+\\ -\frac{2}{C(C-1)}\sum_{c=1}^{C-1}\sum_{m=c+1}^{C}d^{inter}( \mathbf{z}_{c},\mathbf{z}_{m})\Big{)}\] where \(d^{intra}(\mathbf{z}_{c})\) is the mean intra-class distance on the data representations of the data \(\mathbf{z}_{c}\) belonging to the class \(c\), and \(d^{inter}(\mathbf{z}_{c},\mathbf{z}_{m})\) is the mean inter-class distance on the data representations \(\mathbf{z}_{c},\mathbf{z}_{m}\) belonging to the \(c\) and \(m\) classes. ## 4 Results In Tab. 1 the test set accuracy, which was obtained by both the HCL network architecture and the vanilla networks, is reported. It is shown that the adoption of the HCL architecture improves the accuracy in all the cases, especially in the cases where a low accuracy for vanilla networks was obtained. In these cases, in fact, HCL network architecture appears to give a more significant improvement. In Fig. 3 the GDV values for each layer of each model and for CIFAR10 and CIFAR100 dataset are reported. ## 5 Conclusion In this research work, we experimentally investigated the impact of constraining the classification complexity of the intermediate input representations with respect to their linear separability on the performances of DNNs in classification tasks. To this aim, we proposed a novel DNN architecture, which we named Hidden Classification Layer (HCL) network, where the output of each standard hidden layer is sent to a hidden classification layer trained to classify the input \(x\) based on the \(x\) representation given by the standard layer itself. HCL network architecture allows obtaining solutions with input representations at the hidden levels having a lower classification complexity with respect to their linear separability. Note that our approach can be applied in slightly different ways: 1) given an already known neural network architecture, one can, first, augment it by hidden classification layers and, then, train the whole system from scratch; 2) given an already trained neural network architecture, one can, first, augment it by hidden classification layers and, then, tune the whole system; 3) one can design and train a new neural architecture equipped with hidden classification layers. In this study, we used the first approach to test our proposal by considering three successful neural network models (LeNet-5, \begin{table} \begin{tabular}{l c c c} \hline \hline & **Model** & **Baseline** & **Proposed** \\ \hline **MNIST** & LeNet5 & 99.0 & **99.2** \\ & Hinton & 98.7 & **99.4** \\ \hline **FMNIST** & LeNet5 & 90.6 & **90.8** \\ & Hinton & 92.1 & **92.6** \\ & ResNet & 92.3 & **93.3** \\ \hline **CIFAR10** & LeNet5 & 66.2 & **71.5** \\ & Hinton & 81.2 & **83.3** \\ & ResNet & 86.3 & **89.0** \\ & ResNet (augmented) & 94.4 & **94.6** \\ \hline **CIFAR100** & LeNet5 & 34.9 & **38.4** \\ & Hinton & 52.5 & **53.3** \\ & ResNet & 60.1 & **63.6** \\ & ResNet (augmented) & 74.7 & **75.4** \\ \hline \hline \end{tabular} \end{table} Table 1: Results of the evaluation stage. For each dataset, accuracy on the test set obtained on both the vanilla models (_baseline_) and the proposed ones are reported. ResNet has not been tested on MNIST dataset due to the already very high accuracies obtained with the other models. For CIFAR10 and CIFAR100, performance was evaluated also using augmented data (_augmented_) for ResNet Figure 3: GDV values obtained with the proposed approach (LAT) compared with the vanilla networks on the CIFAR100 dataset. On the x axis, the layer of the model and on the y axis the respective GDV value. Figure 2: GDV values obtained with the proposed approach (LAT) compared with the vanilla networks on the CIFAR10 dataset. On the x axis, the layer of the model and on the y axis the respective GDV value. Hinton network, and ResNet18). These models were trained with and without hidden classification layers to evaluate the impact of HCL on the model performances experimentally. Each model was trained and tested on four datasets (MNIST, fashion-MNIST, CIFAR-10 and CIFAR-100). The results show that the HCL network has a positive impact uniformly (see Table 1). It is interesting that the proposed approach leads to a GDV improvement in almost all cases, suggesting that the HCL network architecture can help the model build more separable inner representations. Moreover, it is worth noting that, in all the cases and with and without hidden classifier layers, the GDV values exhibit only a slight decrement for the initial network layers or they have even a wavering behaviour. Just only for the last layers, there is a sharp decrement (this decrease is particularly pronounced for HCL networks). Thus, these results are consistent with (Balduzzi et al., 2017), where the authors show experimentally that, during the learning phase, the loss derivatives with respect to the network parameters behave very similarly to a random walk on the first weight layers. In fact, in our case, data separability occurs mainly in the last layers of the network at the end of the learning process. ## Funding This work is supported by the European Union - FSE-REACT-EU, PON Research and Innovation 2014-2020 DM1062/2021 contract number 18-I-15350-2 and by the Ministry of University and Research, PRIN research project "BRIO - BIAS, RISK, OPACITY in AI: design, verification and development of Trustworthy AI.", Project no. 2020SSKZ7R.
2310.09593
Context-aware Session-based Recommendation with Graph Neural Networks
Session-based recommendation (SBR) is a task that aims to predict items based on anonymous sequences of user behaviors in a session. While there are methods that leverage rich context information in sessions for SBR, most of them have the following limitations: 1) they fail to distinguish the item-item edge types when constructing the global graph for exploiting cross-session contexts; 2) they learn a fixed embedding vector for each item, which lacks the flexibility to reflect the variation of user interests across sessions; 3) they generally use the one-hot encoded vector of the target item as the hard label to predict, thus failing to capture the true user preference. To solve these issues, we propose CARES, a novel context-aware session-based recommendation model with graph neural networks, which utilizes different types of contexts in sessions to capture user interests. Specifically, we first construct a multi-relation cross-session graph to connect items according to intra- and cross-session item-level contexts. Further, to encode the variation of user interests, we design personalized item representations. Finally, we employ a label collaboration strategy for generating soft user preference distribution as labels. Experiments on three benchmark datasets demonstrate that CARES consistently outperforms state-of-the-art models in terms of P@20 and MRR@20. Our data and codes are publicly available at https://github.com/brilliantZhang/CARES.
Zhihui Zhang, JianXiang Yu, Xiang Li
2023-10-14T14:29:52Z
http://arxiv.org/abs/2310.09593v1
# Context-aware Session-based Recommendation with Graph Neural Networks ###### Abstract Session-based recommendation (SBR) is a task that aims to predict items based on anonymous sequences of user behaviors in a session. While there are methods that leverage rich context information in sessions for SBR, most of them have the following limitations: 1) they fail to distinguish the item-item edge types when constructing the global graph for exploiting cross-session contexts; 2) they learn a fixed embedding vector for each item, which lacks the flexibility to reflect the variation of user interests across sessions; 3) they generally use the one-hot encoded vector of the target item as the hard label to predict, thus failing to capture the true user preference. To solve these issues, we propose CARES, a novel context-aware session-based recommendation model with graph neural networks, which utilizes different types of contexts in sessions to capture user interests. Specifically, we first construct a multi-relation cross-session graph to connect items according to intra- and cross-session item-level contexts. Further, to encode the variation of user interests, we design personalized item representations. Finally, we employ a label collaboration strategy for generating soft user preference distribution as labels. Experiments on three benchmark datasets demonstrate that CARES consistently outperforms state-of-the-art models in terms of P@20 and MRR@20. Our data and codes are publicly available at [https://github.com/brilliantZhang/CARES](https://github.com/brilliantZhang/CARES). Session-based recommendation, Graph neural networks, Collaborative learning ## I Introduction Recommendation systems play a crucial role in various fields because they provide users with personalized information to complete a task in the midst of a large amount of information. At present, many recommendation models have achieved great success, but most of them usually need to use user profiles. However, as the number of users on the platform grows and privacy awareness increases, user profiling may not be available in certain applications. Without obtaining user profiles as well as long-term historical user behaviors, it is hard to accurately model portraits of users. Consequently, session-based recommendation (SBR) has recently attracted more attention. Here, a session can generate interactive behavior sequence (e.g., clicks in e-commerce scenarios) in a short period of time, and SBR aims to predict the _next item_ based on an anonymous short-term behavior sequence. To address the SBR problem, some existing methods [9, 10, 11, 19] utilize the rich context information in sessions, which generally includes both _intra-session_ and _cross-session_ ones. For the former, we can further divide it into _item-level context_, which characterizes the neighboring items in the behavior sequence for an item, and _session-level context_, which refers to the complete sequence information in a session. Similarly, the latter includes collaborative information from sessions with similar behavioral patterns for both item and session. Details on the division of contexts are given in Figure 1. Early studies [4, 5, 7] for SBR employ intra-session contexts only, whose performance could be adversely affected when the behavior sequence in a session is very sparse. Recently, there are also methods [9, 10, 11, 19] that leverage both intra-session and cross-session contexts, which aim to incorporate contextual information from relevant sessions to enrich the representation of a given session. In particular, some methods [11, 19] propose to construct a global graph to link items from various sessions according to the intra- and cross-session item-level context information, and then learn item/session embeddings based on the graph. Despite the success, most of these methods suffer from three major limitations. First, when constructing the global graph, they fail to distinguish the item-item edge types. Since it has been verified in [29, 30] that integrating item attributes can improve the recommendation performance, the categorical attributes of items (e.g., "shirts" and "pants" belong to the apparel category), can be used to distinguish item relations. For example, if products in two categories are frequently interacted by users, the relation between the two item categories is of more importance. Second, they learn a fixed embedding vector for each item. However, since user interest could vary across sessions, the embedding of an item should be learned to reflect the variation of user interests and personalized w.r.t. different sessions. Third, they generally use the one-hot encoded vector of the target item as the hard label to be predicted, which may not reflect the true user preference. However, the true distribution of user preferences is usually unknown, as only a limited number of items are exposed to users. Simply regarding the one-hot encoded vector of the target item as the true distribution could induce bias and lead to the overfitting problem [15]. In this paper, to address these problems, we propose a novel context-aware session-based recommendation model CARES, which leverages the four types of contexts introduced earlier. Specifically, we first construct a multi-relation cross-session graph to connect items according to intra- and cross-session item-level contexts, where edge relations are defined based on item categories. Then based on the graph, we learn general item embeddings with graph neural networks (GNNs). Further, to encode the variation of user interests, we also learn personalized item representations w.r.t. sessions with a gating mechanism. After that, we unify item embeddings with item positions and session length to learn session representations. Finally, to alleviate the bias induced by the hard label of one-hot encoded vector of the target item in a session, we employ internal- and external-session-level contexts, and present a label collaboration strategy, which uses most similar historical sessions to the current session for collaborative filtering and generates soft label of user preferences to be predicted. We next summarize our main contributions in this paper as follows: * We propose a novel context-aware session-based recommendation model CARES. * We design personalized item embeddings w.r.t. sessions to capture the variation of user interests across sessions. * We propose a simple and effective label collaboration method that generates soft user preference distribution as labels. * We conduct extensive experiments on three public benchmark datasets to show the superiority of our method over other state-of-art models. ## II Related Work ### _Session-based Recommendation_ Early studies [3] on SBR use the similarity between the last item of the session and candidate items to make recommendations. However, they omit the sequential information in the session. While the Markov-chain-based method [4] can bridge the gap, the number of states and the computational complexity increase exponentially as the problem scale increases. Recently, owing to the powerful representation capability of deep learning, many deep-learning-based methods [5, 6, 7] have been successfully applied to SBR. In particular, some approaches [5, 7] exploit Recurrent Neural Networks (RNNs) to characterize the item's sequential information in the session. However, these RNN-based methods are incapable of capturing long-term item dependencies. Recently, Graph Neural Network (GNN) [8, 12, 16] has attracted more and more attention due to their powerful learning ability for graph structure data representation. To explore the complex transition relation between items in the session, GNN-based SBR constructs sessions into graphs and utilizes GNNs to model the session graph. For instance, SR-GNN [8] first converts the session into a graph and utilizes Gated GNN [23] to model the session graph to explore the complex transition relations between items in the session. After that, GC-SAN [13] further extends SR-GNN by adding self-attention mechanism. However, constructing sessions into graphs will introduce noise and lose the sequential order information, so some GNN-based methods are proposed to alleviate these problems. LESSER [14] improves the way of graph construction for sessions, taking into account the relative order of nodes in sessions. SGNN-HN [12] alleviates the long-range dependency problem by introducing a Star GNN, which improves the information propagation mechanism between items. All these methods only focus on utilizing the internal information in a session. ### _Cross-session Learning in SBR_ Utilizing the current session only to make recommendations is constrained by its limited information. To incorporate collaborative information from external sessions, some collaborative filtering-based SBR methods are proposed to enhance the current session representation. For example, CSRM [9] incorporates the relevant information contained in the neighborhood sessions by adopting a memory module to obtain more accurate session representations. CoSAN [10] utilizes multi-head attention mechanism to fuse item representations in collaborative sessions by building dynamic item representations. GCE-GNN [11] simultaneously constructs local session graphs and a global graph, then extracts information related to the current session from the global graph. MTD [32] constructs a global graph connecting adjacent items in each session and utilizes graphical mutual information maximization to capture global item-wise transition information to enhance the current session's representation. \(S^{2}\)-DHCN [38] utilizes hypergraph convolutional networks to capture high-order item relations and constructs two types of hypergraphs to learn information from inter- and intra-session. The view augmentation in COTREC [37] enables the model to capture beyond-pairwise relations among items across sessions. ### _Multi-relation Learning in SBR_ Heterogeneous graphs have proven effective in handling information by modeling complex high-order dependencies Figure 1: Contexts referred to in this paper. among heterogeneous information. They can extract user interests more accurately through global item relations across sessions [16, 34, 35]. AutoGSR [16] uses Network Architecture Search (NAS) techniques to automatically search for better GNN architectures that capture information on local-context relations and various item-transition semantics. MGIR [35] utilizes item relations of incompatible and co-occurrence relations to generate enhanced session representations, while CoHHN [34] proposes a heterogeneous hypergraph network to model price preferences. These works either built multiple relation graphs or used hypergraphs to model artificial features or side information as auxiliary information in modeling user actions. However, constructing sessions into multiple relation graphs is cumbersome. Therefore, we propose a new approach that models association analysis of items' categories in SBR based on a single heterogeneous graph. ## III Preliminaries In this section, we introduce the problem statement of SBR and the definition of item-side information. ### _Problem Statement_ We formally formulate the task of session-based recommendation (SBR). Let \(V=\{v_{1},v_{2},\ldots,v_{m}\}\) be all of items, where \(m\) is the number of items in \(V\). Assuming that all sessions are denoted as \(U=\{S_{1},S_{2},\ldots,S_{n}\}\), where \(n\) is the number of sessions. Each anonymous session \(S_{\tau}\) in \(U\), which is denoted by \(S_{\tau}=\{v_{1}^{\tau},v_{2}^{\tau},\ldots,v_{t}^{\tau}\}\), consists of a sequence of interactions in chronological order, where \(v_{t}^{\tau}\) denotes the item that the user interacted with at the \(t\)-th timestamp in the session \(S_{\tau}\), and the length of \(S_{\tau}\) is \(t\). The goal of SBR is to recommend the next item from \(V\) that is most probably interacted with by the user given the current session \(S_{\tau}\). We call the item that interacted at the \(t+1\)-th timestamp the target item or the ground truth item of the session, i.e., \(\left(\left[v_{1},v_{2},\ldots,v_{t}\right],v_{t+1}\right)\) is a session and its target item pair. ### _Item-side Information_ Item-side information describes the item itself and can provide extra complementary information for the recommendation. For each item \(v_{i}\), we use its category \(c_{v_{i}}\) as the item-side information to assist in learning user preference. Let \(C=\{c_{1},c_{2},\ldots,c_{l}\}\) be all of categories of items, where \(l\) is the number of categories of items in \(C\). Each category of item \(v_{i}\) is encoded into an unified embedding space, i.e., \(h_{i}^{c}\in\mathbb{R}^{d}\). ## IV The Proposed Method This section elaborates on our proposed novel Context-aware Graph Neural Networks for Session-based Recommendation (CARES). We first give an overview of CARES, which is illustrated in Figure 2. Next, we describe each component in detail. ### _Multi-relation Cross-session Graph_ Most early graph-based methods [8, 12, 13, 14, 16] model the item transition patterns in a single session into graphs only and ignore the global-level relations between items in different sessions. Therefore, we propose to build connections between different sessions to employ global-level item transition relations further. Specifically, we follow [11] to build these edge connections based on \(\varepsilon\)-neighbor sets of items in all sessions, which are formally defined as follows. **Definition 1**: \(\varepsilon\)_-Neighbor set [11]. Given a set of sessions \(U\), for an item \(v_{i}^{x}\) in session \(S_{x}\), its \(\varepsilon\)-Neighbor set is a set of items with:_ \[\mathcal{N}_{\varepsilon}(v_{i}^{x})=\left\{v_{j}^{y}|\,j\in[k- \varepsilon,k+\varepsilon],\forall v_{k}^{y}=v_{i}^{x},v_{k}^{y}\in S_{y},S_{y} \in U\right\},\] _where \(i,j,k\) are positions of items in corresponding sessions, respectively. Further, \(\varepsilon\) is used to control the neighboring range of item transition._ Based on the \(\varepsilon\)-Neighbor set, items from different sessions can be linked. Some existing works [11, 15] consider all the item transitions as one type of relation, while we distinguish item transitions by taking the categorical attribute of items into consideration. Intuitively, if a user successively clicks on items \(v_{1}\) and \(v_{2}\) whose categories are different, we cannot simply consider these two items are related, because this could also indicate the drift of user interest. Further, if a user sequentially clicks on items \(v_{1}\) and \(v_{2}\) with the same category, it is more likely that the two items are highly related. This is because a user usually views a number of similar items before picking the one to buy. Therefore, we propose to construct a multi-relation cross-session graph based on item context and category. Formally, it is defined as \(\mathcal{G}=(\mathcal{V},\mathcal{E})\), where \(\mathcal{V}\) denotes the node set that contains all items in \(V\) and \(\mathcal{E}=\{(v_{i},r_{ij},v_{j})|v_{i}\in V,v_{j}\in\mathcal{N}_{\varepsilon}(v _{i})\}\) represents the edge set in the graph. We use \(r_{ij}=(c_{i},c_{j})\) to denote the edge type, which captures the contextual relation between items of categories \(c_{i}\) and \(c_{j}\). Further, similar as in [31], for the edge between \(v_{i}\) and \(v_{j}\), we give a weight \(e_{ij}=\frac{Freq(v_{i}\in\mathcal{N}_{\varepsilon}(v_{i}))}{(log(Freq(v_{i})^ {x})+1)+\epsilon(log(Freq(v_{j})^{x})+1)}\). Here, \(Freq(\cdot)\) is the frequency counting function over all the sessions. To alleviate the dominant effect of a frequently occurred item, we also introduce a hyper-parameter \(\alpha\), whose value is set to 0.75 in our experiments. To speed up the model efficiency, for each item \(v_{i}\) in the graph, we only keep the top-\(N\) neighbors in each relation that have the largest weights with it. To further simplify the graph, we only retain the top-\(Q\) most frequent contextual relations in the graph. For others, we uniformly set \(r_{ij}=\texttt{Same}\) when \(c_{i}=c_{j}\); \(r_{ij}=\texttt{Drift}\), when \(c_{i}\neq c_{j}\). Figure 3 shows a toy example on converting sessions into a multi-relation cross-session graph. ### _Item Representation Learning_ After the multi-relation cross-session graph is constructed, we next learn item representations. We first use an embedding look-up table to initialize embedding \(\mathbf{h}_{i}\in\mathbb{R}^{d}\) for item \(v_{i}\). After that, we employ the attention mechanism [22] to generate the general embedding vector for each item based on GNNs. Then we use a gating mechanism to further learn a personalized embedding vector for each item w.r.t. a given session. **Learning General Item Representations.** Based on the multi-relation cross-session graph, we can easily capture both the intra-session and cross-session item-level context information. To learn the representation of an item, since its \(\varepsilon\)-Neighbors have different importance, we then introduce item-level attention. Note that for each item, it has various contextual relations. Therefore, when computing attention scores, we need to distinguish edge relations. Specifically, in the \(k\)-th layer, the representation of item \(v_{i}\) is derived by neighborhood aggregation, which is formulated as: \[\mathbf{h}_{i}^{(k)}=\alpha_{ii}\mathbf{W}_{1}\mathbf{h}_{i}^{(k-1)}+\sum_{v_{ j}\in\mathcal{N}(v_{i})}\alpha_{ij}\mathbf{W}_{1}\mathbf{h}_{j}^{(k-1)}. \tag{1}\] Here, the attention score \(\alpha_{ij}\) is computed by \[\alpha_{ij}=\frac{\exp\left(\mathbf{a}^{\top}\sigma\left(\mathbf{W}_{1}| \mathbf{h}_{i}^{(k-1)}\,\|\,\mathbf{h}_{j}^{(k-1)}\,\|\,e_{ij}\|\,\mathbf{r}_ {ij}\|\right)\right)}{\sum_{v_{k}\in\mathcal{N}(v_{i})\cup\{v_{i}\}}\exp\left( \mathbf{a}^{\top}\sigma\left(\mathbf{W}_{1}|\mathbf{h}_{i}^{(k-1)}\,\|\,e_{ ik}\|\,\mathbf{r}_{ik}\right)\right)},\] where \(\sigma\) is the LeakyReLU function, \(\mathbf{a}\) and \(\mathbf{W}_{1}\) are trainable parameters, and \(\|\) denotes the concatenation operator. We also take edge weight \(e_{ij}\) and edge relation embedding \(r_{ij}\in\mathbb{R}^{d}\) as edge features. Figure 3: Illustration of the construction of the cross-session graph. Here, we set \(\varepsilon\) = 2. Figure 2: The overview of CARES. **Learning Personalized Item Representations w.r.t. Sessions.** Note that \(\mathbf{h}_{i}^{(k)}\) in Eq. 1 leverages item-level context and reflects the general embedding vector of item \(v_{i}\). Since an item is generally contained in various sessions, we can further enrich the representation of an item w.r.t. a session. Given a session \(S\) and an item \(v_{i}\in S\), \(S\) could contain many items that are not in \(\mathcal{N}_{\varepsilon}(v_{i})\) and all the items in \(S\) reflect the user interest in the current session. Therefore, we introduce an embedding vector \(\mathbf{h}_{i}^{s}\) for item \(v_{i}\) that is personalized for the session \(S\). Inspired by [28], we add a virtual node \(\tilde{v}\) that is linked to all the items in the session \(S\), whose embedding vector \(\tilde{\mathbf{h}}\) is used to capture the information of all the items in \(S\). After that, we apply a gating mechanism to fuse \(\mathbf{h}_{i}\) and \(\tilde{\mathbf{h}}\) to generate \(\mathbf{h}_{i}^{s}\): \[\mathbf{h}_{i}^{s_{i}(k)}=(1-\delta_{i})\,\mathbf{h}_{i}^{(k)}+\delta_{i} \tilde{\mathbf{h}}^{(k-1)}, \tag{2}\] where the gating score \(\delta_{i}\) is computed by: \[\delta_{i}=\texttt{Sigmoid}\left(\frac{\left(\mathbf{W}_{2}\mathbf{h}_{i}^{ (k)}\right)^{\top}\left(\mathbf{W}_{3}\tilde{\mathbf{h}}^{(k-1)}\right)}{ \sqrt{d}}\right), \tag{3}\] where \(\mathbf{W}_{2}\),\(\mathbf{W}_{3}\in\mathbb{R}^{d\times d}\) are learnable parameters, and \(\sqrt{d}\) is the scaling coefficient. In this way, we can generate a personalized embedding vector \(\mathbf{h}_{i}^{s}\) for item \(v_{i}\) w.r.t. the session \(S\). When \(\delta_{i}\) is small, \(\mathbf{h}_{i}^{s}\) will be close to the general representation of item \(v_{i}\); otherwise, \(\mathbf{h}_{i}^{s}\) will be more indicative to the information in the current session \(S\). Finally, the embedding vector \(\tilde{\mathbf{h}}^{(k)}\) for \(\tilde{v}\) in the \(k\)-th layer is updated as: \[\tilde{\mathbf{h}}^{(k)}=\sum_{v_{i}\in S}\beta_{i}\mathbf{h}_{i}^{s_{i}(k)}, \tag{4}\] where the weight \(\beta_{i}\) is calculated by: \[\beta_{i}=\texttt{Softmax}\left(\frac{\left(\mathbf{W}_{4}\mathbf{h}_{i}^{s_ {i}(k)}\right)^{\top}\left(\mathbf{W}_{5}\tilde{\mathbf{h}}^{(k-1)}\right)}{ \sqrt{d}}\right). \tag{5}\] Note that \(\mathbf{W}_{4}\),\(\mathbf{W}_{5}\in\mathbb{R}^{d\times d}\) are trainable parameters. ### _Session Representation Learning_ Given a session \(S\), although the embedding of the virtual node \(\tilde{v}\) contains the information of all the items in \(S\), it omits the temporal information and cannot be simply taken as the representation of the session. In the previous section, for each item \(v_{i}\), we have computed its general embedding \(\mathbf{h}_{i}\) and personalized embedding \(\mathbf{h}_{i}^{s}\) w.r.t. a session \(S\), respectively. For notation brevity, we overload the embedding of item \(v_{i}\) as \(\mathbf{h}_{i}\) and next show how to calculate session representations based on item representations. To leverage item sequence in a session, in addition to item embeddings, we further incorporate the positional information of items and the length of the session. For all the sessions, we use a shared position embedding look-up table \(\mathbf{P}\), where the \(r\)-th row \(\mathbf{p}_{r}\in\mathbb{R}^{d}\) represents the embedding vector for the \((t-r)\)-th reverse position in a session of length \(t\). Note that we choose a reverse order for positions because the most recent items could be more useful for the prediction of the next item in the session. We also introduce a shared session length embedding look-up table \(\mathbf{L}\), where the \(t\)-th row \(\mathbf{l}_{t}\in\mathbb{R}^{d}\) corresponding to the embedding for the length \(t\) of a session. Note that we limit the maximum length of a session to be \(t_{max}\). After that, for the \(i\)-th item in a session of length \(t\), we unify both the information of item position and session length into the item embedding \(\mathbf{h}_{i}\), and output an updated embedding \(\mathbf{z}_{i}\) for \(v_{i}\): \[\mathbf{z}_{i}=\mathbf{h}_{i}+\mathbf{p}_{t-i}+\mathbf{l}_{t}. \tag{6}\] To calculate the representation of a session, we can also employ item categories in the session. For all the items, we further define a shared item category embedding look-up table, where each row indicates an embedding vector of an item category. Given a session \(S\) of length \(t\), we unify item categories in the session as: \[\mathbf{h}_{c}=\texttt{Mean}(\{\mathbf{h}_{i}^{c}\}_{i=1}^{t},\forall v_{i} \in\mathcal{S}), \tag{7}\] where \(\mathbf{h}_{i}^{c}\) represents the category embedding of the item \(v_{i}\). Then we use the attention mechanism to fuse the information of all the items in \(S\), and have: \[\bar{\mathbf{z}}_{s}=\sum_{i=1}^{t}\gamma_{i}\mathbf{z}_{i}, \tag{8}\] where the attention weight \(\gamma_{i}\) can be calculated by a two-layer MLP: \[\gamma_{i}=\texttt{MLP}(\mathbf{z}_{i}\,\|\,\mathbf{z}_{t}\,\|\,\tilde{ \mathbf{h}}\,\|\,\mathbf{h}_{c}) \tag{9}\] Here, \(\tilde{\mathbf{h}}\) is the embedding of the virtual node \(\tilde{v}\) in Equation 4. we also use the embedding \(\mathbf{z}_{t}\) of the last item in \(S\) because it could be highly related to the prediction of the next item. After that, we combine \(\bar{\mathbf{z}}_{s}\) and \(\mathbf{z}_{t}\) to capture user interests in session \(S\): \[\mathbf{z}_{s}=\mathbf{W}_{6}\left[\bar{\mathbf{z}}_{s}\|\mathbf{z}_{t}\right], \tag{10}\] where \(\mathbf{W}_{6}\) is a weight parameter. Further, inspired by the skip connection technique in [27], we directly derive embedding of item \(v_{i}\) from the look-up table and rerun Equations 6-10 to generate a new \(\mathbf{z}_{s}\) (we denote it as \(\mathbf{z}_{s}^{\prime}\) for difference) without the item representation learning stage in Section IV-B. Finally, the representation of session \(S\) is computed by: \[\mathbf{h}_{s}=\mathbf{z}_{s}+\mathbf{z}_{s}^{\prime}. \tag{11}\] ### _Label Collaboration_ Most existing works [8, 9, 10, 11, 12] use the one-hot encoded vector of the target item as the hard label of user preference, which may not reflect the true preference. The intuition is that users are generally only exposed to a limited number of items, so the lack of other items could induce a bias to user interest. Further, user preference is also influenced by different time periods and contextual scenarios, which can deviate from historical data over time. Therefore, to address the problem, we employ the session-level contexts and propose a label collaboration strategy, which aims to explicitly utilize the target items of historical sessions with most similar behavioral patterns to the current session as collaborative label information. **Collaborative Sessions Retrieval.** Given a session \(S\), our target is to first retrieve \(K\) sessions that are most similar to \(S\) from a fixed-size candidate session pool with \(M\) most recent sessions. Intuitively, the more sessions we retrieve, the more accurate the user preference could be estimated, and the larger computation cost will be induced. Therefore, we further utilize _SimHash_[1] to speed up the model efficiency. The SimHash function takes the session representation as input and generates its binary fingerprint, where each entry is either 0 or 1. It has been pointed out in [2] that the outputs of SimHash satisfy the _locality-sensitive properties_ that the outputs are similar if the input vectors are similar to each other. Specifically, we first project embeddings of \(S\) and other candidate sessions into binary fingerprints by multiplying the input embedding vectors with a hash function, which is set to be a fixed random projection matrix \(H\in\mathbb{R}^{d\times m}\), where \(m<d\). As a result, similar session embedding vectors can get the same hashing output. After that, we calculate the _hamming distance_ between the output vectors and select the top-\(K\) most similar sessions to \(S\) from \(M\) candidate sessions by: \[N_{S},W_{S}=\texttt{topK}(-\texttt{HammingDistance}\left(\mathbf{e},\hat{ \mathbf{e}}\right)),\] where \(\mathbf{e}=\texttt{SimHash}(S)\), \(\hat{\mathbf{e}}=\texttt{SimHash}(\hat{S})\), and \(\hat{S}\) is derived from \(M\) candidate sessions. The weights \(W_{S}\) are then normalized to ensure that they sum to 1. We denote the set of one-hot encoded labels of selected sessions as \(N_{S}=\left\{\mathbf{y}_{1}^{S},\mathbf{y}_{2}^{S},\ldots,\mathbf{y}_{K}^{S}\right\}\) and the set of corresponding weights as \(W_{S}=\left\{w_{1}^{s},w_{2}^{S},\ldots,w_{K}^{S}\right\}\), which will be used for label collaboration of session \(S\). Further, the pool is updated by a slide window scheme: removing the oldest sessions and adding the most recent ones in the next batch. Therefore, compared to the time complexity \(\mathcal{O}\left(MBd\right)\) of retrieval by cosine similarity in [9], the time complexity of our retrieval is \(\mathcal{O}\left(Bm\right)\), where \(B\) is the batch size, \(M\) is the pool size and \(m\) is smaller than session representation dimensionality \(d\). **Collaborative Label Generation.** After \(K\) most similar sessions are retrieved, we next construct the soft label for session \(S\). These \(K\) sessions can help provide more comprehensive estimation for user interests than using \(S\) only. Therefore, we obtain the collaborative label for \(S\) by a weighted sum of the one-hot encoded label of each retrieved session: \[\tilde{\mathbf{y}}=\sum_{i=1}^{K}w_{i}^{S}\mathbf{y}_{i}^{S}. \tag{12}\] ### _Prediction Layer_ The prediction layer is used to output the probability distribution of items that the user will interact at the next timestamp in the current session. Due to the long-tail distribution problem [24] in the data for recommendation, we normalize item embeddings and session embeddings in each layer. Finally, we feed them into a prediction layer, where the inner product and the Softmax function are applied to generate the output: \[\hat{\mathbf{y}}_{i}=\texttt{Softmax}(\mathbf{h}_{s}^{\top}\mathbf{h}_{i}), \tag{13}\] where \(\hat{\mathbf{y}}_{i}\) denotes the probability of interacting with item \(v_{i}\) in the next timestamp. The total loss function consists of two components: a cross-entropy loss based on the hard label \(\mathbf{y}\) and a KL-divergence loss based on the soft label \(\tilde{\mathbf{y}}\): \[\mathcal{L}=\text{CrossEntropy}(\hat{\mathbf{y}},\mathbf{y})+\lambda\text{KLD} (\hat{\mathbf{y}},\tilde{\mathbf{y}}), \tag{14}\] where \(\lambda\) is a trade-off parameter that is used to control the importance of the two components. ## V Experiments In this section, we conduct extensive experiments on three publicly available datasets to show the effectiveness of our method. We preprocess these datasets as in [8]. First, we arrange all the sessions in the chronological order and split the data into training data and test data by the timestamps of sessions. Second, we filter out items that appear less than 5 times or only appear in the test set, and also the sessions of length one. Third, we perform data augmentation with a temporal-window shifting to generate more data samples in a session, e.g., \(\left(\left[v_{1},v_{2},\ldots,v_{n-1}\right],v_{n}\right),\ldots,\left(\left[v _{1},v_{2}\right],v_{3}\right),\left(\left[v_{1}\right],v_{2}\right)\) for session \(\left[v_{1},v_{2},\ldots,v_{n}\right]\). Further, we adopt two widely used evaluation metrics in information retrieval: _Precision (P@20)_ and _Mean Reciprocal Rank (MRR@20)_ for evaluating the performance. ### _Datasets_ The following datasets are utilized to evaluate our model. The statistics of the processed datasets are shown in Table I. \(\bullet\)**Diginetica1** contains anonymous user transaction information extracted from e-commerce search engine logs for five months. The dataset is from CIKM Cup 2016. Footnote 1: [http://cikm2016.cs.iupu.edu/cikm-cup](http://cikm2016.cs.iupu.edu/cikm-cup) \(\bullet\)**Tmall2** records the anonymized users' shopping logs on the online shopping platform called Tmall. The dataset comes from the IJCAI15 competition. Footnote 2: [https://tianchi.aliyun.com/dataset/dataDetail?dataId=42](https://tianchi.aliyun.com/dataset/dataDetail?dataId=42) Footnote 3: [http://2015.recsymboleng.com/challenge](http://2015.recsymboleng.com/challenge) \(\bullet\)**Yoochoose1_643** was built by YOOCHOOSE GmbH to support RecSys Challenge 2015. It records users' clicks from an e-commerce website. We follow Wu [8] by using the most recent proportion \(1/64\) of the training sessions. Footnote 3: [http://2015.recsymboleng.com/challenge](http://2015.recsymboleng.com/challenge) ### _Hyper-parameter Setup_ Following [8, 12], the dimension of the latent vectors is fixed to 256, and the batch size is set to 100. We use the Adam optimizer with the initial learning rate of 0.001, which will decay by 0.8 after every 3 epochs. The \(l_{2}\) penalty is set to \begin{table} \begin{tabular}{c|c|c|c} \hline \hline Dataset & Diginetica & Tmall & Yoochoose1\_64 \\ \hline \#Train sessions & \(719,470\) & \(351,268\) & \(369,859\) \\ \#Test sessions & \(60,858\) & \(25,898\) & \(55,898\) \\ \#Items & \(43,097\) & \(40,728\) & \(16,766\) \\ Avg. lengths & \(5.12\) & \(6.69\) & \(6.16\) \\ \hline \hline \end{tabular} \end{table} Table I: datasets statstics \(10^{-5}\) and the dimension of the hash matrix in SimHash is set to 64. The candidate number of sessions is set to 1500 in the label collaboration strategy. We set the parameter \(\lambda\) for adjusting the loss weights to 0.1 for Deginetica 5 for Yoochoose1_64, and 10 for Tmall. We vary the number of retrieved target items in label collaboration from \(\{10,30,50,70,90\}\) and the number of frequent contextual relations from \(\{0,5,10,20,30\}\) to study their effects. ### _Baselines_ To verify the performance of our proposed model, we compared our model with 17 other methods, which can be grouped into three categories. Readers are referred to Section II for more details. **(Single Session methods): POP** recommends the most popular items. **Item-KNN**[3] recommends items based on the cosine similarity between items in the current session and candidate items. **FPMC**[4] uses both Markov chain and Matrix Factorization to consider the user's personalized and general information. **GRU4REC**[7] exploits the memory of GRUs by characterizing the entire sequence. **NARM**[5] and **STAMP**[6] further utilize attention mechanism additionally, which aims to capture the current interest and general interest of the user. **SRGNN**[8], **LESSER**[14], **SGNN-HN**[12], convert each session into a graph and do not utilize cross-session information. **(Cross Session methods): CSRM**[9] incorporates the relevant information in the neighborhood sessions through the memory network. **CoSAN**[10] utilizes multi-head attention mechanism to build dynamic item representations by fusing item representations in collaborative sessions. **GCE-GNN**[11] and **MTD**[32] simultaneously focus on cross-session and intra-session dependencies. **COTREC**[37] and \(S^{2}\)**-DHCN**[38] employ a global argumentation view of items to mine informative self-supervision signals. **(Multi-relation methods): AutoGSR**[16] and **MGIR**[35] both learn multi-faceted item relations to enhance session representation. Note that MGIR utilizes cross-session information while AutoGSR does not. ### _Overall performance_ From the experimental results on the three datasets in Table II, we have the following observations: (1) It is observed that methods utilizing RNNs or attention mechanisms perform better than early methods such as Item-KNN and FPMC because they are both suitable for dealing with sequential data with temporal information without losing the interal-session-level context. Methods such as CSRM and CoSAN offer higher performance for introducing auxiliary information from historical sessions than single session methods like GRU4Rec, NARM and STAMP. This confirms the effectiveness of leveraging external-session-level contexts. The current best-performing methods such as SGNN-HN, COTREC and MGIR are GNN-based approaches because GNNs are good at capturing complex item-transitions across sessions, which shows the effectiveness of introducing cross-session item-level context by graph modeling. (2) CARES outperforms other GNN-based models SRGNN, LESSER, AotoGSR, and SGNN-HN. This is because all these methods are designed for local sessions without considering cross-session information in the global view. While the cross-session method COTREC leverages self-supervision for enhancing session representation, it ignores heterogeneity and is outperformed by CARES. (3) The leading performance of CARES and COTREC over GCE-GNN implies that it is useful to capture the internal-session-level context in the global graph because the latter only considers the cross-session item-level context of item-transitions and lacks diversity in its collaborative information. Therefore, COTREC employs self-supervised learning to impose a divergence constraint on global view and internal-session view of item embedding, while CARES further introduces personalized item representation w.r.t sessions. This demonstrates the significance of the internal-session-level context in global graph modeling. (4) Our approach achieves the best performance in all the datasets, which shows the importance of making full use of contexts in sessions. Further, our model has a significant improvement in terms of MRR@20 on Diginetica and Yoochoose1_64, indicating that the item relevant to users' interests can be ranked higher, which is critical for user experience improvement and confirms the superiority of our model. (5) To ensure a fair comparison, we conducted experiments with an additional variant model that does not use side information to construct the graph. As shown in Table II, even without utilizing the side information of the item's category (aka CARES_ns), our method still performs well across different datasets. ### _Ablation Study_ We conduct an ablation study on CARES to understand the characteristics of its main components. One variant updates items' embeddings by directly capturing information from intra-session without utilizing general information to model item-transition relationships on the global graph. This helps us understand the importance of including cross-session item-level context in SBR. We call this variant **CARES_ng** (**no g**eneral information). Another variant learns items' embedding without personalized information w.r.t sessions. We call this variant **CARES_np** (**no** personalized information), which helps us evaluate the effectiveness of internal-session-level context. To show the importance of the label collaboration strategy, we train the model with cross-entropy loss only and call this variant **CARES_nl** (**no** label collaboration). **CARES_ns** (**no** side information) represents the variant of CARES without considering category information of items to understand the effect of items' category association in SBR. From the experimental results in Figure 4, the following observations are made. (i) Compared with **CARES_ng**, CARES leverages cross-session item-level context and thus can utilize diverse collaborative information from the global graph and outperform **CARES_ng**. (ii) It can also be observed that CARES with learning personalized information beats **CARES_np** on all the datasets. This indicates that internal-session-level context can effectively preserve user intent through adding personalized information w.r.t sessions. (iii) CARES performs better than **CARES_nl**, and this indicates that utilizing the target items of historical sessions with similar behavioral patterns to the current session as external-session-level context can mitigate the bias in the user preference distribution. (iv) CARES also defeats **CARES_ns**, indicating that items' category plays an important role in learning users' preferences. Additionally, although side information improves recommendation accuracy, our model still performs well without it, as shown in Table II. ### _Influence of Contextual Relations_ In this section, we study how contextual relations affect the performance of the proposed method. Due to the limited space, we only show the results in terms of MRR@20. The results are shown in Figure 5. From the results, we can see that the models that do not use contextual relations always have lower performance. This is because contextual relations can help the model capture more complex item context, which indicates disentangling the relation semantics of sessions is a promising direction for further exploiting the information across sessions. For different datasets, the optimal number of contextual relations is different. For the dataset Yoochoose1_64, the score hits the highest when the relation number is set to 30. For the other two datasets, the optimal relation number is 5 and we can see that increasing the number of relations does not always result in a better performance. This is because only the relation between items' categories with enough high frequency can be considered a context. ### _Sensitivity Analysis of Hyper-Parameters_ We end this section with a sensitivity analysis on the hyper-parameters of CARES. In particular, we study two hyper-parameters: the hash matrix dimension \(m\) and the number of retrieved sessions \(K\). In our experiments, we vary one parameter each time with others fixed. Fig 6 illustrates the results with w.r.t. P@20 and MRR@20 scores on the datasets of Tmall and Yoochoose1_64. (Results on other datasets scores exhibit similar trends, and thus are omitted for space reasons.) From the figure, we see that (1) A larger dimension \(m\) can slightly improve the performance of the model. Since the model is not very sensitive to the hash matrix dimension, setting a small size of \(m\) can also guarantee the performance of the model. (2) Fewer retrieved sessions in label collaboration are not sufficient to provide enough information for the current session. And there is also a performance drop when retrieving more sessions, which shows that a large number of collaborative sessions could contain noise that adversely affects the recommendation performance. So, an appropriate number of retrieved sessions \(K\) is essential. ## VI Conclusion In this paper, we propose a novel method named CARES for session-based recommendation based on graph neural network. Specifically, it converts the session sequences into a global graph with item attributes as context. The general item representations are generated by various contextual relations through item-level attention. After that, we apply a gating mechanism to further enrich the representations of items with personalized information w.r.t sessions. Then the intra- and cross-session context information are subsequently combined to enhance the recommendation performance. Finally, it incorporates label collaboration to generate soft user preference \begin{table} \begin{tabular}{c c c c c c c} \hline \hline & \multicolumn{2}{c}{Diginetica} & \multicolumn{2}{c}{Tmall} & \multicolumn{2}{c}{Yoochoose1\_64} \\ \cline{2-7} Method & P@20 & MRR@20 & P@20 & MRR@20 & P@20 & MRR@20 \\ \hline POP & 1.18 & 0.28 & 2.00 & 0.90 & 6.71 & 0.58 \\ Item-KNN & 35.75 & 11.57 & 9.15 & 3.31 & 51.60 & 21.81 \\ FPMC & 22.14 & 6.66 & 16.06 & 7.32 & 45.62 & 15.01 \\ GRU4Rec & 30.79 & 8.22 & 10.93 & 5.89 & 60.64 & 22.89 \\ NARM & 48.32 & 16.00 & 23.30 & 10.70 & 68.32 & 28.63 \\ STAMP & 46.62 & 15.13 & 26.47 & 13.36 & 68.74 & 29.67 \\ SR-GNN & 50.73 & 17.59 & 27.57 & 13.72 & 70.57 & 30.94 \\ LESSR & 51.71 & 18.15 & 23.53 & 9.56 & 70.05 & 30.59 \\ SGNN-HN & 55.67 & 19.45 & – & – & 72.06 & 32.61 \\ \hline CSRM & 48.49 & 17.13 & 29.46 & 13.96 & – & – \\ CoSAN & 51.97 & 17.92 & 32.68 & 14.09 & – & – \\ GCE-GNN & 54.22 & 19.04 & 33.42 & 15.42 & 70.91 & 30.63 \\ \(S^{2}\)-DHCN & 53.18 & 18.44 & 31.42 & 15.05 & – & – \\ MTD & 51.82 & 17.26 & 29.12 & 13.73 & 71.88 & 31.32 \\ COTREC & 54.18 & 19.07 & 36.35 & 18.04 & – & – \\ \hline AutoGR & 54.56 & 19.20 & 33.71 & 15.87 & 71.77 & 31.02 \\ MGIR & – & – & 36.41 & 17.42 & – & – \\ \hline CARES\_ns & \(55.29\) & 21.04 & 38.17 & 17.79 & 71.82 & 33.05 \\ CARES & \(\mathbf{56.49}\) & \(\mathbf{23.22}\) & \(\mathbf{38.77}\) & \(\mathbf{18.37}\) & \(\mathbf{72.21}\) & \(\mathbf{34.40}\) \\ Improv. & \(1.47\%\) & 19.30\% & 6.48\% & 1.82\% & 0.20\% & \(5.48\%\) \\ \hline \hline \end{tabular} \end{table} Table II: Overall performance comparison on three datasets. For fairness, we directly report the results of baseline methods from their original papers, where “-” indicates the absence of corresponding results in the original papers. distribution as labels and thus empowers the proposed model to alleviate the overfitting problem. Comprehensive experiments demonstrate that our proposed model can make full use of contexts in sessions, especially those cross-session ones, thus achieving state-of-the-art performance over three real-world datasets consistently.
2304.04896
Neural Network Predicts Ion Concentration Profiles under Nanoconfinement
Modeling the ion concentration profile in nanochannel plays an important role in understanding the electrical double layer and electroosmotic flow. Due to the non-negligible surface interaction and the effect of discrete solvent molecules, molecular dynamics (MD) simulation is often used as an essential tool to study the behavior of ions under nanoconfinement. Despite the accuracy of MD simulation in modeling nanoconfinement systems, it is computationally expensive. In this work, we propose neural network to predict ion concentration profiles in nanochannels with different configurations, including channel widths, ion molarity, and ion types. By modeling the ion concentration profile as a probability distribution, our neural network can serve as a much faster surrogate model for MD simulation with high accuracy. We further demonstrate the superior prediction accuracy of neural network over XGBoost. Lastly, we demonstrated that neural network is flexible in predicting ion concentration profiles with different bin sizes. Overall, our deep learning model is a fast, flexible, and accurate surrogate model to predict ion concentration profiles in nanoconfinement.
Zhonglin Cao, Yuyang Wang, Cooper Lorsung, Amir Barati Farimani
2023-04-10T23:51:11Z
http://arxiv.org/abs/2304.04896v1
# Neural Network Predicts Ion Concentration Profiles under Nanoconfinement ###### Abstract Modeling the ion concentration profile in nanochannel plays an important role in understanding the electrical double layer and electroosmotic flow. Due to the non-negligible surface interaction and the effect of discrete solvent molecules, molecular dynamics (MD) simulation is often used as an essential tool to study the behavior of ions under nanoconfinement. Despite the accuracy of MD simulation in modeling nanoconfinement systems, it is computationally expensive. In this work, we propose neural network to predict ion concentration profiles in nanochannels with different configurations, including channel widths, ion molarity, and ion types. By modeling the ion concentration profile as a probability distribution, our neural network can serve as a much faster surrogate model for MD simulation with high accuracy. We further demonstrate the superior prediction accuracy of neural network over XGBoost. Lastly, we demonstrated that neural network is flexible in predicting ion concentration profiles with different bin sizes. Overall, our deep learning model is a fast, flexible, and accurate surrogate model to predict ion concentration profiles in nanoconfinement. ## I Introduction Nanoconfinement defines a state when fluid is confined in nanoscale spaces such as nanotube and nanochannel [1]. Compared with bulk condition, nanoconfined fluid such as water exhibit anomalous viscosity [2; 3], diffusion coefficient [4; 5; 6], phase [7; 8], dynamics [9], and density [10; 11; 4]. These behaviors become more exotic once we add ions to water. When ionic solution is confined by charged nanochannel walls, electrical double layer (EDL) is formed by the ions at the solid-liquid interface [12; 13]. EDL is the basis for the development of advanced energy storage devices such as capacitors and batteries [14]. EDL can be engineered by surface modification to achieve the maximum charge storage capacity. Ions in EDL move with the solvent molecules when external electrical field is applied, resulting in electro-osmotic flow in the nanochannel [15]. Electro-osmotic flow is a widely-used fluidic transport mechanism as it is easily controllable and scalable [15; 16]. Moreover, nanoconfinement of the ionic solution is highly associated with the design and engineering of water treatment and transport systems [17; 18; 19]. By forcing the ionic solution through nanoconfined space, ions can be filtered out when fresh water is produced [20; 21]. Ion concentration distribution in nanoconfined space and EDL is related to the performance and efficiency of the water treatment device or plants [17; 22; 23; 24]. Given the connection between nanoconfined ionic solution and various aforementioned applications, understanding the ion concentration distribution in nanospace is essential for the future development of energy storage, nanofluidic device, and water treatment technologies. Classical continuum models such as Poisson-Boltzmann equation have underwhelming accuracy in predicting ion concentration distribution under nanoconfinement [25; 26] because nanoscale physical properties such as the effect of discrete solvent molecules and surface-ion interactions are not incorporated in those models [15]. In the past two decades, molecular dynamics (MD) simulation has been the major tool for studying the ionic solutions in nanoconfinement as it models the physical interactions at molecular scale. MD simulation has significantly improved prediction accuracy on many properties of nanoconfined ionic solution such as ion and solvent concentration profile [27; 28; 29; 30; 13], ion transport and velocity [31; 32], and charge inversion [12; 15] over continuum models. Despite its high accuracy, MD simulation has the disadvantage of being computationally expensive and resource-demanding. Additionally, to study the ionic distribution in nanochannel, a unique molecular system needs to be created and simulated for each combination of channel width and ion concentration. The trajectories from MD simulation have to be stored (occupying disk storage) and post-processed for the calculation of the desired properties. Therefore, building a surrogate model that makes instantaneous inference on specific physical properties of the ionic solution under different nanoconfinement configurations is of great value. Machine learning and deep learning methods have seen astonishing development in the past decade due to the exponential growth in computational resources and data repositories. They are proven competent in modeling physical phenomena. For example, machine learning is used in identifying and modeling fluid mechanics [33] and dynamical systems [34; 35; 36], and solving mathematical problems [37]. In the field of nanofluidics, graph neural network has been used to accelerate MD simulation [38] and identify the phase of water [39], while convolutional neural network is used for predicting nanoconfined water density profile [40; 41; 42] and self-diffusion [43] of Lennard-Jones fluids. In this work, we propose to use neural network (NN) as a surrogate model for the fast prediction of ion concentration profiles in nanochannels. There are several challenges in developing a surrogate NN model for this problem. Firstly, the ion concentration profile has a high-dimensional correlation with many properties of the nanochannel including the channel width, ion molarity, and ion type. Also, the shape of the ion concentration profile varies based on the bin size during data sampling. With those challenges, training an NN for end-to-end prediction of the entire concentration profile can be difficult and inflexible. To solve these issues, we treat the ion concentration profile in nanochannel as a probability distribution with respect to ion coordinates (details in the Method section) conditioned on nanochannel properties. We then train the NN as a parameterized approximator of the conditional cumulative density distribution of the ions in the nanochannel. Such a method is inspired by the fact that NNs are universal function approximators [44; 45], and it has achieved success in learning probability and cumulative distributions [46; 47; 48; 49]. NN trained in this manner learns a continuous distribution of ions in the nanochannel, which enables it to predict ion concentration profiles with arbitrary bin sizes. Results show that the NN can serve as a much faster surrogate model of MD simulation to accurately predict ion concentration profiles in nanochannels. ## II Method The framework of this work (Fig. 1) consists of three sections. Firstly, we perform molecular dynamics (MD) simulations of different ion-nanochannel systems. Secondly, data points are sampled based on the cumulative density function of ions in nanochannel to form a training dataset and an interpolation test dataset. Lastly, different machine learning models including NN are trained and further evaluated for their accuracy in predicting the ion concentration profile. ### Molecular dynamics simulation The initial configurations of the ion-nanochannel systems are created using VMD [50] and GROMACS [51]. Each system (Fig. 1a) contains a water box with ions sandwiched by two layers of graphene, which serve as the nanochannel walls. All systems have dimensions of 3.19 and 3.40 nm in the \(x\) and \(y\) direction, respectively. There are 832 carbon atoms in the simulation system. The surface-to-surface distance between the two graphene layers is the channel width denoted as \(w\), ranging from 0.8 to 3.0 nm with the spacing of 0.1 nm (\(w\in\{0.8,0.9,\cdots,3.0\}\), 23 variations). The number of water molecules in the nanochannel size of \(3.19\times 3.40\times w\) is controlled such that the water density is at 1 g/cm\({}^{-3}\). Ions of different molarity, \(c\), are added to the system, where \(c\) ranges from 0.8 to 3.6 M changing by 0.2 M (\(c\in\{0.8,1.0,\cdots,3.6\}\), 15 variations). Five types of ions are simulated including Na\({}^{+}\), Cl\({}^{-}\), K\({}^{+}\), Li\({}^{+}\), and Mg\({}^{2+}\). Each simulation system contains only one type of ion. To maintain charge neutrality, the same amount of opposite charges are evenly distributed to each carbon atom in the system, balancing the charge carried by the ions. In total, 1,725 simulations are run. MD simulations are carried out using the LAMMPS [54] software. SPC/E [55] water model is used to simulate water molecules. The interatomic potentials consist of the Lennard-Jones (LJ) potentials and long-range Coulombic interaction, both with a cutoff distance of 10 A. The LJ potentials (Table 1) of ions and graphene are adopted from the ref [53; 56; 52] and ref [4], respectively. Other interatomic potentials are calculated by the arithmetic rule. Nose-Hoover thermostat [57; 58] is used to maintain the temperature of the simulation system at 300 K. In each simulation, the system is firstly run under canonical (NVT) ensemble for 1 ns for the ions to reach equilibration positions. With the ensemble remains unchanged, the simulation is then run for another 1 ns while the trajectories are recorded every 5 ps. Periodic boundary condition is applied to all three dimensions. Post-processing of MD trajectories is conducted using the MDTraj [59] package. ### Ion concentration profile as probability distribution In this work, the ion concentration profile is regarded as the linear transformation of a conditional probability distribution (Fig. 1b). Namely, the ion concentration is the conditional probability multiplied with molar concentration. When the material of nanochannel wall and the solvent molecule remains unchanged (graphene and water in our case), the probability of the \(z\)-coordinate of a nanoconfined ion is at \(r\) nm away from the channel center follows the conditional probability density function (PDF): \[P(|z-o|=r\mid\sigma,\epsilon,w,c,q), \tag{1}\] where \(o\) is the \(z\)-coordinate of nanochannel center, \(\sigma\) and \(\epsilon\) are the LJ potentials of the ion, \(w\) is the nanochannel width, \(c\) is the molarity of ion in channel, and \(q\) is the charge of the ion. If we denote the set including all conditions as \(W=\{\sigma,\epsilon,w,c,q\}\), we get the conditional cumulative density function (CDF) as: \[F(|z-o|=r\mid W)=P(|z-o|\leq r\mid W)=\frac{N_{|z-o|\leq r}}{N_{\text{total}}}, \tag{2}\] where \(N_{|z-o|\leq r}\) is the number of ions having \(z\)-coordinate within \(r\) nm from the nanochannel center, and \(N_{\text{total}}\) is the total number of ions in the system. If the conditional CDF is known, then the ion concentration in any interval \(r_{1}<|z-o|\leq r_{2}\) can be obtained simply by first calculating the conditional PDF: \[P(r_{1}<|z-o|\leq r_{2}\mid W)=\\ F(|z-o|=r_{2}\mid W)-F(|z-o|=r_{1}\mid W) \tag{3}\] and then multiplying it by the molar concentration. Since acquiring true conditional CDF shown by Eq.2 is challenging, we propose to use a neural network parameterized by \(\theta\), denoted as \(F_{\theta}(\cdot)\), to approximate it: \[F_{\theta}(|z-o|=r\mid W)\approx F(|z-o|=r\mid W). \tag{4}\] \begin{table} \begin{tabular}{l l l l l l l} & Na\({}^{52}\) & Cl\({}^{52}\) & Mg\({}^{53}\) & Li\({}^{52}\) & K\({}^{52}\) & C\({}^{4}\) \\ \hline \(\sigma\) (Å) & 2.1600 & 4.8305 & 2.1200 & 1.4094 & 2.8384 & 3.3900 \\ \(\epsilon\) (kcal/mol) & 0.3526 & 0.0128 & 0.8750 & 0.3367 & 0.4297 & 0.0692 \\ \(q\) (e) & +1 & -1 & +2 & +1 & +1 & - \\ \end{tabular} \end{table} Table 1: The Lennard-Jones potentials and the charge of ions simulated in this work. Enough training data points should be sampled based on the true conditional CDF to ensure the expressivity of the neural network [60, 61]. In practice, we sample 2,000 data points using Eq.2 from each simulation (Fig. 1b). Among the 2,000 data points, half of them is sampled with uniformly chosen \(r\in\{0,\frac{w}{2}+0.1\}\) nm, which ensures the model learns that no ion should be present outside of the nanochannel. The other half is sampled with uniformly chosen \(r\in\{\max(0,\frac{w}{2}-0.5),\frac{w}{2}\}\) nm. Such a choice of interval includes more data points within 5 A of the nanochannel wall, thus helping the model to better learn the interfacial ion distribution. 3,450,000 data points are sampled in total from the 1,725 simulations. Each data point has features as \(\{r,\sigma,\epsilon,w,c,q\}\) and labels as the conditional cumulative density \(F(r\mid\sigma,\epsilon,w,c,q)\). Data points sampled from simulations with channel width \(w\in\{1.6,2.4,2.8\}\) nm or with molarity \(c\in\{1.4,2.2,3.0\}\) M are deposited into the test set, while the other ones into the training set. Overall, the training set contains 2,400,000 data points and the test set contains 1,050,000 data points. ### Machine learning models and training In our work, we use NN to model the conditional CDF, \(F(|z-o|=r\mid W)\). Each sample \(i\) in \(N\) training data is denoted as \(\{r_{i},W_{i},F_{i}\}\) representing the descriptor \(W_{i}\) and its corresponding density function value \(F_{i}\) at position \(r_{i}\). The input to the machine learning models is thus a six-dimensional list \(\{r_{i},W_{i}\}=\{r_{i},\sigma_{i},\epsilon_{i},w_{i},c_{i},q_{i}\}\), which describes the conditions and position to predict (Fig. 1). The output is \(\hat{F_{i}}\) which approximates the ground truth CDF \(F_{i}\). An NN is developed as a surrogate model for ion concentration profile prediction. NN is based on fully-connected layers [62, 63] and each layer is given: \[y=a(W^{(l)}x), \tag{5}\] where \(x\) and \(y\) are the input and output for each layer respectively, \(W^{(l)}\) is the weight matrix at \(l\)-th layer, and \(a\) is the element-wise nonlinear activation function. In our case, we used ReLU [64] function for \(a\) in all hidden layers and apply sigmoid in the output layer to guarantee the predicted Figure 1: Framework of predicting ion profiles in nanochannels via NN. **(a)** Data is generated by running MD simulation of nanoconfined ionic solution. Channel width, \(w\), is the surface-to-surface distance between the two charged graphene walls (colored teal). In the shown system, the ions are Na\({}^{+}\) (colored green) with molarity of 2 M and \(w\) is 2 nm. **(b)** shows the probability and cumulative density of ion distribution in the nanochannel. \(r\) is the distance from the \(z\)-direction center of the nanochannel. It is noticeable that the ion concentration distribution shown by the inset is just a linear transformation of the probability distribution. Data points are sampled from the cumulative density and used for the training of NN. **(c)** The NN model takes 6 inputs and predicts the cumulative density of ion within \(r\) nm of the channel center. The predicted cumulative density is then translated to ion concentration profile. cumulative density value is between 0 and 1. By stacking multiple fully-connected layers, NN can work as a universal function approximator [65] which is expected to accurately predict the conditional ion profiles. The objective of the NN is to minimize the MSE between the predictions \(\{\tilde{F}_{i}\}_{i\in N}\) and the ground truth \(\{F_{i}\}_{i\in N}\). The NN is implemented with five hidden layers and the number of units in each hidden layer is \(\{1024,512,256,128,32\}\). We train the NN using Adam optimizer [66] with a learning rate of 0.005 for 100 epochs. To demonstrate the superior performance of NN, we benchmarked the prediction of ion profiles using another machine learning model, extreme gradient boosting (XGBoost). XGBoost is a gradient-boosted decision tree (GBDT) machine learning method and has demonstrated superior and robust performance in many applications [67]. Unlike the NN, XGBoost is a non-parametric machine learning model without strong assumptions about the form of the mapping function from input to output. The model is based on decision trees which predict the labels via a series of if-then-else questions (levels) to the input features. An optimal decision tree estimates the minimum number of levels required to make a prediction during training. GBDT is an ensemble method for decision trees that combines multiple models to boost performance [68; 69]. Specifically, GDBT leverages the error residual of the previous decision tree to train the next and ensembles all the decision trees by a weighted summation of the outputs of the models. For a GBDT \(\tilde{F}_{M}\) with \(M\) decision trees, the ensembled result is given: \[\tilde{F}_{M}(z,W)=\sum_{m}^{M}\gamma_{m}T_{m}(r,W), \tag{6}\] where \(T_{m}\) denotes a single decision tree. And the weighted term \(\gamma_{m}\) is calculated by: \[\gamma_{m}=\operatorname*{arg\,min}_{\gamma}\sum_{i}^{N}\ell(F_{i},\tilde{F}_ {m-1}(r_{i},W_{i})+\gamma T_{m}(r_{i},W_{i})), \tag{7}\] where \(\ell\) is a mean square error (MSE) loss \(\ell(y,\tilde{y})=(y-\tilde{y})^{2}\) that measures the prediction accuracy. XGBoost is a scalable and distributed implementation of GDBT, which builds and trains decision trees in parallel. In our case, we set the level of decision trees as 15 and the \(L_{2}\) regularization coefficient as 5 to mitigate overfitting. Other hyperparameters follow the default settings in the XGBoost package [67]. ## III Result and Discussion ### Prediction of ion concentration profile To examine the performance of the NN and XGBoost models, we compare their predicted ion concentration profiles with the MD simulation results. Fig. 2 shows the ion concentration profile predicted using the three methods with different system configurations (combination of channel width and molarity), where the bin size is set as 0.05 nm. Plots enclosed by the red dashed lines have either channel width or molarity in the interpolation test set, while the other plots are results from the training set. For Na\({}^{+}\) (Fig. 2a), both models achieve close to perfect prediction for configurations in the training set. The location of the model-predicted concentration peaks fits perfectly with the MD simulation results. NN demonstrates more accurate interpolation capability than XGBoost as XGBoost has higher errors in predicting the peak concentration when molarity is 3 M. For Cl\({}^{-}\) (Fig. 2b), XGBoost shows a tendency of overpredicting the peak concentration when the molarity is Figure 2: The comparison between ion concentration profiles predicted by MD simulation, neural network, and XGBoost model when channel width ranges from 1 to 3 nm and molarity ranges from 1 to 3 M. **(a)** shows the results of Na\({}^{+}\) and **(b)** shows the results of Cl\({}^{-}\). Results enclosed by the red dashed lines are included in the interpolation test set, while the others are included in the training set. \(r\) represents the distance to the center of nanochannel. at 3 M. A single layer of Cl\({}^{-}\) occurs in the configuration [1 nm, 1 M], which is different from the other configurations where ion concentration peak occurs closer to the nanoconfinement wall. Both models accurately capture such a physical phenomenon. One small error made by NN is that it fails to predict the secondary concentration peak located at 0.5 nm from the channel center in the configuration [2 nm, 1 M]. In general, Fig. 2 demonstrates that NN is capable of accurately predicting the ion concentration profile by learning the CDF of ion in nanochannel, and NN interpolates better on unseen configurations compared with XGBoost. Another variable besides channel width and molarity is the ion type. Fig. 3 shows the comparison between model-predicted ion concentration profiles and MD simulation results for five different ions. The channel width is 2 nm, the molarity is 2.2 M, and the bin size is 0.05 nm for all subplots in Fig. 3. It can be observed that the location of peaks predicted by both NN and XGBoost is correct compared with MD results. For Na\({}^{+}\), XGBoost underpredicts the concentration of the primary peak while largely overpredicting the secondary peak. XGBoost also significantly underpredicts the concentration of the secondary peak of Mg\({}^{2+}\). Despite minor prediction error found on the secondary peaks of Cl\({}^{-}\) and K\({}^{+}\) profiles, NN is shown to be a more accurate model than XGBoost in this task. Ion concentration profiles of all configurations are available on the GitHub page of this work. Fig. 3 shows that NN bears the potential as a generalizable predictor of ion concentration profile regardless of the type and charge of the ions. ### Error analysis and inference time To thoroughly evaluate NN and XGBoost as a surrogate model to MD simulation, we benchmarked both models on their prediction accuracy and inference time. The mean absolute error (MAE) of Na\({}^{+}\) concentration profile prediction is the first metric of accuracy. Fig. 4a and 4b visualize the MAE heatmap of NN and XGBoost, respectively, for all simulated configurations. The MAE is calculated based on concentration profiles with bin size of 0.05 nm. The tick labels of the channel width and molarity included in the interpolation test set are colored red. Despite a slight increase of MAE when interpolating, NN achieves high prediction accuracy for all configurations. The highest MAE of NN is 0.53 M in the configuration [1.6 nm, 2.8 M]. On the other hand, the prediction accuracy of XGBoost suffers from overfitting. When interpolating Na\({}^{+}\) concentration profile for 1.6, 2.4, 3.0 nm channel width and 1.4, 2.2, 3.0 M molarity, MAE of XGBoost drastically increases. The highest MAE of XGBoost is 4.92 M, which occurs in the configuration [1.6 nm, 3.6 M]. The maximum value of the color bar of the heatmap is truncated at 0.6 M so that low MAE is more visible. Examples of XGBoost overfitting Na\({}^{+}\) and Cl\({}^{-}\) concentration profiles in configuration [1.6 nm, 2 M] are shown in Fig. 4c. For both Na\({}^{+}\) and Cl\({}^{-}\), the concentration peaks are mispredicted by XGBoost to be 0.05 nm away from the MD simulation results, leading to exceptionally high MAE. On the other hand, overfitting has a trivial effect on the prediction accuracy of NN. When channel width is 2.4 nm, no obvious MAE increase is shown in Fig. 4a. Two metrics, MAE and peak deviation are calculated to quantitatively evaluate the advantage of NN in interpolation (Table 2). MAE measures the prediction error of the whole ion concentration profile. Peak deviation measures how well the shape of the predicted ion concentration profile is aligned with the MD simulation result. The lower the value for each metric, the better the model is expected in interpolation. The interpolation MAE of NN is only 14.9% of that of XGBoost. Moreover, the interpolation peak deviation of NN is 0.0019 nm, which is only 6.1% of that of XGBoost. Both metrics \begin{table} \begin{tabular}{l l l l} & NN & XGBoost & MD \\ \hline Interp. MAE (M) & 0.1899 & 1.2764 & - \\ Interp. peak deviation (nm) & 0.0019 & 0.0314 & - \\ Inference time (s) & 0.80(0.10) & 2.56(0.11) & 11.72(0.42) \\ \end{tabular} \end{table} Table 2: Evaluation of the interpolation error and inference time of NN and XGBoost. All metrics are calculated given the bin size of 0.05 nm. Both MAE and peak deviation are averaged over all configurations in the interpolation set. Inference time measures the total time to generate ion concentration profiles for all 1,725 configurations (5 ions, 23 channel width, 15 molarity). The inference time of MD does not include the time used to load molecular trajectories. The inference time reported is averaged over 6 runs, with the standard deviation in parentheses. The lower value of each metric is the better model. Figure 3: Comparison between model predicted ion concentration profile and MD simulation results for five different ions. The channel width is 2 nm and molarity is 2.2 M, which is a configuration included in the interpolation test set. Bin size is set as 0.05 nm. prove that NN does not suffer from overfitting as XGBoost does, and is capable of accurately interpolating ion concentration profiles under different nanoconfinement conditions. Using machine learning as a fast surrogate model for MD simulation is the major motivation for this work. To evaluate the improvement in computation speed, we benchmark the inference time of NN, XGBoost, and MD simulation. Here, we define the inference time to be the total time taken to predict the ion concentration profiles of all 1,725 system configurations (5 ions, 23 channel widths, 15 molarities) with bin size as 0.05 nm. For MD simulation, we only consider the post-processing time of the molecular trajectories using MDTraj[39] and NumPy[70; 71]. The time of loading molecular trajectories is not included for a fair comparison. The benchmark is conducted with an Intel Core i7-8086K CPU for all models (Table 2). Averaged over 6 runs, NN can predict all 1,725 ion concentration profiles in 0.8 s, whereas XGBoost takes 2.56 s and processing MD trajectories takes 11.72 s. NN is approximately 3.2\(\times\) faster than XGBoost and 14.7\(\times\) faster than processing MD simulation trajectories. The inference time benchmark demonstrates that NN is a fast surrogate model for MD simulation. It is noteworthy that running a single MD simulation takes about 8 hours on average using 6 CPU cores, indicating that running all 1,725 simulations takes approximately 82,800 core-hours. If we compare the inference time of NN to the time required to run MD simulation, NN is orders of magnitude faster. Considering the size of NN model is 2.8 MB, which is much smaller than XGBoost model (71.1 MB) and MD simulation trajectories (32.1 GB), NN is also more storage-efficient than the other two. ### Sampling with different bin sizes One advantage of training a NN to learn the CDF instead of the whole ion concentration profile is the flexibility of sampling. By sampling on the CDF and converting probability to ion concentration, the NN can predict ion concentration profiles with arbitrary bin sizes. Fig. 5 shows the prediction of Na\({}^{+}\) concentration profile in the configuration [1.2 nm, 2.2 M] with bin size ranging from 0.01 to 0.1 nm. Both NN and XGBoost successfully model the shape of the profile regardless of Figure 4: Mean absolute error of **(a)** NN and **(b)** XGBoost predicted Na\({}^{+}\) concentration profile in all system configurations. MAE is calculated based on the profiles with bin size of 0.05 nm. The highest MAE of XGBoost in the dark red blocks is 4.92 M. The maximum value of the color bar is truncated such that the MAE of NN can be distinguished. The tick labels of channel width and molarity in the test set are colored red. **(c)** shows examples of failed interpolation of XGBoost for the configuration [1.6 nm, 2.2 M] due to overfitting. Figure 5: Predicted Na\({}^{+}\) concentration profile with bin size ranging from 0.01 to 0.1 nm. The shown configuration is [1.2 nm, 2.2 M], which is included in the interpolation set. the bin size: a primary peak near the confinement wall and a secondary peak at the channel center. When bin size is as fine as 0.01 nm, the concentration profile near the channel center is noisy because of less ion presence. Given the stochastic nature of MD simulation, which is used to generate the training data, the minor prediction error near the channel center with such a fine bin size is expected. The effect of stochasticity reduces as the bin size increases, resulting in more accurate predictions by NN and XGBoost. ## IV Conclusion In this work, we show the viability of using a neural network (NN) as a surrogate model for MD simulation in predicting the ion concentration profile in the nanochannel. We first model the ion concentration profile in nanochannel as a probability distribution conditioned on the configuration of nanochannel systems, such as LJ potentials of the ion, channel width, and molarity of ion. A NN is then trained to predict the conditional cumulative density probability (CDF) distribution of ions given the system configuration. The predicted CDF can be linearly transformed back to the concentration profile as the final output of the NN model. 1,725 MD simulations (5 types of ions, 23 variations of channel width, 15 variations of molarity) are run to generate training and test data for the NN model. We benchmark NN against another machine learning model, XGBoost, to compare their interpolation ability. The two metrics we used are the mean absolute error (MAE) of the whole interpolated ion concentration profile, and the peak deviation from the MD simulation concentration profile. On average, NN achieves 85.1% lower mean absolute error and 93.9% lower peak deviation when interpolating Na+ concentration profiles compared with the XGBoost model. Such a benchmark demonstrates the superior ability of NN to interpolate ion concentration profiles given unseen system configurations. Further, we record the inference time taken by the NN and XGBoost models and compared that to the time taken to post-process MD simulation trajectories. To predict 1,725 ion concentration profiles, NN takes an inference time of 0.80 s, which is approximately 3.2\(\times\) and 14.7\(\times\) faster than the XGBoost and processing MD trajectories, respectively. At last, we show that NN can reliably predict ion concentration profile with any bin size. The accuracy of NN prediction increases with larger bin sizes because of the reduced effect of stochasticity. In conclusion, NN is a fast, flexible, and most importantly, accurate surrogate model to predict ion concentration profiles under nanoconfinement. ###### Acknowledgements. We wish to acknowledge the computational resources provided by the Pittsburgh Supercomputing Center (PSC). Z.C. acknowledges the funding from the Neil and Jo Bushnell Fellowship in Engineering. ## Data Availability Statement The training data used for machine learning model training are openly available on GitHub ([https://github.com/zcao0420/IonNet](https://github.com/zcao0420/IonNet)).
2302.00956
Resilient Binary Neural Network
Binary neural networks (BNNs) have received ever-increasing popularity for their great capability of reducing storage burden as well as quickening inference time. However, there is a severe performance drop compared with real-valued networks, due to its intrinsic frequent weight oscillation during training. In this paper, we introduce a Resilient Binary Neural Network (ReBNN) to mitigate the frequent oscillation for better BNNs' training. We identify that the weight oscillation mainly stems from the non-parametric scaling factor. To address this issue, we propose to parameterize the scaling factor and introduce a weighted reconstruction loss to build an adaptive training objective. For the first time, we show that the weight oscillation is controlled by the balanced parameter attached to the reconstruction loss, which provides a theoretical foundation to parameterize it in back propagation. Based on this, we learn our ReBNN by calculating the balanced parameter based on its maximum magnitude, which can effectively mitigate the weight oscillation with a resilient training process. Extensive experiments are conducted upon various network models, such as ResNet and Faster-RCNN for computer vision, as well as BERT for natural language processing. The results demonstrate the overwhelming performance of our ReBNN over prior arts. For example, our ReBNN achieves 66.9% Top-1 accuracy with ResNet-18 backbone on the ImageNet dataset, surpassing existing state-of-the-arts by a significant margin. Our code is open-sourced at https://github.com/SteveTsui/ReBNN.
Sheng Xu, Yanjing Li, Teli Ma, Mingbao Lin, Hao Dong, Baochang Zhang, Peng Gao, Jinhu Lv
2023-02-02T08:51:07Z
http://arxiv.org/abs/2302.00956v2
# Resilient Binary Neural Network ###### Abstract Binary neural networks (BNNs) have received ever-increasing popularity for their great capability of reducing storage burden as well as queueing inference time. However, there is a severe performance drop compared with real-valued networks, due to its intrinsic frequent weight oscillation during training. In this paper, we introduce a Resilient Binary Neural Network (ReBNN) to mitigate the frequent oscillation for better BNNs' training. We identify that the weight oscillation mainly stems from the non-parametric scaling factor. To address this issue, we propose to parameterize the scaling factor and introduce a weighted reconstruction loss to build an adaptive training objective. For the first time, we show that the weight oscillation is controlled by the balanced parameter attached to the reconstruction loss, which provides a theoretical foundation to parameterize it in back propagation. Based on this, we learn our ReBNN by calculating the balanced parameter based on its maximum magnitude, which can effectively mitigate the weight oscillation with a resilient training process. Extensive experiments are conducted upon various network models, such as ResNet and Faster-RCNN for computer vision, as as BERT for natural language processing. The results demonstrate the overwhelming performance of our ReBNN over prior arts. For example, our ReBNN achieves 66.9% Top-1 accuracy with ResNet-18 backbone on the ImageNet dataset, surpassing existing state-of-the-arts by a significant margin. Our code is open-sourced at [https://github.com/SteveTsui/ReBNN](https://github.com/SteveTsui/ReBNN). 1 Beihang University, Beijing, P.R.China \({}^{2}\) Shanghai AI Laboratory, Shanghai, P.R.China \({}^{3}\) Peking University, Beijing, P.R.China \({}^{4}\) Zhongguancun Laboratory, Beijing, P.R.China ## Introduction Deep neural networks (DNNs) have dominated the recent advances of artificial intelligence from computer vision (CV) [17, 14] to natural language processing (NLP) [16, 15] and many beyond. In particular, large pre-trained models, _e.g._, ResNet [14] and BERT [13], have continuously broken many records of the state-of-the-art performance. However, the achievement also comes with tremendous demands for memory and computation resources. These demands pose a huge challenge to the computing ability of many devices, especially resource-limited platforms such as mobile phones and electronic gadgets. In light of this, substantial research efforts are being invested in saving memory usage and computational power for an efficient online inference [14, 15, 16, 17]. Among these studies, network quantization is particularly suitable for model deployment on resource-limited platforms for its great reduction in parameter bit-width and practical speedups supported by general hardware devices. Binarization, an extreme form of quantization, represents weights and activations of CNNs using a single bit, which well decreases the storage requirements by \(32\times\) and computation cost by up to \(58\times\)[15]. Consequently, binarized neural networks (BNNs) are widely deployed on various tasks such as image classification [15, 16, 17, 18] and object detection [16, 17], and have the potential to be deployed directly on next-generation AI chips. However, the performance of BNNs remains largely inequal to the real-valued counterparts, due primarily to the degraded representation capability and trainability. Conventional BNNs [15, 16] are often sub-optimized, due to their intrinsic frequent weight oscillation during training. We first identify that the weight oscillation mainly stems from the non-parametric scaling factor. Fig. 1(a) shows the epoch-wise oscillation1 of ReActNet, where weight oscillation exists even when the network is convergent. As shown in Fig. 1(b), the conventional ReActNet [16] possesses a channel-wise tri-modal distribution in the 1-bit convolution layers, whose peaks respectively center around the \(\{-1,0,+1\}\). Such distribution leads to a magnified scaling factor \(\alpha\), and thus the quantized weights \(\pm\alpha\) are quite larger than the small weights around \(0\), which might cause the weight oscillation. As illustrated in Fig. 1(c), in BNNs, the real-valued latent tensor is binarized by the sign function and scaled by the scaling factor (the orange dot) in the forward propagation. In the backward propagation, the gradient is computed based on the quantized value \(\pm\alpha\) (indicated by the yellow dotted line). However, the gradient of small latent weights is misleading, when the scaling factor is magnified by the weights around \(\pm 1\) as ReActNet (Fig. 1(a)). Then the update is conducted on the latent value (the **black** dot), which leads to the oscillation of the latent weight. With extremely limited representation states, such latent weights with small magnitudes frequently oscillate during the non-convex optimization. To address the aforementioned problem, we aim to introduce a Resilient Binary Neural Network (ReBNN). The intuition of our work is to re-learn the channel-wise scaling factor as well as the latent weights in a unified framework. Accordingly, we propose to parameterize the scaling factor and introduce a weighted reconstruction loss to build an adaptive training objective. We further show that the oscillation is factually controlled by the balanced parameter attached to the reconstruction loss, which provides a theoretical foundation to parameterize it in back propagation. The oscillation only happens when the gradient possesses a magnitude big enough to change the sign of the latent weight. Consequently, we calculate the balanced parameter based on the maximum magnitude of weight gradient during each iteration, leading to resilient gradients and effectively mitigating the weight oscillation. Our main contributions are summarized as follows: * We propose a new resilient gradient for learning the binary neural networks (ReBNN), which mitigates the frequent oscillation to better train BNNs. * We parameterize the scaling factor and introduce a weighted reconstruction loss to build an adaptive learning objective. We prove that the occurrence of oscillation is controlled by the balanced parameter attached to the reconstruction loss. Therefore, we utilize resilient weight gradients to learn our ReBNN and effectively mitigate the weight oscillation. * Extensive experiments demonstrate the superiority of our ReBNN against other prior state-of-the-arts. For example, our ReBNN achieves 66.9% Top-1 accuracy on the ImageNet dataset, surpassing prior ReActNet by 1.0% with no extra parameters. In particular, our ReBNN also achieves state-of-the-art on fully binarized BERT models, demonstrating the generality of our ReBNN. ## Related Work BinaryNet, based on BinaryConnect, was proposed to train CNNs with binary weights. The activations are triggered at run-time while the parameters are computed during training. Following this line of research, local binary convolution (LBC) layers are introduced in [11] to binarize the non-linearly activations. XNOR-Net [14] is introduced to improve convolution efficiency by binarizing the weights and inputs of the convolution kernels. More recently, Bi-Real Net [15] explores a new variant of residual structure to preserve the information of real activations before the sign function, with a tight approximation to the derivative of the non-differentiable sign function. Real-to-binary [13] re-scales the feature maps on the channels according to the input before binarized operations and adds a SE-Net [15] like gating module. ReActNet [15] replaces the conventional PReLU [12] and the sign function of the BNNs with RPReLU and RSign with a learnable threshold, thus improving the performance of BNNs. RBONN [21] introduces a recurrent bilinear optimization to address the asynchronous convergence problem for BNNs, which further improves the performance of BNNs. However, most of these aforementioned suffer from the weight oscillation mainly stemming from the non-parametric scaling factor. Unlike prior works, our ReBNN proposes to parameterize the scaling factor and introduces a weighted reconstruction loss to build an adaptive training objective. We further prove the oscillation is controlled by the balanced parameter. Based on the analysis, we introduce a resilient weight gradient to effectively address the oscillation problem. Figure 1: (a) We show the epoch-wise weight oscillation of ReActNet. (b) We randomly select 2 channels of the first 1-bit layer in ReActNet [15]. Obviously, the distribution is with 3 peaks centering around \(\{-1,0,+1\}\), which magnifies the non-parametric scaling factor (**red** line). (c) We illustrate the weight oscillation caused by such inappropriate scale calculation, where \(\mathbf{w}\) and \(\mathcal{L}\) indicate the latent weight and network loss function (**blue** line), respectively. ## Methodology ### Preliminaries Given an \(N\)-layer CNN model, we denote its weight set as \(\mathbf{W}=\{\mathbf{w}^{n}\}_{n=1}^{N}\) and input feature map set as \(\mathbf{A}=\{\mathbf{a}^{n}_{in}\}_{n=1}^{N}\). The \(\mathbf{w}^{n}\in\mathbb{R}^{C^{n}_{in}\times C^{n}_{in}\times K^{n}}\times K^{n}\) and \(\mathbf{a}^{n}_{in}\in\mathbb{R}^{C^{n}_{in}\times W^{n}_{in}\times H^{n}_{in}}\) are the convolutional weight and the input feature map in the \(n\)-th layer, where \(C^{n}_{in}\), \(C^{n}_{out}\) and \(K^{n}\) respectively stand for input channel number, output channel number and the kernel size. Also, \(W^{n}_{in}\) and \(H^{n}_{in}\) are the width and height of the feature maps. Then, the convolutional outputs \(\mathbf{a}^{n}_{out}\) can be technically formulated as: \[\mathbf{a}^{n}_{out}=\mathbf{w}^{n}\otimes\mathbf{a}^{n}_{in}, \tag{1}\] where \(\otimes\) represents the convolution operation. Herein, we omit the non-linear function for simplicity. Binary neural network intends to represent \(\mathbf{w}^{n}\) and \(\mathbf{a}^{n}\) in a 1-bit format as \(\mathbf{b}^{\mathbf{w}^{n}}\in\{-1,+1\}^{C^{n}_{out}\times C^{n}_{in}\times K^ {n}\times K^{n}}\) and \(\mathbf{b}^{\mathbf{a}^{n}_{in}}\in\{-1,+1\}^{C^{n}_{in}\times W^{n}_{in}\times H ^{n}_{in}}\) such that the float-point convolutional outputs can be approximated by the efficient XNOR and Bit-count instructions as: \[\mathbf{a}^{n}_{out}\approx\boldsymbol{\alpha}^{n}\circ(\mathbf{b}^{\mathbf{w} ^{n}}\odot\mathbf{b}^{\mathbf{a}^{n}_{in}}), \tag{2}\] where \(\circ\) represents the channel-wise multiplication, \(\odot\) denotes the XNOR and Bit-count instructions, and \(\boldsymbol{\alpha}^{n}=\{\alpha^{n}_{1},\alpha^{n}_{2},...,\alpha^{n}_{C^{n}_{ out}}\}\in\mathbb{R}^{C^{n}_{out}}_{+}\) is known as the channel-wise scaling factor vector (Rastegari et al., 2016) to mitigate the output gap between Eq. (1) and its approximation of Eq. (2). We denote \(\mathcal{A}=\{\boldsymbol{\alpha}^{n}\}_{n=1}^{N}\). Most existing implementations simply follow earlier studies (Rastegari et al., 2016; Liu et al., 2018) to optimize \(\mathcal{A}\) and latent weights \(\mathbf{W}\) based on a non-parametric bi-level optimization as: \[\mathbf{W}^{*} =\operatorname*{arg\,min}_{\mathbf{W}}\mathcal{L}(\mathbf{W}; \mathcal{A}^{*}), \tag{3}\] \[\mathrm{s.t.} \boldsymbol{\alpha}^{n*} =\operatorname*{arg\,min}_{\boldsymbol{\alpha}^{n}}\|\mathbf{w}^{ n}-\boldsymbol{\alpha}^{n}\circ\mathbf{b}^{\mathbf{w}^{n}}\|_{2}^{2}, \tag{4}\] where \(\mathcal{L}(\cdot)\) represents the training loss. Consequently, a closed-form solution of \(\boldsymbol{\alpha}^{n}\) can be derived via the channel-wise absolute mean (CAM) as \(\alpha^{n}_{i}=\frac{\|\mathbf{w}^{n}_{i},\|_{1}}{M^{n}}\) and \(M^{n}=C^{n}_{in}\times K^{n}\times K^{n}\). For ease of representation, we use \(\mathbf{w}^{n}_{i}\) as an alternative of \(\mathbf{w}^{n}_{i,...}\) in what follows. The latent weight \(\mathbf{w}^{n}\) is updated via a standard gradient back-propagation algorithm and its gradient is calculated as: \[\delta_{\mathbf{w}^{n}_{i}}=\frac{\partial\mathcal{L}}{\partial\mathbf{w}^{n}_ {i}}=\frac{\partial\mathcal{L}}{\partial\hat{\mathbf{w}}^{n}_{i}}\frac{ \partial\hat{\mathbf{w}}^{n}_{i}}{\partial\mathbf{w}^{n}_{i}}=\alpha^{n}_{i} \frac{\partial\mathcal{L}}{\partial\hat{\mathbf{w}}^{n}_{i}}\varoq{1}_{| \mathbf{w}^{n}_{i}|\leq 1}, \tag{5}\] where \(\varoq{8}\) denotes the Hadmard product and \(\hat{\mathbf{w}}^{n}=\boldsymbol{\alpha}^{n}\circ\mathbf{b}^{\mathbf{w}^{n}}\). **Discussion**. Eq. (5) shows weight gradient mainly comes from the non-parametric \(\alpha^{n}_{i}\) and the gradient \(\frac{\partial\mathcal{L}}{\partial\hat{\mathbf{w}}^{n}_{i}}\). \(\frac{\partial\mathcal{L}}{\partial\hat{\mathbf{w}}^{n}_{i}}\) is automatically solved in the back propagation and becomes smaller as network convergence, however, \(\alpha^{n}_{i}\) is often magnified by the tri-modal distribution (Liu et al., 2020). Therefore, weight oscillation mainly stems from \(\alpha^{n}_{i}\). Given a single weight \(\mathbf{w}^{n}_{i,j}(1\leq j\leq M^{n})\) centering around zero, the gradient \(\frac{\partial\mathcal{L}}{\partial\hat{\mathbf{w}}^{n}_{i,j}}\) is misleading, due to the significant gap between \(\mathbf{w}^{n}_{i,j}\) and \(\alpha^{n}_{i}\mathbf{b}^{\mathbf{w}^{n}_{i,j}}\). Consequently, the bi-level optimization leads to frequent weight oscillation. To address this issue, we reformulate traditional bi-level optimization using Lagrange multiplier and show that a learnable scaling factor is a natural training stabilizer. ### Resilient Binary Neural Network We first give the learning objective in this paper as: \[\operatorname*{arg\,min}_{\mathbf{W},\mathcal{A}}\mathcal{L}(\mathbf{W}, \mathcal{A})+\mathcal{L}_{R}(\mathbf{W},\mathcal{A}), \tag{6}\] where \(\mathcal{L}_{R}(\mathbf{W},\mathcal{A})\) is a weighted reconstruction loss and defined as: \[\mathcal{L}_{R}(\mathbf{W},\mathcal{A})=\frac{1}{2}\sum_{n=1}^{N}\sum_{i=1}^{C _{out}}\gamma^{n}_{i}\|\mathbf{w}^{n}_{i}-\alpha^{n}_{i}\mathbf{b}^{\mathbf{w }^{n}_{i}}\|_{2}^{2}, \tag{7}\] in which \(\gamma^{n}_{i}\) is a balanced parameter. Based on the objective, the weight gradient in Eq. (5) becomes: \[\begin{split}\delta_{\mathbf{w}^{n}_{i}}&=\frac{ \partial\mathcal{L}}{\partial\mathbf{w}^{n}_{i}}+\gamma^{n}_{i}(\mathbf{w}^{n}_ {i}-\alpha^{n}_{i}\mathbf{b}^{\mathbf{w}^{n}_{i}})\\ &=\alpha^{n}_{i}(\frac{\partial\mathcal{L}}{\partial\hat{\mathbf{ w}}^{n}_{i}}\varoq{1}_{|\mathbf{w}^{n}_{i}|\leq 1}-\gamma^{n}_{i}\mathbf{b}^{\mathbf{w}^{n}_{i}})+ \gamma^{n}_{i}\mathbf{w}^{n}_{i}.\end{split} \tag{8}\] The \(\mathcal{S}^{n}_{i}(\alpha^{n}_{i},\mathbf{w}^{n}_{i})=\gamma^{n}_{i}(\mathbf{ w}^{n}_{i}-\alpha^{n}_{i}\mathbf{b}^{\mathbf{w}^{n}_{i}})\) is an additional term added in the back-propagation process. We add this item given that a too small \(\alpha^{n}_{i}\) diminishes the gradient \(\delta_{\mathbf{w}^{n}_{i}}\) and causes a constant weight \(\mathbf{w}^{n}_{i}\). In what follows, we state and prove the proposition that \(\delta_{\mathbf{w}^{n}_{i,j}}\) is a resilient gradient for a single weight \(\mathbf{w}^{n}_{i,j}\). We sometimes omit subscript \(i,j\) and superscript \(n\) for an easy representation. **Proposition 1**.: _The additional term \(\mathcal{S}(\alpha,\mathbf{w})=\gamma(\mathbf{w}-\alpha\mathbf{b}^{\mathbf{w}})\) achieves a resilient training process by suppressing frequent weight oscillation. Its balanced factor \(\gamma\) can be considered as the parameter controlling the occurrence of the weight oscillation._ **Proof:** We prove the proposition by contradiction. For a single weight \(\mathbf{w}\) centering around zero, the straight-through-estimator \(\mathbf{1}_{|\mathbf{w}|\leq 1}=1\). Thus we omit it in the following. Based on Eq. (8), with a learning rate \(\eta\), the weight updating process is formulated as: \[\begin{split}\mathbf{w}^{t+1}&=\mathbf{w}^{t}-\eta \delta_{\mathbf{w}^{t}}\\ &=\mathbf{w}^{t}-\eta[\alpha^{t}(\frac{\partial\mathcal{L}}{\partial \hat{\mathbf{w}}^{t}}-\gamma\mathbf{b}^{\mathbf{w}^{t}})+\gamma\mathbf{w}^{t}] \\ &=(1-\eta\gamma)\mathbf{w}^{t}-\eta\alpha^{t}(\frac{\partial\mathcal{L}}{ \partial\hat{\mathbf{w}}^{t}}-\gamma\mathbf{b}^{\mathbf{w}^{t}})\\ &=(1-\eta\gamma)\big{[}\mathbf{w}^{t}-\frac{\eta\alpha^{t}}{(1- \eta\gamma)}(\frac{\partial\mathcal{L}}{\partial\hat{\mathbf{w}}^{t}}-\gamma \mathbf{b}^{\mathbf{w}^{t}})\big{]},\end{split} \tag{9}\] where \(t\) denotes the \(t\)-th training iteration and \(\eta\) represents learning rate. Different weights shares different distances to the quantization level \(\pm 1\), therefore, their gradients should be modified in compliance with their scaling factors and current learning rate. We first assume the initial state \(\mathbf{b}^{\mathbf{w}^{t}}=-1\), and Similarly, the oscillation probability from the iteration \(t+1\) to \(t+2\) is: \[P(\mathbf{b}^{\mathbf{w}^{t+1}}\neq\mathbf{b}^{\mathbf{w}^{t+2}})\Big{|}_{ \mathbf{b}^{\mathbf{w}^{t+1}}=1}\leq P(\frac{\partial\mathcal{L}}{\partial\hat{ \mathbf{w}}^{t+1}}\geq\gamma). \tag{11}\] Thus, the sequential oscillation probability from the iteration \(t\) to \(t+2\) is: \[\begin{split}& P((\mathbf{b}^{\mathbf{w}^{t+1}}\neq\mathbf{b}^{ \mathbf{w}^{t+2}})\cap(\mathbf{b}^{\mathbf{w}^{t+1}}\neq\mathbf{b}^{\mathbf{w}^ {t+2}}))|_{\mathbf{b}^{\mathbf{w}^{t}}=-1}\\ &\leq P\big{(}(\frac{\partial\mathcal{L}}{\partial\hat{\mathbf{w }}^{t}}\leq-\gamma)\cap(\frac{\partial\mathcal{L}}{\partial\hat{\mathbf{w}}^{t +1}}\geq\gamma)\big{)},\end{split} \tag{12}\] which denotes that the weight oscillation happens only if the magnitudes of \(\frac{\partial\mathcal{L}}{\partial\hat{\mathbf{w}}^{t}}\) and \(\frac{\partial\mathcal{L}}{\partial\hat{\mathbf{w}}^{t+1}}\) are both larger than \(\gamma\). **As a result, its attached factor \(\gamma\) can be considered as a parameter used to control the occurrence of the weight oscillation**. However, if the conditions in Eq. (12) are met, with Eq. (9) concluded, the gradient of \(\hat{\mathbf{w}}^{t+1}\) is formulated as: \[\begin{split}\frac{\partial\mathcal{L}}{\partial\hat{\mathbf{w} }^{t+1}}&=\frac{\partial\mathcal{L}}{\partial\hat{\mathbf{w}}^{t }}-\eta\frac{\partial^{2}\mathcal{L}}{\partial(\hat{\mathbf{w}}^{t})^{2}} \geq\gamma,\\ \eta\frac{\partial^{2}\mathcal{L}}{\partial(\hat{\mathbf{w}}^{t} )^{2}}&\leq\frac{\partial\mathcal{L}}{\partial\hat{\mathbf{w}}^{t }}-\gamma\leq-2\gamma.\end{split} \tag{13}\] Note that \(\eta\) and \(\gamma\) are two positive variables, thus the second-order gradient \(\frac{\partial^{2}\mathcal{L}}{\partial(\hat{\mathbf{w}}^{t})^{2}}<0\) holds always. Consequently, \(\mathcal{L}(\hat{\mathbf{w}}^{t+1})\) can only be a local maxima, instead of a minima, which raises a contradiction with convergence in the training process. Such a contradiction indicates that the training algorithm will be convergent until no oscillation occurs, due to the additional term \(\mathcal{S}(\alpha,\mathbf{w})\). Therefore, we completes our proof. Our proposition and proof reveal that the balanced parameter \(\gamma\) is actually a "threshold". A very small "threshold" fails to mitigate the frequent oscillation effectively while a too large one suppresses the necessary sign inversion and hinders the gradient descent process. To solve this, we devise the learning rule of \(\gamma\) as: \[\gamma_{i}^{n,t+1}=\frac{1}{M^{n}}\|\mathbf{b}^{\mathbf{w}_{i}^{n,t}}\varoquasw \mathbf{b}^{\mathbf{w}_{i}^{n,t+1}}-\mathbf{1}\|_{0}\cdot\max_{1\leq j\leq M^ {n}}(|\frac{\partial\mathcal{L}}{\partial\hat{\mathbf{w}}_{i,j}^{n,t}}|), \tag{14}\] where the first item \(\frac{1}{M^{n}}\|\mathbf{b}^{\mathbf{w}_{i}^{n,t}}\varoquasw\mathbf{b}^{ \mathbf{w}_{i}^{n,t+1}}-\mathbf{1}\|_{0}\) denotes the proportion of weights with sign changed. The second item \(\max_{1\leq j\leq M^{n}}(|\frac{\partial\mathcal{L}}{\partial\hat{\mathbf{w}} _{i,j}^{n}}|)\) is derived from Eq. (12), denoting the gradient with the greatest magnitude of the \(t\)-th iteration. In this way, we suppress the frequent weight oscillation by a resilient gradient. We further optimize the scaling factor as: \[\delta_{\alpha_{i}^{n}}=\frac{\partial\mathcal{L}}{\partial\alpha_{i}^{n}}+ \frac{\partial\mathcal{L}_{R}}{\partial\alpha_{i}^{n}}. \tag{15}\] The gradient derived from softmax loss can be easily calculated according to back propagation. Based on Eq. (7), it is easy to derive: \[\frac{\partial\mathcal{L}_{R}}{\partial\alpha_{i}^{n}}=\gamma_{i}^{n}(\mathbf{ w}_{i}^{n}-\alpha_{i}^{n}\mathbf{b}^{\mathbf{w}_{i}^{n}})\varoquasw\mathbf{b}^{ \mathbf{w}_{i}^{n}}. \tag{16}\] ## Experiments Our ReBNNs are evaluated first on image classification and object detection tasks for visual recognition. Then, we evaluate ReBNN on the GLUE [22] benchmark with diverse NLP tasks. In this section, we first introduce the implementation details of ReBNN. Then we validate the effectiveness of the balanced parameter in the ablation study. Finally, we compare our method with state-of-the-art BNNs on various tasks to demonstrate the superiority of ReBNNs. ### Datasets and Implementation Details **Datasets:** For its huge scope and diversity, the ImageNet object classification dataset [23] is more demanding, which has 1000 classes, 1.2 million training photos, and 50k validation images. The COCO dataset includes images from 80 different categories. All our experiments on COCO dataset are conducted on the COCO 2014 [10] object detection track in the training stage, which contains the combination of 80k images from the COCO train2014 and 35k images sampled from COCO val2014, _i.e._, COCO trainval35k. Then we test our method on the remaining 5k images from the COCO minival. We report the average precision (AP) for IoUs\(\in\)[0.5: 0.05: 0.95], designated as mAP@[.5,.95], using COCO's standard evaluation metric. For further analyzing our method, we also report AP\({}_{50}\), AP\({}_{75}\), AP\({}_{s}\), AP\({}_{m}\), and AP\({}_{l}\). The GLUE benchmark contains multiple natural language understanding tasks. We follow [22] to evaluate the performance: Matthews correlation for CoLA, Spearman correlation for STS-B, and accuracy for the rest tasks: RTE, MRPC, SST-2, QQP, MNLI-m (matched), and MNLI-mm (mismatched). Also, for machine reading comprehension on SQuAD, we report the EM (exact match) and F1 score. **Implementation Details:** PyTorch [23] is used to implement ReBNN. We run the experiments on 4 NVIDIA Tesla A100 GPUs with \(80\) GB memory. Following [10], we retain weights in the first layer, shortcut, and last layer in the networks as the real-valued. For the image classification task, ResNets [11] are employed as the backbone networks to build our ReBNNs. We offer two implementation setups for fair comparison. First, we use **one-stage training** on ResNets, with SGD as the optimization algorithm and a momentum of 0.9, and a weight decay of \(1e-4\) following [21]. \(\eta\) is set to 0.1. The learning rates are optimized by the annealing cosine learning rate schedule. The number of epochs is set as 200. Then, we employ **two-stage training** following [10]. Each stage counts 256 epochs. In this implementation, Adam is selected as the optimizer. And the network is supervised by a real-valued ResNet-34 teacher. The weight decay is set as 0 following [10]. The learning rates \(\eta\) is set as \(1e-3\) and annealed to 0 by linear descent. For objection detection, we use the Faster-RCNN [10] and SSD [10], which are based on ResNet-18 [10] and VGG-16 [26] backbone, respectively. We fine-tune the detector on the dataset for object detection. For SSD and Faster-RCNN, the batch size is set to 16 and 8, respectively, with applying SGD optimizer. \(\eta\) is equal to 0.008. We use the same structure and training settings as BiDet (Wang et al., 2020) on the SSD framework. The input resolution is \(1000\times 600\) for Faster-RCNN and \(300\times 300\) for SSD, respectively. For the natural language processing task, we conduct experiments based on BERT\({}_{\rm BASE}\)(Devlin et al., 2018) (with 12 hidden layers) architecture following BiBERT (Qin et al., 2022), respectively. The detailed training setups are the same as BiBERT. We extend the ReBNN to multi-layer perceptrons (MLPs) and use the Bi-Attention following BiBERT (Qin et al., 2022). ### Ablation study Since no extra hyper-parameter is introduced, we first evaluate the different calculation of \(\gamma\). Then we show how our ReBNN achieves a resilient training process. In the ablation study, we use the ResNet-18 backbone initialized from the first stage training with W32A1 following (Liu et al., 2020). **Calculation of \(\gamma\):** We compare the different calculations of \(\gamma\) in this part. As shown in Tab. 1, the performances increase first and then decrease when increasing the value of constant \(\gamma\). Considering that the gradient magnitude varies layer-wise and channel-wise, a subtle \(\gamma\) can hardly be manually set as a global value. We further compare the gradient-based calculation. To avoid extreme values, we set the upper bound as \(2e-4\) and lower bound as \(1e-5\). As shown in the bottom lines, we first use \(\max_{1\leq j\leq M^{n}}(|\frac{\partial\mathcal{L}}{\partial\mathbf{w}_{i,j }^{n}}|)\), the maximum intra-channel gradient of last iteration, which shows a similar performance compared with the constant \(1e-4\). This indicates that only using the maximum intra-channel gradient may also suppress necessary sign flip, thus hindering the training. Inspired by this, we use Eq. (14) to calculate \(\gamma\) and improve the performance by 0.6%, showing that considering the weight oscillation proportion allows the necessary sign flip and leads a more effective training. We also show the training loss curves in Fig. 3(b). As plotted, the curves of \(\mathcal{L}\) almost demonstrate the degrees of training sufficiency. Thus we draw the conclusion that ReBNN with \(\gamma\) calculated by Eq. (14) achieves the lowest training loss as well as an efficient training process. Note that the loss may not be minimal at each training iteration, but our method is just a reasonable version of gradient descent algorithms by nature, which can be used to solve the optimization problem as general. We empirically prove ReBNN's capability of mitigating the weight oscillation, leading to a better convergence. **Resilient training process:** We first show the evolution of the latent weight distribution is this section. We plot the distribution of the first channel of the first binary convolution layer per 32 epochs in Fig. 2. As seen, our ReBNN can efficiently redistribute the BNNs towards resilience. Conventional ReActNet (Liu et al., 2020) possesses a tri-model distribution, which is unstable due to the scaling factor with \begin{table} \begin{tabular}{c c c} \hline \hline Value of \(\gamma\) & Top-1 & Top-5 \\ \hline \(0\) & 65.8 & 86.3 \\ \(1e-5\) & 66.2 & 86.7 \\ \(1e-4\) & 66.4 & 86.7 \\ \(1e-3\) & 66.3 & 86.8 \\ \(1e-2\) & 65.9 & 86.5 \\ \(\max_{1\leq j\leq M^{n}}(|\frac{\partial\mathcal{L}}{\partial\mathbf{w}_{i,j}^ {n}}|)\) & 66.3 & 86.2 \\ **Eq. (14)** & **66.9** & **87.1** \\ \hline \hline \end{tabular} \end{table} Table 1: We compare different calculation method of \(\gamma\), including constant varying from \(0\) to \(1e-2\) and gradient-based calculation. Figure 3: (a) The epoch-wise weight oscillation ratio of ReActNet (solid), ReCU (dotted) and ReBNN (dashed). (b) Comparing the loss curves of ReActNet and our ReBNN with different calculation of \(\gamma\). Figure 2: The evolution of latent weight distribution of (a) ReActNet and (b) ReBNN. We select the first channel of the first binary convolution layer to show the evolution. The model is initialized from the first stage training with W32A1 following (Liu et al., 2020). We plot the distribution every 32 epochs. large magnitudes. In contrast, our ReBNN is constrained by the balanced parameter \(\gamma\) during training, thus leading to a resilient bi-modal distribution with fewer weights centering around zero. We also plot the ratios of sequential weight oscillation of ReBNN and ReActNet for the 1-st, 8-th, and 16-th binary convolution layers of ResNet-18. As shown in Fig. 3(a), the dashed lines gain much lower magnitudes than the solid (ReActNet) and dotted (ReCU [21]) lines with the same color, validating the effectiveness of our ReBNN in suppressing the consecutive weight oscillation. Besides, we can also find that the sequential weight oscillation ratios of ReBNN are gradually decreased to 0 as the training converges. ### Image classification We first show the experimental results on ImageNet with ResNet-18 and ResNet-34 [14] backbones in Tab. 2. We compare ReBNN with BNN [15], XNOR-Net [17], Bi-Real Net [16], RBNN [18], and ReCU [21] for the one-stage training strategy. For the two-stage training strategy, we compare with ReActNet [16], FDA-BNN [21], and ReCU [21]. We evaluate our ReBNN with one-stage training following [21]. ReBNN outperforms all of the compared binary models in both Top-1 and Top-5 accuracy, as shown in Tab. 2. ReBNN-based ResNet-18 respectively achieves 61.6% and 83.4% in Top-1 and Top-5 accuracy, with 0.6% increases over state-of-the-art RECU. ReBNN further outperforms all compared methods with ResNet-34 backbone, achieving 65.8% Top-1 accuracy. We further evaluate our ReBNN with two-stage training following [16], where ReBNN surpasses ReActNet by 1.0%/0.6% Top-1 accuracy with ResNet-18/34 backbones, respectively. In this paper, we use memory usage and OPs following [16] in comparison to other tasks for further reference. As shown in Tab. 2, ReBNN theoretically accelerates ResNet-18/34 by 11.17\(\times\) and 19.04\(\times\), which is significant for real-time applications. \begin{table} \begin{tabular}{c c c c c c c} \hline \hline Network & Method & \#Bits & Size\({}_{\rm(MB)}\) & OPs\({}_{\rm(10^{8})}\) & Top-1 & Top-5 \\ \hline \multirow{8}{*}{ResNet-18} & Real-valued & 32-32 & 46.76 & 18.21 & 69.6 & 89.2 \\ & BNN & & & & 22.2 & 67.1 \\ & XNOR-Net & & & & 51.2 & 73.2 \\ & Bi-Real Net & & & & 56.4 & 79.5 \\ & RBNN & 1-1 & 4.15 & 1.63 & 59.6 & 81.6 \\ & ReCU & & & & 61.0 & 82.6 \\ & **ReRNN\({}_{1}\)** & & & **61.6** & **83.4** \\ & ReActNet & & & & 55.9 & 86.2 \\ & FDA-BNN & & & & 65.8 & 86.4 \\ & ReCU & 1-1 & 4.15 & 1.63 & 66.4 & 86.5 \\ & **ReBNN\({}_{2}\)** & & & & **66.9** & **87.1** \\ \hline \multirow{8}{*}{ResNet-34} & Real-valued & 32-32 & 87.19 & 36.74 & 73.3 & 91.3 \\ & Bi-Real Net & & & 62.2 & 83.9 \\ \cline{1-1} & RBNN & 1-1 & 5.41 & 1.93 & 63.1 & 84.4 \\ \cline{1-1} & RecU & 1-1 & 5.41 & 1.93 & 65.1 & 85.8 \\ \cline{1-1} & **ReBNN\({}_{1}\)** & & & **65.8** & **86.2** \\ \cline{1-1} & ReActNet & 1-1 & 5.41 & 1.93 & 69.3 & 88.6 \\ \cline{1-1} & **ReBNN\({}_{2}\)** & 1-1 & 5.41 & 1.93 & **69.9** & **88.9** \\ \hline \hline \end{tabular} \end{table} Table 2: A performance comparison with SOTAs on ImageNet with different training strategies. #Bits denotes the bit width of weights and activations. We report the Top-1 (%) and Top-5 (%) accuracy performances. ReBNN\({}_{1}\) and ReBNN\({}_{2}\) denote our ReBNN learned with one-stage and two-stage training. \begin{table} \begin{tabular}{c c c c c c c c c c c} \hline \hline Framework & Backbone & Method & \#Bits & Size\({}_{\rm(MB)}\) & OPs\({}_{\rm(G)}\) & \multicolumn{3}{c}{mAP} & \multirow{2}{*}{\({\rm{\bf{p}}}_{50}\)} & \multirow{2}{*}{\({\rm{\bf{AP}}}_{75}\)} & \multirow{2}{*}{\({\rm{\bf{AP}}}_{s}\)} & \multirow{2}{*}{\({\rm{\bf{AP}}}_{m}\)} & \multirow{2}{*}{\({\rm{\bf{AP}}}_{1}\)} \\ & & Real-valued & 32-32 & 47.48 & 434.39 & 26.0 & 44.8 & 27.2 & 10.0 & 28.9 & 39.7 \\ \multirow{4}{*}{Faster-RCNN} & \multirow{4}{*}{ResNet-18} & Real-valued & 4-4 & 6.73 & 55.90 & 22.9 & 38.6 & 23.7 & 8.0 & 24.9 & 36.3 \\ & & XNOR-Net & & & & 10.4 & 21.6 & 8.8 & 2.7 & 11.8 & 15.9 \\ & & Bi-Real Net & & & & 14.4 & 29.0 & 13.4 & 3.7 & 15.4 & 24.1 \\ & & BiDet & & & 15.7 & 31.0 & 14.4 & 4.9 & 16.7 & 25.4 \\ & & **ReBNN** & & & **19.6** & **37.6** & **20.4** & **7.0** & **20.1** & **33.1** \\ \hline \multirow{8}{*}{SSD} & \multirow{4}{*}{VGG-16} & Real-valued & 32-32 & 105.16 & 31.44 & 23.2 & 41.2 & 23.4 & 5.3 & 23.2 & 39.6 \\ & & DoRe ### Object detection Because of its size and diversity, the COCO dataset presents a great challenge for object detection. On COCO, the proposed ReBNN is compared against state-of-the-art 1-bit neural networks such as XNOR-Net [14], Bi-Real Net [13], and BiDet [20]. We present the performance of the 4-bit DoReFa-Net [1] for reference. As shown in Tab. 3, compared with state-of-the-art XNOR-Net, Bi-Real Net, and BiDet, our method improves the mAP@[.5,.95] by 9.2%, 5.2%, and 3.9% using the Faster-RCNN framework with the ResNet-18 backbone. Moreover, on other APs with different IoU thresholds, our ReBNN clearly beats others. Compared to DoReFa-Net, a quantized neural network with 4-bit weights and activations, our ReBNN obtains only 3.3% lower mAP. Our method yields a 1-bit detector with a performance of only 6.1% mAP lower than the best-performing real-valued counterpart (19.6% vs. 26.0%). Similarly, using the SSD300 framework with the VGG-16 backbone, our method achieves 18.1% mAP@[.5,.95], outperforming XNOR-Net, Bi-Real Net, and BiDet by 10.0 %, 6.9%, and 4.9% mAP, respectively. Our ReBNN also achieves highly efficient models by theoretically accelerating Faster-RCNN and SSD by 50.62\(\times\) and 14.76\(\times\). ### Natural language processing In Tab. 4, we show experiments on the BERT\({}_{\mathrm{BASE}}\) architecture and the GLUE benchmark without data augmentation following BiBERT [20]. Experiments show that outperforms other methods on the development set of GLUE benchmark, including TernaryBERT [1], Bi-O2BERT [1], Q-BERT [1], Q2BERT [1], and BiBERT [20]. Our ReBNN surpasses existing methods on BERT\({}_{\mathrm{BASE}}\) architecture by a clear margin in the average accuracy. For example, our ReBNN surpasses BiBERT by 6.6% accuracy on QNLI dataset, which is significant for the natural language processing task. We observe our ReBNN brings improvements on 7 out of total 8 datasets, thus leading to a 2.6% average accuracy improvement. Our ReBNN also achieves highly efficient models by theoretically accelerating the BERT\({}_{\mathrm{BASE}}\) architecture by 56.25\(\times\). ### Deployment Efficiency We implement the 1-bit models achieved by our ReBNN on ODROID C4, which has a 2.016 GHz 64-bit quad-core ARM Cortex-A55. With evaluating its real speed in practice, the efficiency of our ReBNN is proved when deployed into real-world mobile devices. We leverage the SIMD instruction SSHL on ARM NEON to make the inference framework BOLT [1] compatible with ReBNN. We compare ReBNN to the real-valued backbones in Tab. 5. We can see that ReBNN's inference speed is substantially faster with the highly efficient BOLT framework. For example, the acceleration rate achieves about 8.64\(\times\) on ResNet-18, which is slightly lower than the theoretical acceleration rate. For ResNet-34 backbone, ReBNN can achieve 9.03\(\times\) acceleration rate with BOLT framework on hardware, which is significant for the computer vision on real-world edge devices. ## Conclusion In this paper, we analyze the influence of frequent weight oscillation in binary neural networks and proposed a Resilient Binary Neural Network (ReBNN) to provide resilient gradients for latent weights updating. Our method specifically proposes to parameterize the scaling factor and introduces a weighted reconstruction loss to build an adaptive training objective. We further manifest that the balanced parameter can serve as an indicator to reflect the frequency of the weight oscillation during back propagation. Our ReBNN reaches resilience by learning the balanced parameter, leading to a great reduction of weight oscillation. ReBNN shows strong generalization to gain impressive performance on various tasks such as image classification, object detection, and natural language processing tasks, demonstrating the superiority of the proposed method over state-of-the-art BNNs. \begin{table} \begin{tabular}{c c c c c c c c c c c c c} \hline Method & \#Bits & Size\({}_{\mathrm{(MB)}}\) & OPs\({}_{\mathrm{(G)}}\) & MNLI-m/mm & QQP & QNLI & SST-2 & CoLA & STS-B & MRPC & RTE & Avg. \\ \hline Real-valued & 32-32-32 & 418 & 22.5 & 84.9/85.5 & 91.4 & 92.1 & 93.2 & 59.7 & 90.1 & 86.3 & 72.2 & 83.9 \\ - & Q-BERT & 2-8-8 & 43.0 & 6.5 & 76.6/77.0 & - & - & 84.6 & - & - & 68.3 & 52.7 & - \\ Q2BERT & 2-8-8 & 43.0 & 6.5 & 47.2/47.3 & 67.0 & 61.3 & 80.6 & 0 & 4.4 & 68.4 & 52.7 & 47.7 \\ TernaryBERT & 2-2-2 & 28.0 & 1.5 & 40.3/40.0 & 63.1 & 50.0 & 80.7 & 0 & 12.4 & 68.3 & 54.5 & 45.5 \\ BinaryBERT & & & 35.6/35.3 & 66.2 & 51.5 & 53.2 & 0 & 6.1 & 68.3 & 52.7 & 41.0 \\ BiBERT & 1-1-1 & 16.5 & 0.4 & 66.1/67.5 & 84.8 & 72.6 & 88.7 & 25.4 & 33.6 & 72.5 & **57.4** & 63.2 \\ **ReBNN** & & & **69.9/71.3** & **85.2** & **79.2** & **89.3** & **28.8** & **38.7** & **72.6** & 56.9 & **65.8** \\ \hline \end{tabular} \end{table} Table 4: Comparison of BERT quantization methods without data augmentation. #Bits denotes the bit width of weights, word embedding, and activations. “Avg.” denotes the average results. \begin{table} \begin{tabular}{c c c c c c} \hline Network & Method & W/A & Size\({}_{\mathrm{(MB)}}\) & Memory Saving & Latency\({}_{\mathrm{(ms)}}\) & Acceleration \\ \hline \multirow{2}{*}{ResNet-18} & Real-valued & 32/32 & 46.76 & - & 583.1 & - \\ & ReBNN & 1/1 & 4.15 & 17.26\(\times\) & 67.5 & 8.64\(\times\) \\ \multirow{2}{*}{ResNet-34} & Real-valued & 32/32 & 87.19 & - & 1025.6 & - \\ & ReBNN & 1/1 & 5.41 & 16.12\(\times\) & 113.6 & 9.03\(\times\) \\ \hline \end{tabular} \end{table} Table 5: Comparing ReBNN with real-valued models on hardware (single thread). ## Acknowledgment This work was supported by National Natural Science Foundation of China under Grant 62076016, 62206272, 62141604, 61972016, and 62032016, Beijing Natural Science Foundation L223024.
2304.04666
Battle Against Fluctuating Quantum Noise: Compression-Aided Framework to Enable Robust Quantum Neural Network
Recently, we have been witnessing the scale-up of superconducting quantum computers; however, the noise of quantum bits (qubits) is still an obstacle for real-world applications to leveraging the power of quantum computing. Although there exist error mitigation or error-aware designs for quantum applications, the inherent fluctuation of noise (a.k.a., instability) can easily collapse the performance of error-aware designs. What's worse, users can even not be aware of the performance degradation caused by the change in noise. To address both issues, in this paper we use Quantum Neural Network (QNN) as a vehicle to present a novel compression-aided framework, namely QuCAD, which will adapt a trained QNN to fluctuating quantum noise. In addition, with the historical calibration (noise) data, our framework will build a model repository offline, which will significantly reduce the optimization time in the online adaption process. Emulation results on an earthquake detection dataset show that QuCAD can achieve 14.91% accuracy gain on average in 146 days over a noise-aware training approach. For the execution on a 7-qubit IBM quantum processor, IBM-Jakarta, QuCAD can consistently achieve 12.52% accuracy gain on earthquake detection.
Zhirui Hu, Youzuo Lin, Qiang Guan, Weiwen Jiang
2023-04-10T15:42:38Z
http://arxiv.org/abs/2304.04666v1
# Battle Against Fluctuating Quantum Noise: ###### Abstract Recently, we have been witnessing the scale-up of superconducting quantum computers; however, the noise of quantum bits (qubits) is still an obstacle for real-world applications to leveraging the power of quantum computing. Although there exist error mitigation or error-aware designs for quantum applications, the inherent fluctuation of noise (a.k.a., instability) can easily collapse the performance of error-aware designs. What's worse, users can even not be aware of the performance degradation caused by the change in noise. To address both issues, in this paper we use Quantum Neural Network (QNN) as a vehicle to present a novel compression-aided framework, namely _QuCAD_, which will adapt a trained QNN to fluctuating quantum noise. In addition, with the historical calibration (noise) data, our framework will build a model repository offline, which will significantly reduce the optimization time in the online adaption process. Emulation results on an earthquake detection dataset show that QuCAD can achieve 14.91% accuracy gain on average in 146 days over a noise-aware training approach. For the execution on a 7-qubit IBM quantum processor, ibm-jakarta, QuCAD can consistently achieve 12.52% accuracy gain on earthquake detection. ## I Introduction We are currently in the Noisy Intermediate-Scale Quantum (NISQ) era where noise and scalability have been two well-known and critical issues in quantum computing. Nowadays, we have been witnessing the rapid development of superconducting quantum computers and the scalability issue is gradually mitigated. As an example, IBM took only 6 years to scale up its quantum computers from 5 to 433 qubits and the development of quantum research[1, 2, 3, 4, 5] is advancing rapidly. However, the high noise in quantum computing is still an obstacle for real-world applications to take advantage of quantum computing. There are many sources of noise in quantum computing, such as gate errors and readout errors. As shown in Fig. 1, the color of qubits and their connections indicates the Pauli-X and CNOT gate error from the IBM Belem backend. Unlike CMOS noise that is within a small range under \(10^{-15}\) so classical computing is more focused on performance efficiency rather than noise[6, 7, 8], the noise on qubits can reach \(10^{-2}\) to \(10^{-4}\). Moreover, as shown in Fig. 1, noise from 1-year-long profiling on the IBM Belem backend is fluctuating in a wide range, called "fluctuating quantum noise". Although there exist works to improve the robustness of quantum circuits to noise, such as error mitigation [9] and noise-aware designs [10, 11, 12], these works commonly perform the optimization based on the noise at one moment. The fluctuating quantum noise can easily make the quantum circuit lose its robustness. Thus, new innovations are needed to deal with the fluctuating noise. In this paper, we propose a novel framework, namely "QuCAD", to address the above issues. To illustrate our framework, we use Quantum Neural Network (QNN) -- a.k.a, variational quantum circuit (VQC) as an example -- since the learning approach has been shown to be an effective way for a wide range of applications from different domains (such as chemistry [13], healthcare [14], and finance [15]); and meanwhile, [16] recently has shown the potential quantum speedups using VQC. To deal with fluctuating quantum noise, a straightforward method is to apply a noise-aware training approach to retrain QNN before each inference; however, it will obviously incur high costs. More importantly, as the quantum noise changes in a wide range, we observe that a set of parameters will deviate from the loss surface, which impedes the noise-aware training to find optimal solutions. To address this problem, we made an investigation and found that these parameters will lead to short circuits after the logical-to-physical compilation. Equivalent to classical neural networks, these QNN parameters can be regarded as compression levels. Therefore, QNN compression can be helpful to optimize the model in a noisy environment. Based on our observations, in QuCAD, we develop a novel noise-aware QNN compression algorithm. It will interplay with other two components: (1) a model repository constructor that can build a repository of compressed models offline using representative historical data; and (2) a model repository manager that can make an online adaption of models to the fluctuating noise. As such, QuCAD can automatically and efficiently obtain the QNN models adapted to run-time noise for high performance. The main contributions of this paper are as follows. * We reveal that the fluctuating quantum noise will collapse the performance of quantum neural networks (QNNs). * We develop a noise-aware QNN compression algorithm to adapt pretrained QNN model to a given noise. * On top of the noise-aware compression algorithm, we further propose a 2-stage framework to adapt QNN model to fluctuating quantum noise automatically. Fig. 1: The fluctuating noise observed on IBM backend bele Evaluation is conducted on both IBM Aer simulator and IBM quantum processor ibm-jakarta. Experiment results on MNIST, earthquake detection dataset, and Iris show the effectiveness and efficiency of QuCAD. Especially, QuCAD achieves superior performance among the competitors on all datasets. It achieves 16.32%, 38.88%, and 15.36% accuracy gain compared with the default configuration without optimization. Even compared with noise-aware training before every execution, QuCAD can still achieve over a 15% accuracy improvement on average; meanwhile, QuCAD can reduce the training time to over 100\(\times\) at the online stage. For the execution on a 7-qubit IBM quantum processor ibm-jakarta, QuCAD can consistently achieve a 13.7% accuracy gain on the earthquake detection dataset. The remainder of the paper is organized as follows. Section 2 reviews the related work and provides observations, challenges and motivations. Section 3 presents the proposed QuCAD framework. Experimental results are provided in Section 4 and concluding remarks are given in Section 5. ## II Related Work, Challenge, and Motivation ### _Related Work_ There are two commonly applied approaches to mitigate the effect of quantum noise. One is to adjust quantum circuits by noise-aware training [12] and mapping [11]. Noise-aware training is an adversary method, which injects noise into the training process so that the parameter of model can be learned from both datasets and devices. Noise-aware mapping is to minimize the sum of accumulated noise by changing the mapping from logical qubits to physical qubits. Another method is to estimate the ideal outputs by post-processing measurement data, e.g., zero-error noise extrapolation [17], probabilistic error cancellation[18], and virtual distillation[19]. However, these two kinds of approaches are based on noise at one moment, so we can hardly maintain the performance without redoing these methods as noise changes anytime. There are a few works addressing the fluctuating-noise issue, which can be quantitatively analyzed in two aspects: the noise of device and the distance between ideal results and noisy results. [20] evaluated the stability of NISQ devices with multiple metrics that characterize stability. [21, 22] defined Hellinger distance, computational accuracy and result reproducibility to expound the distance between ideal result and noisy observation. These works show the significance of reproducing results in a long-term execution on a quantum device. However, it is still not clear what effects the fluctuating noise will make on quantum applications. ### _Observation, Challenge and Motivation_ This section will provide our observations on the simulation performance of a quantum neural network model on a noisy quantum computer over a period of one year. **Observation 1: Fluctuating noise can collapse the model accuracy of a noise-aware trained QNN model.** Fig. 2 (a) shows the daily accuracy of a QNN model on the quantum processor in Fig. 1, which demonstrates that the accuracy can be varied significantly along with the fluctuating noise. The QNN model is trained using the noise-aware training method [12] based on the calibration (noise) data on day 1 (8/10/22). Its accuracy is over 80% from day 1 to day 22; however, when error rates increased on day 24, the accuracy decreased to 22%. This observation shows that the noise-aware design can obtain a robust quantum circuit to a certain range of noise, but the performance can be collapsed when the noise rate goes beyond a threshold. **Challenge 1: Noise on qubits can create breakpoints beyond the optimization surface, creating difficulties in training** Relying on training only to adapt to noise may miss the opportunity to find the optimal solution. Fig. 3(a)-(b) shows an example of the results of a quantum circuit with 2 parameters (x-axis and y-axis) in a perfect environment (simulation) and in a noisy environment (realistic). From the difference shown in Fig. 3(c), we can see that the breakpoints in the loss landscape are with much lower noise. Given the optimization started from a random point, in order to reach these breakpoints, it requires a dedicated learning rate for each parameter, which is almost impossible in a training algorithm. **Motivation 1: Not only relying on training but also involving compression to battle against quantum noise.** Looking closer at these breakpoints in Fig. 3(c), we observe that the parameter value of 0 creates these breakpoints. We also observe such breakpoints around other specific values, like \(\frac{\pi}{2}\), \(\pi\), \(\frac{2\pi}{2}\), etc. We further investigate the root cause and we found the improvement in performance is caused by the reduction of physical circuit length. More specifically, due to the transpilation (i.e., logical-to-physic qubit mapping), the logical quantum gate with different values will result in varied circuit lengths on physical qubits. Analog to the classical neural networks, the reduction of the network complexity is known as compression. Based on the above understanding, it motivates us to employ compression techniques to address the quantum noise. For the same noise setting as Fig. 2(a), we perform the model compression on Day 1, and results are reported in Fig. 2(b). It is clear that the results of compression (i.e., yellow points) are much better than the noise-aware training (i.e., blue points). However, we still observe a significant accuracy drop between March 15 to May 29. **Observation 2: Behaviors of fluctuating noise on different qubits has heterogeneity.** To explore the root cause of the accuracy drop, we investigate the change of CNOT noise on all pairs of qubits on three dates: (1) Feb. 12, (2) March 15, and (3) April 25. Fig.4 (a) reports the results. It is clear that the qubits on March 15 and April 25 have much higher noise than that on Feb. 12. A more interesting observation is that the fluctuating noise on different qubits has heterogeneity. Specifically, on Feb. 12, \(\langle q_{3},q_{4}\rangle\) has the highest noise, while \(\langle q_{1},q_{2}\rangle\) becomes the noisiest one on March 15 and April 25. Along with the heterogeneous Fig. 3: Noise-aware training may miss optimal solution: (a) Optimization surface of 2-parameter VQC under noise free environment. (b) Optimization surface of the same VQC under a noisy environment. (c) Difference between (a) and (b). Fig. 2: The accuracy of QNN on 4-class MNIST from August 2021 to August 2022 on IBM backend been using Qiskit Simulation. changes of noise on qubits, the compressed QNN model may lose its robustness, which causes the accuracy degradation between March 15 to May 29. **Motivation 2: Adding noise awareness in compression to battle against fluctuating quantum noise** To address the above challenges, only conducting noise-agnostic compression with the objective of minimizing circuit length is not enough; on the other hand, we need to take the heterogeneous noise on qubits into consideration. This motivates us to develop a "noise-aware compression" on QNNs, which can involve the noise level at each qubit to guide how the model will be compressed. Details will be introduced in Sec III-A. We use an example to illustrate the necessity of noise-aware compression. As shown in Fig. 4 (b), on March 15 and April 25, we observe significant changes in the noise of qubits, which makes the original compressed model suffer an accuracy drop from 79% to 22.5% and 56.5%. By using a noise-aware compression on these dates, we resume the accuracy to 38.5% and 80% on March 15 and April 25, respectively. With noise-aware compression, now, the problem is how frequently should we perform the compression. Due to the fluctuation of quantum noise, one straightforward idea is to leverage the noise-aware compression before using it, so that it can adapt to the new noise. However, this can be too costly. **Observation 3: Models can be re-utilized.** Let's see the original model in Fig. 4(b), which experienced a dramatic accuracy drop on March 15. However, after 9 days, on March 24, the accuracy of this model resumed to 80.5%. Therefore, the previous model can be re-utilized later. **Motivation 3: A model repository can avoid model optimization every day to improve efficiency.** The above observation inspires us to build a model repository to keep a set of models. At run time, instead of directly performing optimization (i.e., compression) for a new noise, we can first check if models in the repository can adapt to the noise. In this way, it is possible to reuse pre-optimized models and significantly reduce the optimization cost at run time. With the above observations and motivations, we propose a novel framework QuCAD in the following section to devise a noise-aware compression algorithm, build a model repository upon historical data offline, and manage it at run time. ## III Compression-Aided Framework This section will introduce our proposed compression-aided framework, namely QuCAD, to battle against fluctuating quantum noise. Before introducing details, we first formally formulate the problem as follows: Given a QNN model \(M\), the quantum processor \(Q\) with history calibration (noise) data \(D_{\mathrm{t}}\), the current calibration data \(D_{\mathrm{c}}\) of \(Q\), the problem is how to leverage the calibration data (i.e., \(D_{t}\) and \(D_{c}\)) to find a model \(M^{\prime}\) with the objective of maximizing the accuracy of \(M^{\prime}\) on \(Q\) with \(D_{c}\). ### _Framework Overview_ Fig. 5 shows the overview of the QuCAD framework. It contains 3 main components: (1) a noise-aware compression algorithm, (2) an offline model repository constructor, and (3) an online model repository manager. The noise-aware compression algorithm is the core of QuCAD in both offline and online optimizations. The offline optimization includes the following steps to build a model repository. We will first use the historical calibration data to obtain their corresponding performance for the given QNN model \(M\). Then, a clustering algorithm is developed to create several groups in terms of calibration data and corresponding model performance. The centroid of calibration data in each group (\(D^{\prime}\)) will be used to optimize model \(M\) the compression algorithm to generate the compressed model \(M^{\prime}\). The pair of \(\langle M^{\prime},D^{\prime}\rangle\) will be placed into the model repository. The online optimization will get the current calibration data \(D_{\mathrm{c}}\) of quantum computer \(Q\) as input. We match \(D_{c}\) with the existing calibration data \(D^{\prime}\) of items \(\langle M^{\prime},D^{\prime}\rangle\) in the model repository, aiming at finding the most similar one. The model repository manager will use the difference between calibration data \(D_{c}\) and \(D^{\prime}\) to make a judgment whether model \(M^{\prime}\) can be directly used under \(D_{c}\). If the distance is over a pre-set threshold then performance degradation is predicted, we will regard the current calibration data as a new centroid and generate a new model by noise-aware compression and put it into the model repository. Otherwise, we will output matched model directly. ### _Noise-Aware Compression_ Quantum neural network compression was recently proposed [23] to reduce circuit length, where an Alternating direction method of multipliers (ADMM) approach is applied. In this paper, we will also employ ADMM as the optimizer for noise-aware compression, and the new challenge here is how to involve noise awareness in the compression process. In the previous work, the authors conducted compression upon the logical quantum circuit. However, to involve noise in the compression of quantum gates, we need to fix the physic qubits of each quantum gate. _Therefore, we will take the quantum circuit after routing on restricted topology as input, instead of the logical quantum circuit._ Before introducing our proposed algorithm, we first define the notations and the optimization problem which will be used in ADMM. We denote \(\mathbf{T}\) as a table of compression-level, which are breakpoints in the example of _Motivation 1_. We denote the function of a VQC under a noise-free (a.k.a., perfect, denoted by \(p\)) environment as \(W_{p}(\mathbf{\theta})\) Fig. 4: Noise-aware compression is needed: (a) CNOT gate noise on three days. (b) Noise-aware compressing and tuning models on the three days in (a) and testing the on the following days. Fig. 5: Illustration of the proposed Compression-Aided Framework (QuCAD). where \(\mathbf{\theta}=[\theta_{1},\theta_{2},\cdots,\theta_{n}]\) are a set of trainable parameters, and \(\theta_{i}\) is the parameter of gate \(g_{i}\). With the consideration of noise, the function of VQC will be changed to \(W_{n}(\mathbf{\theta})\). On top of these, the deviation caused by noise can be defined as \(N(\mathbf{\theta})=W_{n}(\mathbf{\theta})-W_{p}(\mathbf{\theta})\). For a quantum gate \(g_{i}\), it is associated with a physic qubit \(q_{k}\) or a pair of physic qubits \(\langle q_{k},q_{l}\rangle\). For simplicity, we denote such an association as a function \(\langle q_{k},q_{l}\rangle=A(g_{i})\), and we use \(k=l\) to represent \(g_{i}\) is associated with one qubit \(q_{i}\). We denote \(\mathbf{C}\) as a table of calibration data, and the notation \(n_{k,l}\in\mathbf{C}\) or the function \(C(q_{k},q_{l})\) to represent the noise rate on qubit \(q_{k}\) and \(q_{l}\) (or \(q_{k}\) if \(k=l\)). Then, the problem can be formulated as below. \[\min_{\mathbf{\theta}}\quad W_{p}(\mathbf{\theta})+N(\mathbf{\theta}) \tag{1}\] Now, to enable using ADMM to perform noise-aware compression, we first decompose the optimization problem in Eq. 1 to two sub-problems and solve them separately: (1) maximize accuracy and (2) minimize the deviation caused by noise. The first subproblem can be solved by a gradient-based optimizer. For the second problem, we will use a set of auxiliary variables and an indicator function to resolve it, which will be introduced later. Therefore, we reformulate the optimization problem that can be solved by ADMM as below. \[\min_{\{\theta_{i}\}}\quad f(W_{p}(\mathbf{\theta}))+N(\mathbf{Z})+\sum_{\forall z_{i }\in\mathbf{Z}}s_{i}(z_{i}), \tag{2}\] where \(\mathbf{Z}\) is a set of auxiliary variables for subproblem decomposition and \(z_{i}\in\mathbf{Z}\) is corresponding to \(\theta_{i}\in\mathbf{\theta}\); function \(f\) represents training loss on the given dataset; \(\mathbf{T^{admm}}\) is gate-related compression table build on \(T\); and \(s_{i}(z_{i})\) is an indicator, which will indicate whether the parameter \(\theta_{i}\) will be pruned or not. In the \(r^{th}\) iteration of ADMM optimization, one key step is to determine whether or not to compress a parameter. According to the parameter \(\theta_{i}\), compression table \(T\), and noise data \(n_{k,l}\), we will build a mask. Fig. 6 illustrates the process to create the mask, which is composed of three steps. First, by comparing the parameter \(\theta_{i}\) with each compression level in table \(T\), we generate two tables: \(\mathbf{T^{admm}}\) and \(\mathbf{D}\). The \(i^{th}\) element in \(\mathbf{T^{admm}}\) is denoted as \(T_{i}^{admm}\), which is the nearest compression level of parameter \(\theta_{i}\); while \(d_{i}\) is the minimum distance between parameter \(\theta_{i}\) and any compression level. _Note that in a noise-agnostic compression [23], a mask will be generated by using table \(\mathbf{D}\). In the second step, we further consider gate noise and generate a priority table \(\mathbf{P}\)._ Notation \(p_{i}\in\mathbf{P}\) indicates the priority of gate \(g_{i}\) to be pruned; then, we have \(p_{i}=\frac{C(A(g_{i}))}{d_{i}}\), where \(A(g_{i})\) is the qubits associated with \(g_{i}\) and \(C(A(g_{i}))\) is the noise rate. Based on \(p_{i}\), we formulate the mask \(mask(g_{i},\mathbf{C})^{r}\) for gate \(g_{i}\) on the given calibration data \(\mathbf{C}\) in the \(r^{th}\) iteration as below. \[mask(g_{i},\mathbf{C})^{r}=\begin{cases}0&\text{ if }p_{i}^{r}<threshold\\ 1&\text{ if }otherwise.\end{cases} \tag{3}\] In the above formula, the mask equals \(1\) indicating that the gate \(g_{i}\) has a high priority, which is larger than a pre-set threshold, to be compressed. To maintain high accuracy, we will utilize the compression level \(T_{i}^{admm}\) if \(g_{i}\) is masked to be compressed.Based on these understandings, we define the indicator function \(s_{i}(z_{i})\): \[s_{i}(z_{i})=\begin{cases}0&\text{ if }z_{i}=T_{i}^{admm}\times mask(g_{i},\mathbf{C} )^{r}\\ &or\ mask(g_{i},\mathbf{C})^{r}=0\\ +\infty&\text{ if }otherwise.\end{cases} \tag{4}\] Note that \(s_{i}\) is used in Eq. 2 to restrict the value of \(z_{i}\). It requires its value to be 0 for a valid solution. In the above formula, we set \(s_{i}(z_{i})=0\) in two cases: (1) if \(mask(g_{i},\mathbf{C})^{r}=0\), indicating we do not require the compression on gate \(g_{i}\); or (2) \(\theta_{i}=T_{i}^{admm}\times mask(g_{i},\mathbf{C})^{r}\), indicating that the parameter \(\theta_{i}\) has to be compressed to be the compression level \(T_{i}^{admm}\). For each round, we will get \(\mathbf{\theta}^{r}\) and \(\mathbf{Z}^{r}\) alternately. At last, we will get the optimized parameters \(\mathbf{\theta}\) to minimize Eq. 1. Then, we will employ noise injection to fine-tune parameters \(\mathbf{\theta}\) to further improve the performance, where we will freeze the compressed parameters to not be tuned using the final \(mask\). ### _Offline Model Repository Constructor_ As discussed in _Motivation 3_, it is possible to use the noise-aware compression to perform optimization before using the QNN, but it is too costly and there exist opportunities to improve efficiency by building a model repository so that the model can be reused. In this subsection, we will explain how to build the repository using a modified noise-aware k-means clustering algorithm. There are two inputs of the model repository constructor: (1) offline calibration data, denoted as \(\mathbf{C}=[\mathbf{c_{1}},\mathbf{c_{2}},...,\mathbf{c_{n}}]\in R^{n\times d}\); and (2) the corresponding QNN accuracy under the calibrations, denoted as \(\mathbf{p}=[p_{1},p_{2},...,p_{n}]\in R^{n}\), where \(n\) is the number of calibration data and \(d\) is the total number of noise rates in each calibration data. Our objective is to split calibration data (\(\mathbf{C}\)) into \(k\) groups, and the samples in the same group are with similar calibration data and performance; meanwhile, the centroid \(\mathbf{r_{i}}\) is representative of each group (\(\mathbf{g_{i}}\)). Then, we can use the representative centroid \(\mathbf{r_{i}}\) to do noise-aware compression and the compressed model will be added to the repository. _Objective Function and Distance._ To achieve our goal, we first define performance-aware weight, which is \(\mathbf{w}=[w_{1},w_{2},...,w_{d}]\), where \(w_{j}\) is the absolute correlation coefficient \(\rho=|\frac{\text{cov}(X,Y)}{\sigma_{x}\sigma_{y}}|\) between the model performance \(\mathbf{p}\) and the \(j^{th}\) dimension in calibration data \(\mathbf{C}_{\cdot,\mathbf{j}}\). The weighted distance (noted as \(dist_{L1}^{w}\)) between two samples (\(\mathbf{c_{i}}\) and \(\mathbf{c_{j}}\))of calibration data can be defined as \[dist_{L1}^{w}(\mathbf{c_{i}},\mathbf{c_{j}})=dist_{L_{1}}(\mathbf{w}\cdot \mathbf{c_{i}},\mathbf{w}\cdot\mathbf{c_{j}}) \tag{5}\] where \(dist_{L_{1}}\) is the Manhattan distance between two vectors; The objective function is designed to partition the data into \(K\) clusters such that the sum of weighted Manhattan (\(L_{1}\)) absolute errors (WSAE) of all their clusters is minimized. Therefore, the objective function WSAE is designed as: \[WSAE=\sum_{\mathbf{g_{i}}\in\mathbf{C}}\sum_{\mathbf{v}\in\mathbf{g_{i}}}dist_{L _{1}}^{w}(\mathbf{r_{i}},\mathbf{c}) \tag{6}\] \(\mathbf{G}\) is all groups, \(\mathbf{r_{i}}\) is the representative of group \(\mathbf{g_{i}}\in\mathbf{G}\), and \(\mathbf{c}\in\mathbf{g_{i}}\) is the candidate calibration in group \(\mathbf{g_{i}}\). Since the noise is considered in model performance, the clustering not only considers the value of noise but also the effects of noise on the given QNN model. ### _Online Model Repository Manager_ After building the model repository, the next question is how to use it for online algorithms. We provide the following guidance to Fig. 6: Noise-aware mask generation in ADMM process. use the repository efficiently. **Guidance 1**: _The cluster results can help to judge whether to generate new models into the model repository manager. At the offline stage, we can get the average weighted distance:_ \[\overline{(dist_{L1}^{v})_{i}}=\frac{\sum_{\forall\mathbf{c}\in\mathbf{g_{i}}} dist_{L_{1}}(\mathbf{r_{i}},\mathbf{c})}{n_{i}}\] _between the centroid(_\(\mathbf{r_{i}}\)_) and all samples (_\(\forall\mathbf{c}\in\mathbf{g_{i}}\)_) in the_ \(i^{th}\) _cluster, where_ \(n_{i}\) _is the number of samples in the_ \(i^{th}\) _cluster. We set_ \(max_{i}(\overline{(dist_{L1}^{v})_{i}})\) _as a threshold_ \(th_{w}\) _to decide whether to add a new centroid (i.e., new representative) in the model repository. If the_ \(min_{j}(disj)>th_{w}\) _where_ \(disj\) _is the_ \(dist_{L1}^{w}\) _distance between the_ \(j^{th}\) _centrol and the current calibration data, we will add the current calibration data to the model repository._ **Guidance 2**: _The cluster results can be utilized to predict the performance of the given model with current calibration data. Specifically, we can obtain the average accuracy of each cluster, say_ \(\overline{acc_{i}}\) _for the_ \(i^{th}\) _cluster. According to users' requirement on QNN model accuracy_ \(A\)_, we can set cluster_ \(g_{i}\) _as an invalid cluster if its average accuracy_ \(a\bar{c}c_{i}\) _is less than_ \(A\)_. Then, at the online stage, if the current calibration matches the centroid in an invalid cluster, we will set the current calibration data as an invalid data, and output a failure report._ ## IV Experiments ### _Experiments Setup_ **Datasets and model.** We evaluate our framework on three classification tasks. (1) We extract 4 class (0,1,3,6) from MNIST [24] with the former 90% samples for training and latter 200 samples for testing. To process MNIST data, we apply angle encoding [25] to encode \(4\times 4\) images to 4 qubits, and adopt 2 repeats of a VQC block (4RY +4CRY +4RY +4RX +4CRX +4RX +4RZ + 4CRZ +4CRZ) as the original model. (2) We extract 1500 samples of the earthquake detection dataset from FDSN [26]. Each sample has a positive or negative label. We utilize 90% and 10% samples for training and testing, respectively. We encode features to 4 qubits and employ the same VQC as MNIST. (3) We use Iris [27] dataset with 66.6% and 33.4% samples for training and testing. Features are encoded to 4 qubits with 3 repeats of VQC blocks. **Calibrations and Environment Settings.** We pull history calibrations from Aug. 10, 2021 to Sep. 20, 2022 from IBM backend (ibm_belem) using Qiskit Interface. The front 243 days are used for offline optimization and the remaining 146 days' data are used for online tests. We generate noise models from history calibration data and integrate them into Qiskit noise simulator for online simulation. Besides, we also deploy QuCAD on ibm-jakarta and evaluate the output model of QuCAD on a real IBM quantum processor, ibm-jakarta. Our codes are based on Qiskit APIs and Torch-Quantum [28]. **Competitors.** We employ different approaches for comparison, including: (1) Baseline: training in a noise-free environment without optimization. (2) Noise-aware Training Once [12]: applying noise injection on the first day for training. (3) Noise-aware Training Everyday: extend the noise-aware training everyday. (4) One-time Compression[23]: applying compression with the objective of minimizing circuit length on the first day. (5) QuCAD w/o offline: generating the models by our framework without an offline stage. (6) QuCAD: generating the models by our framework during the offline and online stages. ### _Main Results of our proposed QuCAD_ **Effective evaluation on noisy simulation.** Table I reports the comparison results of different methods on MNIST, Iris, and earthquake detection datasets. Columns "Mean accuracy" and "Variance" gives the statistical information of model accuracy on the continuously 146 days. Column "Days over 0.8" stands for the number of days that the model accuracy is higher than 80%, which is similar to "Days over 0.7" and "Days over 0.5" columns. From this table, we can clearly see that our proposed QuCAD outperforms all competitors. Specifically, on these 3 datasets, QuCAD achieves improvements of 16.32%, 38.88%, and 15.36% respectively, compared with the baseline. Although there exists one case that the 'days over 0.8' of 'QuCAD w/o offline' is 1 day more than that of 'QuCAD' on Iris, QuCAD has many days to have accuracy over 70%. Besides, QuCAD has the lowest variance except for the baseline on Iris, showing the stability of QuCAD. Kindly note that the mean accuracy of the baseline on Iris is much lower than QuCAD. We also observed that QuCAD outperforms competitors on the number of days over different accuracy requirements, which again demonstrates the effectiveness of our framework. Compared with noise-aware training, even one-time compression has a significant improvement on all datasets, which validates our observation in Fig. 3. On the other hand, QuCAD w/o offline outperforms one-time compression, indicating that online adaptation is needed. Furthermore, compared with 'QuCAD w/o offline', QuCAD achieves improvements of 3.36%, 1.14%, and 1.41%, showing the effectiveness of offline optimization in QuCAD. **Efficiency evaluation.** We recorded the training time at the online stage in Fig. 7 on 4-class MNIST. In the figure, the bars represent the mean accuracy (i.e., right axis) and each point with a number corresponds to a normalized training time (i.e., left axis). From the results, we can see that QuCAD can achieve 146\(\times\) and 110.3\(\times\) speedup over "compression everyday" and "noise-aware train every data", respectively. This shows the efficiency of our framework, which mainly comes from the reduction of the number of online optimization. More specifically, the centroids generated offline can well represent the calibrations at the online stage if the distribution of calibrations doesn't change much. **Evaluation on real quantum computers.** We also evaluate QuCAD on the earthquake detection dataset using IBM quantum processor ibm-jakarta with different calibration data at different time. Results are shown in Fig. 8. QuCAD can consistently outperform the two competitors by 13.7% and 12.52% on average. Besides, we can see that the accuracy of QuCAD on different days is more stable than others, which reflects our methods can adapt QNN models to fluctuating noise. ### _Ablation Study_ **QuCAD vs. Practical Upper Bound.** We further investigate the performance of 8 representative days in Fig. 9(a). We apply the result of noise-aware compression every day as a practical upper bound. From the results, we can observe that QuCAD has a competitive performance compared to the practical upper bound, showing QuCAD can get approximate optimal results. **Noise-Aware vs. Noise-Agnostic Compression.** We further evaluate the proposed compression algorithm on those 8 representative days, as shown in Fig. 9(b). Results show that noise-aware compression can outperform noise-agnostic compression on most days, showing the effectiveness of our proposed noise-aware compression. We also observe both compression approaches obtained the same accuracy on 5/4 and 7/14. There are two possible reasons: (1) there is no great difference among qubits; and (2) The noise level is small and the simple compression is enough to get a good performance. **Model repository constructor.** We also did an ablation study on the clustering algorithm developed in the model repository constructor. We compare our proposed noise-aware distance \(dist_{L,1}^{w}\)and the standard 'L2 norm' distance. Results reported in Table II show that our method can get 2.89% higher mean accuracy of 6 clusters on average and obtain 2.23% accuracy gain on that for all samples consistently. Results indicate that our proposed method can improve the quality of the centroids and make centroids represent other samples better in a cluster. ## V Conclusion In this work, we reveal the fluctuating noise in quantum computing and it will significantly affect the performance of quantum applications. To battle against fluctuating noise, we further observe that the high noise level may create breakpoints in the loss surface, and in turn, the noise-aware training may find inferior solutions. By investigating the breakpoints, we observe that quantum neural network compression can be a hammer to the noise issue. And we build a compression-aided framework, namely QuCAD, which can automatically adapt a given model to fluctuating quantum noise. Evaluations on MNIST, earthquake detection dataset, and Iris show the effectiveness and efficiency of QuCAD. specifically, QuCAD can obtain stable performance on the earthquake detection task using a real IBM quantum processor.
2308.11800
Complex-valued neural networks for voice anti-spoofing
Current anti-spoofing and audio deepfake detection systems use either magnitude spectrogram-based features (such as CQT or Melspectrograms) or raw audio processed through convolution or sinc-layers. Both methods have drawbacks: magnitude spectrograms discard phase information, which affects audio naturalness, and raw-feature-based models cannot use traditional explainable AI methods. This paper proposes a new approach that combines the benefits of both methods by using complex-valued neural networks to process the complex-valued, CQT frequency-domain representation of the input audio. This method retains phase information and allows for explainable AI methods. Results show that this approach outperforms previous methods on the "In-the-Wild" anti-spoofing dataset and enables interpretation of the results through explainable AI. Ablation studies confirm that the model has learned to use phase information to detect voice spoofing.
Nicolas M. Müller, Philip Sperl, Konstantin Böttinger
2023-08-22T21:49:38Z
http://arxiv.org/abs/2308.11800v1
# Complex-valued neural networks for voice anti-spoofing ###### Abstract Current anti-spoofing and audio deepfake detection systems use either magnitude spectrogram-based features (such as CQT or Melspectrograms) or raw audio processed through convolution or sinc-layers. Both methods have drawbacks: magnitude spectrograms discard phase information, which affects audio naturalness, and raw-feature-based models cannot use traditional explainable AI methods. This paper proposes a new approach that combines the benefits of both methods by using complex-valued neural networks to process the complex-valued, CQT frequency-domain representation of the input audio. This method retains phase information and allows for explainable AI methods. Results show that this approach outperforms previous methods on the "In-the-Wild" anti-spoofing dataset and enables interpretation of the results through explainable AI. Ablation studies confirm that the model has learned to use phase information to detect voice spoofing. Nicolas M. Muller, Philip Sperl, Konstantin Bottinger Fraunhofer AISEC [email protected] **Index Terms**: voice anti-spoofing, audio deepfake detection, complex neural network ## 1 Introduction Artificial Intelligence (AI) is advancing at a rapid pace, and has enabled the development of numerous good and helpful applications that are changing the way we live, work, and interact with each other. However, along with these positive advancements, new threats have emerged, particularly in the form of deepfakes and spoofs. Deepfakes are computer-generated images, videos, or audio that are created using AI algorithms to manipulate and alter original content. Although deepfakes can be used for harmless fun, they can also be misused for malicious purposes such as creating fake news, information campaigns, slander, or fraud. This is concerning as deepfakes can be highly convincing, making it challenging to distinguish between genuine and fake content. Spoofing, on the other hand, involves creating a fake or manipulated version of oneself to circumvent biometric identification systems such as facial recognition or fingerprint scanners. This has significant implications, especially in the realm of security, as it can compromise the integrity of identity verification systems. As a result, the detection of spoofed or faked content is becoming increasingly important. It is crucial to develop effective methods for detecting such misuse of AI in order to ensure that these technologies are used ethically and responsibly. Using Machine Learning (ML) for voice anti-spoofing requires adequate preprocessing because human speech has long-range temporal dependencies, with one second of audio usually represented by \(16,000\) single data points or more. Previous approaches to voice anti-spoofing have taken one of two approaches to audio preprocessing. Some have used spectral preprocessing, transforming the time-domain waveform into a magnitude spectrogram using the short-time Fourier transform (STFT) or similar techniques. This approach has shown good performance but has one key disadvantage: it discards phase information from the spectrogram. This phase information is crucial for audio quality and voice naturalness [1], and in the domain of speech-to-text (STT), it is laboriously recreated using Griffin-Lim or neural vocoders [1, 2, 3]. As bad phase is very audible1, we argue that it is a useful feature that should not be discarded. Footnote 1: Audio examples available at google.github.io/phase-prediction. The second approach to voice anti-spoofing is to design models that process raw audio directly, which have been shown to be more effective [4, 5, 6], but lack transparency because explainable AI methods (XAI) such as saliency maps require input data with spatial dimensions (i.e. at least two-dimensional input). In this paper, we propose a new approach to voice anti-spoofing that combines the benefits of both previous approaches. We transform input audio into a complex-valued spectrogram using the constant-Q transform, a technique closely related to the STFT, which yields a complex-valued frequency representation. This representation is mathematically equivalent to the time-domain representation of the input audio, but more suited to machine-learning algorithms. We then process this frequency representation using a complex-valued convolutional neural network, which allows us to process all information present in the audio file, without the need to discard the phase. We demonstrate that our proposed approach outperforms both magnitude spectrogram-based models and raw-feature models. Our approach is conceptually and architecturally simple, which sets it apart from some of the recent state-of-the-art raw models. Moreover, it enables the use of explainable AI techniques. In summary, our contributions to the field of voice anti-spoofing can be outlined as follows: * We emphasize the significance of phase information in the complex Short-Time Fourier Transform (STFT) output, which has been neglected in previous research. * Based on this insight, we propose a corresponding complex-valued input feature and neural architecture for jointly processing both magnitude and phase information. * We evaluate our approach and demonstrate its superiority over both magnitude spectrogram-based models and raw-based models. We provide an online web interface2 where one can test arbitrary input, including YouTube videos, against our model. Footnote 2: [https://deepfake-total.com](https://deepfake-total.com) ## 2 Previous Work As previously mentioned, voice anti-spoofing traditionally employs one of two feature preprocessing approaches. The first approach involves using magnitude-spectral features like the constant-Q transform (CQT) [7], log or mel-scaled spectrograms [8]. These techniques use the complex-valued STFT of a time-domain audio signal as a foundation, extracting the magnitude and discarding phase information. The result is then squared, scaled, and possibly binned using the mel-scale [8] to mimic the human ear's perception. Previously suggested voice anti-spoofing architectures have then employed neural components such as convolutions, attention mechanisms, recurrence, or transformer blocks [9, 10, 11, 12, 13] to process the resulting spectrogram. These models have shown good performance, but no longer achieve state of the art. The second approach involves directly processing the time-domain "raw" audio using either neural convolutions on the audio file itself [14] or stacks of sinc-layers [15] corresponding to rectangular band-pass filters. Max-pooling is often used [5] to avoid phase mismatch between the audio waveform and the sinc wavelets. The result is then processed using stacks of convolutions and gated recurrence (RawNet2) [5], more advanced architectures like spectro-temporal graph attention neural networks (RawGat-ST) [4], or differentiable architecture search [6]. Although these "raw" models have been shown to deliver outstanding performance [4, 5, 6], they lack explainability. This is because existing XAI techniques such as saliency maps [16] or Smooth Grad [17] are designed for spatially-dimensioned input, while "raw" audio is a one-dimensional vector. As a result, it becomes challenging to comprehend and trust the models' judgments. Among other disadvantages, this impedes the detection of "learning shortcuts" [18], i.e. highly predictive, but artificial correlations between input and target which do not reflect real-world causality. Detecting such shortcuts is particularly crucial in voice spoof detection, where they have already been identified [19] and may result in a lack of generalizability to real-world scenarios [20]. Thus, there is an urgent demand for explainable anti-spoofing models. ## 3 Proposed Approach ### Complex-valued CQT spectrograms In digital signal processing, an input audio signal \(X=[X[0],X[1],\ldots,X[n]]\) is represented in the time domain as a series of scalar values \(X[t]\in[-1,1]\in\mathbb{R}\), which correspond to measurements of air pressure at time \(t/s\), where \(s\) is the sampling rate (e.g., 16 kHz or 16,000 samples per second). To convert this signal into a frequency representation \(Z\), one may use the Short Time Fourier Transform, which is a bijective transform: \[Z[t,k]=\sum_{n=0}^{N-1}W[n]X[n+t]e^{-2\pi iknN^{-1}} \tag{1}\] Here, \(X\) is the time-domain signal, and \(W\) is a window such as the Gaussian, Hann, or Hamming window of size \(N\). The frequency-domain representation \(Z\) is a complex-valued, two-dimensional vector, where \(t\) is the temporal and \(k\) the frequency index. Elements in \(Z\) are complex-valued scalars, i.e. \(Z[t,k]=\alpha e^{i\theta}\in\mathbb{C}\), where \(\alpha\in\mathbb{R}\) is the magnitude and \(\theta\in[0,2\pi[\) the phase. Although \(Z\) is better suited for neural processing than the corresponding time-domain representation \(X\), it also has its own drawbacks: the uniform time and frequency resolution for all frequency bins \(k\) does not align with the non-linearities of the human auditory system [21, 22]. To address this issue, we employ the constant Q transform (CQT) [7, 23] which processes the same number of cycles \(Q\) for each frequency and spaces the frequency bins \(k\) geometrically (i.e., higher frequencies are farther apart). Therefore, for high frequencies \(k\), CQT employs smaller window sizes \(N_{k}\) (and thus higher time resolution), while for lower frequencies, it employs larger window sizes and thus larger frequency resolution. Thus, instead of using the STFT, we convert time-domain audio \(X\) into a complex-valued CQT spectrogram: \[Z_{Q}[t,k]=\frac{1}{N_{k}}\sum_{n=0}^{N_{k}-1}W_{k}[n]X[n+t]e^{-2\pi iQnN_{k}^ {-1}} \tag{2}\] Previous work has already shown that magnitude-based CQT is better suited to voice antispoofing than magnitude-based STFT [24], which motivates our approach. Finally, we convert the complex-valued CQT-spectrogram into a log representation by means of the following transformation: \[\mathbb{C} \rightarrow\mathbb{C} \tag{3}\] \[|z|e^{i\theta} \mapsto\text{max}\left(\epsilon,-\text{log}_{e}|z|+c\right) \cdot\alpha\cdot e^{i\theta} \tag{4}\] To account for the logarithmic perception of sound level by the human ear, we log-scale the magnitude of the complex number while keeping the phase intact. However, \(\text{log}_{e}|z|\) can be negative, because \(\text{log}_{e}|z|e^{i\theta}=-\text{log}_{e}|z|e^{i\theta+i\pi}\), leading to ambiguity. To address this, we apply a lower threshold of \(\epsilon>0\) to ensure that the magnitude remains positive. Additionally, to ease model training, we introduce trainable parameters \(\alpha,c\in\mathbb{R}^{>0}\) to scale the magnitude. In our experiments, these converge to approximately \(\alpha=0.15\) and \(c=-0.3\). To summarize, we utilize CQT followed by eq. (4) to generate complex-valued CQT log-spectrograms (C-CQT). ### Complex-valued neural networks Complex-valued neural networks (CVNN) are networks where both inputs \(X\) and weights \(\theta\) are complex numbers \(a+ib\in\mathbb{C}\). Apart from that, CVNNs rely on many of the same fundamental components as traditional real-valued ones. For instance, linear layers, convolutions, and simple recurrent networks like RNN operate identically in both types of networks. However, more complex components such as attention and recurrence, such as GRU [25], need to be adapted, since typical activation functions like _sigmoid_, _tanh_, and _softmax_ cannot be applied directly to complex-valued scalars [26]. For example, the complex _ReLU_ function can be implemented as \[CReLU(x)=\text{max}(0,\Re(x))+\text{max}(0,\Im(x)) \tag{5}\] where \(\Re\) and \(\Im\) denote the real and imaginary parts of a complex number. In supervised classification, class scores \(y\) for \(n\) classes can be derived from complex-valued logits \(z\) as follows: \[\text{softmax}(|z|)_{i}=\frac{e^{|z_{i}|}}{\sum_{j=i}^{n}e^{|z_{j}|}} \tag{6}\] Classes with high probability are represented by logits with a large magnitude. These models, like their real counterparts, are trained using gradient descent [26] through the use of Wirtinger Calculus [27]. ### Proposed Architecture In order to process complex-valued, frequency-domain audio input, we use a complex convolutional network. It consists of four blocks of convolutions, where each block is composed of two-dimensional complex convolutions (kernel size \(3\), stride \(2\) and padding \(1\)), complex ReLU and complex Batch-Normalisation. This is followed by linear projection, which consists of three complex-valued linear layers with CReLU activation and Dropout of \(40\%\). This is followed by two-dimensional complex time pooling. The output is a two-class complex vector of shape \((B,2)\), to which we apply eq. (6) in order to obtain real-valued class scores. There are two target classes: class \(0\), which corresponds to bonafide audio, and class \(1\), which corresponds to spoofed audio. The input frequency-domain audio has shape \(B,F,T\) where \(B\) is the batch-size, \(F\) the number of frequency bins, and \(T\) the number of time bins. The convolutional stack outputs a tensor \(B,C,L\) where \(C\) is the number of output channels and \(L\) is the aggregated time. Figure 1 provides an overview. ## 4 Evaluation ### Datasets We are utilizing two datasets for our experiments. The first dataset is the Logical Access (LA) section of the ASVspoof 2019 dataset [28]. This dataset is widely used in related research [4, 5, 6, 9, 10, 11, 12, 13] and is considered one of the most established anti-spoofing datasets. It includes audio files that are either genuine human speech recordings (bona-fide) or manipulated/synthesized audio (spoofed). The spoofed audio files are generated using 19 different Text-To-Speech (TTS) synthesis algorithms that are considered a threat to the authenticity of human voice in terms of spoofing detection. Therefore, the spoofed audio files are labeled as "attacks" by ASVspoof. The dataset consists of 19 attackers, labeled as A1 to A19, and for each attacker, there are 4914 synthetic audio recordings and 7355 genuine samples. Furthermore, we utilize the "In-the-Wild" (ITW) dataset [20], which comprises \(37.9\) hours of audio recordings, either spoofed (\(17.2\) hours) or authentic (\(20.7\) hours), obtained from \(58\) English-speaking celebrities and politicians via online video sharing platforms, such as YouTube. It tries to match the speaking style for each pair of spoofed and authentic instance to prevent the model from distinguishing spoofs based on extraneous characteristics (also called "machine learning shortcuts"), such as speaking style, background noise, or setting. For instance, for a spoofed speech by Barack Obama, an authentic speech was also included. Our objective is for the model to distinguish spoofed audio based on either disfluencies that indicate poor naturalness or artifacts resulting from the text-to-speech (TTS) process. Since our primary concern is the real-world performance of the models on unseen audio recordings, we train them on the entire ASVspoof dataset (all splits) and assess their generalization abilities using the "In-the-Wild" dataset. ### Data-augmentation and Hyperparameters Previous research has identified a significant learning shortcut in the ASVspoof 2019 dataset, whereby the duration of silence in an audio file is highly correlated with its corresponding label. This correlation has led to an overestimation of anti-spoofing system performance [19]. To obtain a realistic estimate of the anti-spoofing model performance, it is crucial to eliminate this shortcut. We address this issue by following the suggestions made by related work [19, 30] and trim the beginning and end silences of an audio file. Moreover, we randomly select a 2-second segment from the remaining audio to ensure that all audio files have equal length. This prevents our models from using the presence or position of the cut-off as a new learning shortcut. We apply this technique to all subsequent analyses. In addition, inspired by the widespread use of data augmentation in the image domain, we employ the following audio data augmentations in all subsequent analyses. By doing so, we further aim to avoid shortcuts, model overfitting, and promote model generalization. First, we use Adversarial Retraining [31]. Namely, we employ the Fast Gradient Sign Method (FGSM) to craft adversarial examples with a probability of \(20\%\) and a magnitude of \(0.25\%\) of the input magnitude and supply these as additional training examples. This method has been shown to improve model generalization [31] and regularization [32]. Second, we use audio augmentations [33] such as room impulse response, frequency masking, pitch- and timeshift, gain, high, low- and bandpass filters, polarity inversion, and clipping to diversify the input data with a probability of \(20\%\). Third, again with a probability of \(20\%\), we partially encode the input using MP3, ulaw, and alaw codecs to perform compression. Lastly, we add random clips of noise and music to the audio files with a probability of \(5\%\) by utilizing the MusDB18 [34] and Noise ESC 50 [35] datasets. We utilize the Adam optimizer with a learning rate of \(5\cdot 10^{-3}\) to train all models. The models are trained for \(25\) epochs with a weight decay of \(10^{-6}\) and a batch-size of \(32\). To prevent overfitting, we employ early stopping with a patience of \(3\) epochs and a minimum delta of \(5\cdot 10^{-4}\). We implement the models using Python and PyTorch. For the Constant-Q Transform (CQT), we use a hop size of \(32\) samples with the "Hann" windowing function. We train all models using an Nvidia DGX-A100 server, which is equipped with eight A100 GPUs, each having a memory of 40GB, and a total server memory of 1024GB. It features two AMD Rome 7742 processors, each with 64 cores. Figure 1: Our proposed complex-valued architecture. ### Evaluation and Results We adopt the Equal Error Rate (EER) as the performance metric for our model evaluation, consistent with previous studies [4, 5, 6, 28, 36]. EER is the point on the Receiver Operating Characteristic (ROC) curve where the false acceptance rate and false rejection rate are equal. For each experimental configuration, we conduct three independent trials and report the mean and standard deviation of the EER. Table 1 summarizes the results of our proposed model compared to models from related work. We observe the following: Firstly, our complex-valued model demonstrates an absolute improvement over related work by about \(3\%\) EER when compared to "raw" features and \(10\%\) EER when using magnitude-based CQT features. Secondly, we observe the least amount of overfitting, as indicated by the small gap between the training and testing performance. ### Ablation Study In order to evaluate the impact of the phase information, we perform an ablation study where we keep all parameters for our proposed model, but discard or randomize the phase information from the complex spectrogram. Table 2 presents the results. We observe that the removal of phase information ("zero phase") results in a \(4\%\) degradation in model performance with respect to EER. This suggests that the proposed model has indeed learned to detect spoofing attacks by utilizing the mismatch between phase and magnitude information to some extent. Furthermore, randomizing the phase information causes an additional \(4\%\) decrease in performance with respect to EER. We presume that this is due to the fact that the model not only lacks phase information, but also has to cope with a significant amount of noise when dealing with randomly generated phase information. ### Explainable AI Our model allows the application of explainable AI techniques such as saliency maps [16] and Smooth Grad [17]. These techniques allow us to visualize how our model processes audio in the frequency domain, thereby enabling us to gain insight into the decision-making process of our model. To demonstrate the effectiveness of these techniques, we apply Smooth Grad and present an exemplary output in Figure 2. Our analysis shows that the model does not rely on any obvious shortcuts, such as the duration of silence[19] or other artifacts such as sampling or ringing issues in the upper frequency bands. Instead, the model focuses on the speech signal itself, as evidenced by the red XAI-overlay coinciding with the spectro-temporal bins containing descriptive features. ## 5 Conclusion and Future Work This paper introduces a novel approach to voice anti-spoofing, which involves utilizing complex-valued features and complex-valued neural networks. This approach is motivated by the fact that magnitude-based feature extraction discards phase information, which is difficult to spoof yet crucial for producing natural-sounding synthesized speech, thereby constituting a useful input feature to voice anti-spoofing systems. Building on previous research, we thus propose using the complex-valued Constant-Q Transform (C-CQT) as a new input feature and suggest a corresponding complex-valued neural architecture. Our proposed approach not only outperforms previous related work but also allows for explainability through established XAI-methods, which is lacking in "raw"-feature-based models. Through ablation studies, we demonstrate that our model has effectively learned to use phase information to distinguish between spoofed and bona-fide audio. These results indicate the potential of our approach in improving the accuracy of voice anti-spoofing and advancing the understanding of the underlying decision-making process. In summary, we suggest an effective architecture that can be useful for anti-spoofing purposes. Despite the simplicity of our current model, it already surpasses the performance of related works that employ more sophisticated components. We are confident that incorporating further model refinements would be straightforward and could potentially enhance the ability to detect spoofed voice signals. \begin{table} \begin{tabular}{l l|l l|l l} \hline \hline Model Name & Feature Type & EER Test ITW & EER Train & Epoch Time (s) & Num. Parameters \\ \hline Proposed Model & C-CQT & **26.95\(\pm\)3.12** & 12.382\(\pm\)6.58 & 276.6\(\pm\)6.5 & 2,459,492 \\ CRNN Spoof [14] & Raw & 29.90\(\pm\)4.33 & 8.103\(\pm\)0.59 & 177.0\(\pm\)5.0 & 3,330,562 \\ MesoNet [12] & CQT & 37.05\(\pm\)3.93 & 11.496\(\pm\)0.19 & 187.0\(\pm\)21.2 & 11,698 \\ RawGat-ST [5] & Raw & 39.29\(\pm\)2.41 & 11.802\(\pm\)0.12 & 402.5\(\pm\)1.1 & 440,810 \\ RawNet2 [4] & Raw & 40.00\(\pm\)0.25 & 11.680\(\pm\)0.02 & 113.4\(\pm\)5.9 & 17,648,770 \\ LCNN [14] & Mel-Spec & 55.07\(\pm\)7.09 & 21.575\(\pm\)1.82 & 170.8\(\pm\)12.2 & 178,306 \\ Deep ResNet [29] & Mel-Spec & 58.80\(\pm\)0.23 & 36.21\(\pm\)0.65 & 192.7\(\pm\)6.8 & 111,874 \\ \hline \hline \end{tabular} \end{table} Table 1: Model evaluation results on the “In-the-Wild” dataset. The results are averaged over three independent runs, with the standard deviation displayed. \begin{table} \begin{tabular}{l l l l} \hline \hline Model Name & Phase & EER Test ITW & EER Train \\ \hline Proposed Model & full & **26.95\(\pm\)3.12** & 12.38\(\pm\)6.58 \\ & zero & 31.29\(\pm\)1.31 & 5.94\(\pm\)0.37 \\ & random & 35.79\(\pm\)0.13 & 8.09\(\pm\)0.18 \\ \hline \hline \end{tabular} \end{table} Table 2: Ablation study results for the C-CQT feature: full phase retention, random phase selection, or zero assignment. Figure 2: SmoothGrad [17] applied on an instance from the ASVspoof dataset.
2304.09424
Loss Minimization Yields Multicalibration for Large Neural Networks
Multicalibration is a notion of fairness for predictors that requires them to provide calibrated predictions across a large set of protected groups. Multicalibration is known to be a distinct goal than loss minimization, even for simple predictors such as linear functions. In this work, we consider the setting where the protected groups can be represented by neural networks of size $k$, and the predictors are neural networks of size $n > k$. We show that minimizing the squared loss over all neural nets of size $n$ implies multicalibration for all but a bounded number of unlucky values of $n$. We also give evidence that our bound on the number of unlucky values is tight, given our proof technique. Previously, results of the flavor that loss minimization yields multicalibration were known only for predictors that were near the ground truth, hence were rather limited in applicability. Unlike these, our results rely on the expressivity of neural nets and utilize the representation of the predictor.
Jarosław Błasiok, Parikshit Gopalan, Lunjia Hu, Adam Tauman Kalai, Preetum Nakkiran
2023-04-19T05:16:20Z
http://arxiv.org/abs/2304.09424v2
# Loss minimization yields multicalibration ###### Abstract Multicalibration is a notion of fairness that aims to provide accurate predictions across a large set of groups. Multicalibration is known to be a different goal than loss minimization, even for simple predictors such as linear functions. In this note, we show that for (almost all) large neural network sizes, optimally minimizing squared error leads to multicalibration. Our results are about representational aspects of neural networks, and not about algorithmic or sample complexity considerations. Previous such results were known only for predictors that were nearly Bayes-optimal and were therefore representation independent. We emphasize that our results do not apply to specific algorithms for optimizing neural networks, such as SGD, and thus they should not be interpreted as "fairness comes for free from optimizing neural networks". ## 1 Introduction Accuracy and multicalibration (MC) are different notions. Accuracy is typically framed as loss minimization. For simplicity, consider the squared loss of a predictor \(\ell(f):=\mathbb{E}[(f(x)-y)^{2}]\), with bounded labels \(y\in\{0,1\}\) and examples \((x,y)\in\mathcal{X}\times\mathcal{Y}\) that are drawn from an arbitrary joint distribution \(\mathcal{D}\). A predictor is a function \(f:\mathcal{X}\to[0,1]\) which assigns to each point \(x\) a probability \(f(x)\) which is the estimated probability that the label is \(1\). The notions of multicalibration, introduced in the work of Hebert-Johnson et al. (2018) is a notion of fairness that applies to every subgroup in a family \(\mathcal{C}\). Informally, it asks that the predictions be calibrated even conditioned on membership in \(\mathcal{C}\). **Definition 1.1** (Multicalibration (Kim et al., 2022; Hebert-Johnson et al., 2018)).: _Let \(\alpha>0\) and \(\mathcal{C}\) be a class of auditor functions \(c:\mathcal{X}\times[0,1]\to[0,1]\). The predictor \(f:\mathcal{X}\to[0,1]\) is \((\mathcal{C},\alpha)\)-multicalibrated or \((\mathcal{C},\alpha)\)-MC if for all \(c\in\mathcal{C}\),_ \[\Big{|}\,\mathbb{E}_{x,y}\left[c\big{(}x,f(x)\big{)}\cdot\big{(}y-f(x)\big{)} \right]\Big{|}\leq\alpha.\] _When \(\mathcal{C}\) is clear from context, we say that \(f\) is \(\alpha\)-MC for brevity. 1_ Footnote 1: The MC definition above is version due to Kim et al. (2022, Appendix 1), which was also used by Deng et al. (2023); Dwork et al. (2022). The original definition (Hebert-Johnson et al., 2018; Gopalan et al., 2022) considers only those \(c\) that can be factored as \(c(x,f(x))=g(x)w(f(x))\) where \(g:\mathcal{X}\to[0,1]\) and \(w:[0,1]\to[0,1]\). For the setting where \(\mathcal{C}\) is a family of neural nets, the general definition is more natural, since it amounts to both \(x\) and \(f(x)\) being inputs to an auditor neural net. When \(c\) maps to \(\{0,1\}\) values, it can be viewed as defining a _group_ which is a subset of the domain \(\mathcal{X}\) and MC means that \(\mathbb{E}[y]\approx\mathbb{E}[f(x)]\) conditioned on membership in this group, where the degree of closeness depends on the size of the group. Good calibration is guaranteed for any group of sufficient likelihood that can be computed by the classifier family. We also consider the weaker notion of multiaccuracy in expectation, where the auditor \(\mathcal{C}\) does not have access to the predictions. **Definition 1.2** (Multiaccuracy in expectation (Hebert-Johnson et al., 2018)).: _Let \(\alpha>0\) and \(\mathcal{C}\) be a class of auditor functions \(c:\mathcal{X}\to[0,1]\). The predictor \(f:\mathcal{X}\to[0,1]\) is \((\mathcal{C},\alpha)\)-multiaccurate or \((\mathcal{C},\alpha)\)-MA if for all \(c\in\mathcal{C}\),_ \[\Big{|}\,\mathbb{E}_{x,y}\big{[}c(x)\cdot\big{(}y-f(x)\big{)}\big{]}\,\Big{|} \leq\alpha.\] Multiaccuracy implies the weaker guarantee of accuracy in expectation for any group of sufficient likelihood that can be computed by the classifier family \(\mathcal{C}\). In this work, we consider the class \(\mathcal{C}\) computed by bounded-size Neural Networks (NNs), say of at most \(k\) nodes. This is a flexible representation due to the universality of NNs. For large enough \(k\), \(\mathcal{C}\) can express predicates like \(x\in S\) and \(f(x)\in I\) for simple subsets \(S\subseteq\mathcal{X}\) and \(I\subseteq[0,1]\). Our definition allows the generalization to \(c\) that may output real values in \([0,1]\), which we can think of conditioning on a distribution. The size restriction \(k\) is of interest and will play a fundamental role in our analysis. It captures the complexity of the auditor class \(\mathcal{C}\), which may be smaller than the predictor \(f\) learned in many cases of interest, if we require that \(f\) be \((\mathcal{C},\alpha)\)-multicalibrated. It is easy to show that the Bayes optimal predictor \(f(x)=\mathbb{E}[y\mid x]\) both perfectly minimizes squared loss and is also perfectly multicalibrated with respect to any class \(\mathcal{C}\)(see Barocas et al., 2019, Chapter 3). Liu et al. (2019) bound the MC error in terms of closeness to Bayes optimality. While interesting, these statements are representation independent-they do not shed light on different representations used in practice, such as linear predictors or NNs. In general, it is unclear whether the optimal predictor from a restricted family, which is chosen to minimize a certain loss should satisfy multicalibration (or even just calibration). It is easy to see that a loss-optimal linear function will not in general be multicalibrated. Our core question is: _are loss-optimal NNs multicalibrated_? The relation between loss minimization and multicalibration has been investigated extensively in the literature over the last few years (Kim et al., 2019, Gopalan et al., 2022, 2023a). It is known that minimizing any proper loss for linear models over a base hypothesis class \(\mathcal{C}\) yields multiaccuracy for \(\mathcal{C}\)(Gopalan et al., 2023a), but not multicalibration (Gopalan et al., 2022c). Indeed, it is known from the work of Gopalan et al. (2022a) that achieving multicalibration is as hard as minimizing arbitrary convex losses over \(\mathcal{C}\). However, little was known about the relation between these notions and models for which loss-minimization is non-convex, most importantly for deep neural nets. Kim et al. (2019) showed that retraining the last layer of a DNN with cross-entropy guarantees multiaccuracy with respect the features in the penultimate layer; this can be seen as a consequence of the result of Gopalan et al. (2023a) for linear models. To summarize the state of our understanding before this work, the convex setting was well understood, but there was little evidence one way or the other for how loss minimization and multicalibration relate in the non-convex case in setting, and for DNNs in particular. ### Our results We present the following answer to this question: _(most) loss-optimal large NNs are in fact multicalibrated_. Thus unlike simple classifiers, such as linear threshold functions, which face a trade-off between optimizing loss and MC, we show that for large NNs, the goals of MC and accuracy are closely aligned. Simpler representations may have other redeeming qualities, such as interpretability, but our analysis shows that NNs do not face the same inherent tension. This is important because it would otherwise be natural to combine NNs with existing MC algorithms. These MC algorithms are boosting-like algorithms that can achieve MC using any loss-minimizing algorithm-they repeatedly run the learning algorithm and produce a classifier that is an ensemble of the base classifiers (in this case NNs). Of course, one cannot efficiently solve the NP-hard problem of minimizing loss over all NNs of a given size, and in practice heuristics such as gradient descent are used. In this paradigm common in computational learning theory, an analysis of perfect loss minimization sheds light on a heuristic optimizer-if the property fails to hold for the heuristic then we understand it is due to poor loss minimization (and sometimes can be used to further reduce loss). Our results suggest that, rather than using an MC algorithm which would train multiple NNs and output a complex ensemble, one may prefer to simply train a larger NN. However, like the analysis of these MC algorithms, our analysis only holds assuming one can minimize loss over NNs (and a MC failure, once detected, can be directly converted into a NN with lower loss). Making this precise is somewhat subtle. Our results do not address algorithmic or sample complexity of NNs, which is left for future work. We disregard training time, compute and data resources. The results may be of interest purely for understanding NNs as a representation, similar to the universal representation theorems (e.g., Hornik et al., 1989). They also may be relevant to settings where inference is the bottleneck, e.g., the case where one is concerned with accuracy and model size. Using massive training resources is also consistent with recent large-scale pre-training efforts used to create models that can be then re-used across numerous applications, such as GPT-3 (Brown et al., 2020), PaLM (Chowdhery et al., 2022) and DALL-E-2 (Ramesh et al., 2022). Model-size and accuracy are often of greater importance as the pre-training costs can be amortized over numerous applications of inference. For neural nets, there may be no single optimal NN but instead a sequence of successively larger NNs that achieve decreasing losses, only approaching Bayes optimality for impractically large networks. One must therefore select a finite-size NN. If we are simply outputting the NN with lowest generalization loss, this essentially amounts to selecting the size. The first theorem states that for all but a bounded number of NN sizes, the loss-optimal NN is nearly MC with respect to smaller NNs, say of size \(k\) nodes. **Theorem 1.3** (Informal version of Theorem 3.2).: _Let \(k\in\mathbb{N}\) be an integer and \(\alpha\in(0,1]\). Then there are only \(O(k/\alpha^{2})\) different neural network sizes \(n\) for which the loss-optimal \(n\)-node NN is not \(\alpha\)-MC with respect to NNs of size \(k\)._ While this does not indicate which NN sizes will lead to MC, it suggests that the vast majority of loss-optimal large NNs (size \(\gg k/\alpha^{2}\)) are MC. The intuition behind why a large NN is MC is simple: if a NN \(f\) is not MC, then its loss can be improved using the classifier \(c\) which is a witness to its MC failure. Unfortunately, this improved NN is larger, so \(f\) may be optimal for its size. Nonetheless, we are able to bound the number of sizes for which MC fails. In other words, failure of the loss-optimizer to be multicalibrated at size \(n\) indicates a significant drop in loss happens at size \(n+k\), and such significant drops cannot happen too often. We also give a second approach based on regularization, which can also be motivated economically. Deploying large classifiers is expensive. To deploy a finite classifier, one may consider a cost, say, a linear cost of for deploying a NN of \(n\) nodes. Once amortized over queries, this is equivalent to using regularization and choosing a classifier that minimizes loss plus a constant, say \(1/N\), times size. Since loss \(\ell(f)\in[0,1]\), the optimal solution is always an NN with at most \(N\) nodes. Our second theorem shows that large NNs optimized for loss, with sufficiently small regularization, achieve MC. These networks may be similarly large. **Theorem 1.4** (Informal version of Theorem 3.3).: _Let \(k\in\mathbb{N}\) be an integer and \(\alpha\in(0,1]\). Then, for \(N=O(k/\alpha^{2})\), selecting a NN with size regularization term \(1/N\) will lead to a NN of size \(\leq N\) that is \(\alpha\)-MC with respect to NNs of size \(k\)._ While we cannot give tight lower bounds for analysis, Section 4 presents lower bounds suggesting that our current analysis cannot be significantly improved. To do this, we observe that the same exact analysis proves that loss minimization for Juntas (functions depending on a bounded number of features) yields multiaccuracy for juntas of bounded size \(k\). Here we show a lower bound, proving tightness up to constant factors of our bounds: there are indeed \(\Omega(k/\alpha^{2})\) integers \(n\) for which the loss-optimal junta is not multiaccurate. The right quantitative bound uses the noise stability of the majority function (see O'Donnell, 2014). Thus, a stronger result, if it exists, would use properties of DNNs and calibration beyond what our proof currently uses. **Theorem 1.5** (Informal statement of Theorem 4.2).: _Let \(\mathcal{J}_{k}(\mathcal{X})\) denote functions that depend on \(k\) input variables from the domain \(\mathcal{X}=\{\pm 1\}^{m}\). For every \(k\) and small enough \(\alpha\), there exist \(m\in\mathbb{Z}_{>0}\), a distribution \(\mathcal{D}\) over \(\mathcal{X}\times\{0,1\}=\{\pm 1\}^{m}\times\{0,1\}\), and at least \(\Omega(k/\alpha^{2})\) distinct non-negative integers \(n\) such that any model \(f_{n}\in\mathcal{J}_{n}(\mathcal{X})\) is not \((\mathcal{C},\alpha)\)-MA with respect to \(\mathcal{C}=\mathcal{J}_{k}(\mathcal{X})\)._ Contributions.Our main contribution is proving that for "most" large NNs, loss-optimal NNs are multicibrated. We provide two ways of formalizing the notion of most, which both lead to similar bounds. This can be viewed as an additional potential benefit of the NN representation, which is not satisfied by all other representations. However, as discussed in Section 6, this should not be viewed as a statement that "fairness comes for free if you just optimize NNs," because of the blowup we face in the NN size, because MC is not itself adequate for fairness in some applications, and because it is not known if we can efficiently find perfectly optimal NNs. The work of Hebert-Johnson et al. (2018) reduces the problem of learning such a predictor to weak agnostic learning for the class \(\mathcal{C}\). Their algorithm starts an arbitrary predictor \(f\) and a weak agnostic learner for the class \(\mathcal{C}\), and post-process \(f\) to a predictor \(g\) which is \((\mathcal{C},\alpha)\)-multicalibrated. One can view \(g\) as being a circuit composed of \(f\) together with some number of hypothesis from the class \(\mathcal{C}\). Subsequently, Gopalan et al. (2022) showed that MC can be achieved using the boosting via branching programs algorithm of Mansour and McAllester (2002). Given that NNs are essentially circuits, hence more general than branching programs, it is perhaps not surprising that one can achieve MC using a neural net architecture. But in this view, we only think of neural nets as a circuit class, without paying attention to how they are learned. The dominant approach to learning a neural net is to fix an architecture and then perform loss minimization. Previous results did not shed much light on whether neural nets learned using this paradigm can be reasonably multicibrated for an expressive class \(\mathcal{C}\). Our work takes a step in this direction by showing that the goal of loss minimization is aligned with multicalibration. The next step towards would be to specialize the loss minimization algorithm to stochastic gradient descent, which is popularly used, and ask if the resulting neural nets offer any multicalibration guarantees. Organization.Section 2 defines the setting and mathematical preliminaries. Section 3 gives our main results, with the regularization analysis covered in Section 3.1. Releated work is presented in Section 5. Finally, Section 6 discusses risks and limitations of the present work. ## 2 Preliminaries We assume \(\mathcal{X}\subseteq\mathbb{R}^{d}\) is a Euclidean space in some dimension \(d\), and focus on binary classification where \(\mathcal{Y}=\{0,1\}\). We can also allow for \(\mathcal{Y}=[0,1]\), in which case the multicalibration guarantee we achieve is called mean multicalibration (Jung et al., 2020), or the multiclass setting with \(l>2\) distinct labels, we focus on the binary classification setting for simplicity. We assume an arbitrary, unknown joint distribution \(\mathcal{D}\) on \(\mathcal{X}\times\mathcal{Y}\). For simplicity we focus on the \(l_{2}\) loss, \[\ell(f):=\operatorname*{\mathbb{E}}_{\mathcal{D}}\left[\left(y-f(x)\right)^{2} \right].\] Since only one distribution \(\mathcal{D}\) is used throughout the analysis, we assume it is fixed and omit it from our notation, e.g., writing \(\ell(f)\) rather than \(\ell_{\mathcal{D}}(f)\) and omitting it from the expectation when clear from context, as above. For a Euclidean subset \(S\), let \(\mathsf{NN}_{n}(S)\) denote the family of fully-connected Neural Networks with the standard ReLU activations and exactly \(n\) nodes, which map inputs from \(S\) to output values in \([0,1]\). The ReLU activation computes \(\mathsf{ReLU}(z):=\max(0,z)\) on input \(z\). Thus \(\mathsf{NN}_{n}\) is defined by a Directed Acyclic Graph (DAG) with \(n\) nodes, where the activation of a node with \(d_{\text{in}}\) inputs is \(a=\mathsf{ReLU}(w\cdot a_{\text{in}}+b)\) where \(a_{\text{in}}\in\mathbb{R}^{d_{\text{in}}}\) is the vector of activations of its inputs, \(w\in\mathbb{R}^{d_{\text{in}}}\) is a vector of equal dimension, and \(b\in\mathbb{R}\) is a bias term. We also define \(\mathsf{NN}_{0}=\{0\}\), i.e., the constant \(0\) function is defined to be computed by a 0-node NN. The set of functions computed by \(\mathsf{NN}_{n}(S)\) is monotonically increasing with \(n\) since we can trivially add identity nodes to compute the same function. Enforcing an output in \([0,1]\) is added to the definition for convenience and can easily be achieved by wrapping the output \(z\) in two ReLUs: \[\forall z\in\mathbb{R}\ \operatorname{clip}_{[0,1]}(z):=\mathsf{ReLU}(z- \mathsf{ReLU}(z-1))=\max(0,\min(1,z))\in[0,1]. \tag{1}\] The results in this paper can be extended by enforcing various architectures, such as a NN with a given number of hidden layers, but we present the results for a general feed-forward architecture for simplicity. ## 3 Multicalibration and NNs A standard fact from statistics is that if one has a function that is correlated with the residual \(y-f(x)\), one can scale and add it to the predictor to reduce loss, and clipping it to the interval \(\mathcal{Y}=[0,1]\) can only further reduce loss. This combination can easily be computed using ReLU functions. The Lemma below shows that if a \(k\)-node witness \(c\) to the fact that \(f\) is not \(\alpha\)-MC, can be used to augment \(f\) with \(k+3\) additional nodes and reduce its loss by at least \(\alpha^{2}\). **Lemma 3.1** (Loss reduction from MC).: _Let \(f\in\mathsf{NN}_{n}(\mathcal{X})\), \(c\in\mathsf{NN}_{k}(\mathcal{X}\times\mathcal{Y})\) and suppose,_ \[\mathbb{E}\left[c\big{(}x,f(x)\big{)}\cdot\big{(}y-f(x)\big{)}\right]=\beta.\] _Then \(h(x):=\operatorname{clip}_{[0,1]}\bigl{(}f(x)+\beta c(x,f(x))\bigr{)}\) belongs to \(\mathsf{NN}_{n+k+3}(\mathcal{X})\) and has loss \(\ell(h)\leq\ell(f)-\beta^{2}\)._ Proof.: Observe that \(h(x)=\operatorname{clip}_{\mathcal{Y}}\bigl{(}f(x)+\beta c(x,f(x))\bigr{)}\) is computed by \[h(x)=\mathsf{ReLU}\bigl{(}\mathsf{ReLU}(f(x)+\beta c(x,f(x)))-\mathsf{ReLU}(f( x)+\beta c(x,f(x))-1)\bigr{)}. \tag{2}\] as can be seen through Eq. (1). Then observe that Eq. (2) is indeed a representation of a \((n+k+3)\)-node NN: \(n\) nodes to compute \(f(x)\), \(k\) nodes to compute \(c(x,f(x))\) and then the 3 additional ReLU nodes as described (note that \(f(x)\) and \(c(x,f(x))\) are both re-used without recomputing them). Thus \(h\in\mathsf{NN}_{n+k+3}(\mathcal{X})\) as claimed. Next, define \(g(x):=f(x)+\beta c(x,f(x))\), so \(h(x)=\operatorname{clip}_{[0,1]}(g(x))\). Then, \[\ell(g) =\mathbb{E}\left[(y-f(x)-\beta c(x,f(x)))^{2}\right]\] \[=\mathbb{E}\left[(y-f(x))^{2}-2\beta c(x,f(x))(y-f(x))+\beta^{2}c ^{2}(x,f(x))\right]\] \[=\ell(f)-2\beta\,\mathbb{E}\left[c(x,f(x))(y-f(x))\right]+\beta^{ 2}\,\mathbb{E}\left[c^{2}(x,f(x))\right]\] \[=\ell(f)-2\beta^{2}+\beta^{2}\,\mathbb{E}\left[c^{2}(x,f(x)) \right].\] Since \(c^{2}(x,f(x))\leq 1\), this implies that \(\ell(g)\leq\ell(f)-\beta^{2}\). Finally, note that for any \((x,y)\), \((y-h(x))^{2}\leq(y-g(x))^{2}\) since \(y\in\{0,1\}\) and \(h(x)\) is the projection of \(g(x)\) onto the closest point in \([0,1]\), thus \(\ell(h)\leq\ell(g)\) Using this lemma, we can now prove our main result. The first states that the set of NN sizes \(n\) for which there is a loss-optimal, \(n\)-node NN that is _not_\((\mathcal{C},\alpha)\)-MC is at most \((k+3)/\alpha^{2}\). **Theorem 3.2**.: _Let \(\mathcal{D}\) be a distribution over \(\mathcal{X}\times\mathcal{Y}\), and let \(k\in\mathbb{N}\) and \(\alpha\in(0,1]\). Then for all but at most \((k+3)/\alpha^{2}\) integers \(n\in\mathbb{N}\), for every minimizer \(\hat{f}_{n}\):_ \[\hat{f}_{n}\in\operatorname*{arg\,min}_{f\in\mathsf{NN}_{n}(\mathcal{X})}\ell (f),\] \(\hat{f}_{n}\) _is \((\mathcal{C},\alpha)\)-MC with respect to \(\mathcal{C}=\mathsf{NN}_{k}(\mathcal{X}\times\mathcal{Y})\)._ Proof.: Say an \(n\)-node NN is "bad" if it minimizes loss among \(\mathsf{NN}_{n}(\mathcal{X})\) but is _not_\((\mathcal{C},\alpha)\)-MC. Say size \(n\) is "bad" if there is any bad \(n\)-node NN. For each \(n\), fix \(f_{n}\in\mathsf{NN}_{n}(\mathcal{X})\) that minimizes \(\ell(f)\). If there is more than one such minimizer, select a bad one if there is one. The losses for \(f_{n}\) are non-increasing and between 0 and 1, because the set of functions computable by \(\mathsf{NN}_{n}\) is monotonically increasing with \(n\): \[1\geq\ell(f_{1})\geq\ell(f_{2})\geq\ell(f_{3})\ldots\geq 0.\] For any \(n\), we claim that if there is an \(n\)-node NN \(f_{n}\in\mathsf{NN}_{n}(\mathcal{X})\) which minimizes \(\ell(f)\) that is not \((\mathcal{C},\alpha)\)-MC, then it must be the case that, \[\ell(f_{n+k+3})<\ell(f_{n})-\alpha^{2}. \tag{3}\] This is because: (1) by definition of \((\mathcal{C},\alpha)\)-MC, there must be a auditor \(c\in\mathcal{C}\) with \[|\mathbb{E}[c(x,f_{n}(x))(y-f_{n}(x))]|=\beta>\alpha\] and (2) by Lemma 3.1 we can combine \(f_{n},c\) to form a NN with \((n+k+3)\) nodes where the loss drops by \(\beta^{2}>\alpha^{2}\), implying Equation (3). To complete the proof, partition the integers based on their residues mod \(b=k+3\). In each partition, there will be \(<1/\alpha^{2}\) drops in \(\ell(f_{n})\) of magnitude \(\alpha\) since \(\ell(f_{n})\in[0,1]\), and each bad size corresponds to a drop of magnitude at least \(\alpha^{2}\) by Equation (3). ### Regularization If one is worried about avoiding a "bad" size, then one can pick the size randomly from a large range, since there are relatively few bad sizes. Alternatively, one can use the natural regularization approach discussed in the introduction. Note that if one applies a regularization of \(1/N\) times the number of nodes, the optimum will never have more than \(N\) nodes because the loss of a NN with 0 nodes is at most 1. In this case, one guarantees \((\mathcal{C},\alpha)\)-MC with certainty. **Theorem 3.3** (Size-regularized NNs.).: _Let \(\mathcal{D}\) be a distribution over \(\mathcal{X}\times[0,1]\), and let \(k\in\mathbb{N},\alpha\in(0,1]\) and \(N=(k+3)/\alpha^{2}\). Let \(\hat{f}\) be any minimizer of:_ \[\hat{f}\in\operatorname*{arg\,min}_{n\leq N;\,\hat{f}\in\mathsf{NN}_{n}( \mathcal{X})}\ell(f)+\frac{n}{N}. \tag{4}\] _Then \(\hat{f}\) is \((\mathcal{C},\alpha)\)-MC for \(\mathcal{C}=\mathsf{NN}_{k}(\mathcal{X}\times[0,1])\)._ Proof.: The size-0 NN that computes the constant 0 function has loss at most 1 (since the labels are in \(\{0,1\}\)). So we may assume that the optimization was carried out over all \(n\), as any solution to the full optimization will have \(n\leq N\). Say the minimum occurs at \(\hat{n},\hat{f}\), so \(\hat{f}\) consists of \(\hat{n}\) nodes. Suppose the theorem were false, i.e., there exists some \(c\in\mathsf{NN}_{k}(\mathcal{X}\times[0,1])\) with at most \(k\) nodes such that \[\beta:=\operatorname*{\mathbb{E}}_{(x,y)\sim\mathcal{D}}\left[c\big{(}x,\hat{f }(x)\big{)}\cdot\big{(}y-\hat{f}(x)\big{)}\right]\] satisfies \(|\beta|>\alpha\). By Lemma 3.1, for \[h(x):=\operatorname{clip}_{[0,1]}\left(\hat{f}(x)+\beta c\big{(}x,\hat{f}(x) \big{)}\right),\] we have, \[\ell(h)\leq\ell(\hat{f})-\beta^{2}<\ell(\hat{f})-\alpha^{2}=\ell(\hat{f})- \frac{k+3}{N},\] where the last equality is by the choice of \(N\). Again \(h\in\mathsf{NN}_{\hat{n}+k+3}\). This contradicts the optimality of \(\hat{f}\) for Eq. (4), since \[\ell(h)+\frac{1}{N}(\hat{n}+k+3)<\ell(\hat{f})+\frac{1}{N}\hat{n}.\] This gives a way of finding a \(n\leq(k+3)/\alpha^{2}\)-node NN that is \(\alpha\)-MC with respect to \(k\)-node NNs, since \(N=(k+3)/\alpha^{2}\). Finite training sets.If one has a training set consisting of \(m\) examples iid from \(\mathcal{D}\), a natural approach is to minimize training loss. If \(m\) is sufficiently large compared to the number of NN parameters, which is polynomial in \(n\), generalization bounds guarantee every \(f\in\mathsf{NN}_{n}(\mathcal{X})\) will have training loss close to its true loss \(\ell(f)\), and thus any \(\hat{f}_{n}\) which minimizes training error (still ignoring computation time) will have, say, \(\ell(\hat{f}_{n})\leq\min_{\mathsf{NN}_{n}(\mathcal{X})}\ell(f)+\epsilon\) for \(\epsilon=O(\alpha^{2})\). This can, in turn, be used with the above theorems to show that, outside a set of \(O(k/\alpha^{2})\) NN sizes, all NNs that are optimal on the training set will be \(O(\alpha)\)-MC with respect to \(k\)-node NNs. While such an analysis would be straightforward, we find it unsatisfactory given the fact that current generalization bounds, though correct, seem to be too loose to capture the performance of many NN learning algorithms in practice (e.g. (Zhang et al., 2021; Nagarajan and Kolter, 2019)). However, our results above may be relevant in settings where generalization is guaranteed -- for example, when models are trained using Stochastic Gradient Descent (SGD) for only one-epoch (one pass through the training data). In this case, the learning algorithm can be thought of as optimizing via SGD directly on the population loss, without considering a finite train set. If we heuristically believe that, when run for long enough, the optimization reaches close to a population loss minima within the architecture family, then our results imply most resulting minima will also be multicalibrated. Moreover, the one-epoch setting may not be far from reality, since most modern large language models are indeed trained for only one epoch (Brown et al., 2020; Biderman et al., 2023), and there is evidence that generalization in the multi-epoch setting can be understood via the one-epoch setting (Nakkiran et al., 2021). ## 4 A lower bound We would like to understand the tightness of the analysis we have presented. Unfortunately, this is challenging due to the complex structure of NNs. Instead, this section provides some evidence of the tightness of our analysis at least _using our current methods_. To do this, we consider another natural class of functions namely \(k\)_-juntas_ and a weaker notion of multigroup fairness called multiaccuracy, to which our analysis applies. In this setting, we show a sharp result, proving that our bounds are tight up to constant factors. The class of _Juntas_, functions that depend on a small subset of inputs, has been well studied in computational learning theory (Mossel et al., 2004; Fischer et al., 2004). In this section, we show that Juntas satisfy a similar property to NNs in that, for most sizes, minimizing loss for Juntas also implies MA with respect to smaller Juntas. We also prove a _lower bound_ for showing that our bounds are tight up to constant factors. For our results in this section, we choose the domain \(\mathcal{X}\) to be the Boolean cube \(\{-1,1\}^{m}\) for a dimension \(m\in\mathbb{Z}_{>0}\). That is, every \(x\in\mathcal{X}\) can be written as \(x=(x_{1},\ldots,x_{m})\) where \(x_{i}\in\{-1,1\}\) for every \(i=1,\ldots,m\). For a positive integer \(k\) and a function \(f:\mathcal{X}\to[0,1]\), we say \(f\) is a _\(k\)-junta_ if there exist \(i_{1},\ldots,i_{k}\in\{1,\ldots,m\}\) and \(g:\{-1,1\}^{k}\to[0,1]\) such that \(f(x)=g(x_{i_{1}},\ldots,x_{i_{k}})\) for every \(x\in\mathcal{X}\). We say a function \(f:\mathcal{X}\to[0,1]\) is a \(0\)-junta if \(f\) is a constant function. We use \(\mathcal{J}_{k}(\mathcal{X})\) to denote the family of \(k\)-juntas over domain \(\mathcal{X}\). The following theorem is analogous to Theorem 3.2: **Theorem 4.1**.: _Let \(\mathcal{D}\) be a distribution over \(\mathcal{X}\times\mathcal{Y}\), where \(\mathcal{X}=\{-1,1\}^{m}\) for a positive integer \(m\) and \(\mathcal{Y}=\{0,1\}\). Let \(k\in\mathbb{Z}_{>0}\) and \(\alpha\in(0,1]\) be parameters. Then for all but at most \(k/\alpha^{2}\) nonnegative integers \(n\in\mathbb{Z}_{\geq 0}\), for every minimizer \(\hat{f}_{n}\):_ \[\hat{f}_{n}\in\operatorname*{arg\,min}_{f\in\mathcal{J}_{n}(\mathcal{X})}\ell (f),\] \(\hat{f}_{n}\) _is \((\mathcal{C},\alpha)\)-MA with respect to \(\mathcal{C}=\mathcal{J}_{k}(\mathcal{X})\)._ The proof works exactly like the proof of Theorem 3.2 using the following observation. For \(f\in\mathcal{J}_{n}(\mathcal{X}),c\in\mathcal{J}_{k}(\mathcal{X})\), and \(\beta\in\mathbb{R}\), define function \(h:\mathcal{X}\to[0,1]\) as \[h(x)=\operatorname{clip}_{[0,1]}(f(x)+\beta c(x)),\] then \(h\in\mathcal{J}_{n+k}(\mathcal{X})\). The following theorem gives a lower bound that matches Theorem 4.1 up to a constant factor. **Theorem 4.2**.: _For every \(k\in\mathbb{Z}_{>0}\) and every \(\alpha\in(0,1/(6\pi)]\), there exist \(m\in\mathbb{Z}_{>0}\), a distribution \(\mathcal{D}\) over \(\mathcal{X}\times\mathcal{Y}\) with \(\mathcal{X}=\{-1,1\}^{m}\) and \(\mathcal{Y}=\{0,1\}\), and at least \(k/(54\pi^{2}\alpha^{2})\) distinct nonnegative integers \(n\) such that any model \(f_{n}\in\mathcal{J}_{n}(\mathcal{X})\) is not \((\mathcal{C},\alpha)\)-MA with respect to \(\mathcal{C}=\mathcal{J}_{k}(\mathcal{X})\)._ Key to our proof of Theorem 4.2 is the _majority_ function. For an odd positive integer \(k\), we define the majority function \(\mathsf{MAJ}:\{-1,1\}^{k}\to\{-1,1\}\) such that for every \((x_{1},\ldots,x_{k})\in\{-1,1\}^{k}\), \(\mathsf{MAJ}(x_{1},\ldots,x_{k})=1\) if \(x_{1}+\cdots+x_{k}>0\), and \(\mathsf{MAJ}(x_{1},\ldots,x_{k})=-1\) otherwise. The following lemma about majority functions follows from standard noise sensitivity bounds (see O'Donnell, 2014). We provide a proof for completeness. **Lemma 4.3**.: _For any odd positive integers \(m\) and \(k\) satisfying \(k\leq m\),_ \[\mathbb{E}[\mathsf{MAJ}(x_{1},\ldots,x_{k})\mathsf{MAJ}(x_{1},\ldots,x_{m})]> \frac{2}{\pi}\cdot\sqrt{\frac{k}{m}},\] _where the expectation is over \((x_{1},\ldots,x_{m})\) drawn uniformly at random from \(\{-1,1\}^{m}\).2_ Footnote 2: The constant \(2/\pi\) cannot be improved because in the limit where \(k,m\to\infty,\sqrt{k/m}\to\rho\in(0,1)\), using the central limit theorem one can show that \(\mathbb{E}[\mathsf{MAJ}(x_{1},\ldots,x_{k})\mathsf{MAJ}(x_{1},\ldots,x_{m})] \to(2/\pi)\arcsin\rho\). Also, it is easy to show that \(\mathbb{E}[f(x_{1},\ldots,x_{k})\mathsf{MAJ}(x_{1},\ldots,x_{m})]\) is maximized when \(f=\mathsf{MAJ}\) among all \(f:\{-1,1\}^{k}\to[-1,1]\) (see e.g. Gopalan et al., 2008, Lemma 13). Using the majority function, we define a distribution \(\mathcal{D}\) over \(\{-1,1\}^{m}\times\{0,1\}\) for any odd positive integer \(m\) as follows. We first draw \(x\in\{-1,1\}^{m}\) uniformly at random and then set \[y=\frac{1}{2}(1+\mathsf{MAJ}(x))\in\{0,1\}.\] We define \(\mathcal{D}\) to be the distribution of \((x,y)\). Lemma 4.3 allows us to prove the following lemma about the distribution \(\mathcal{D}\), which we then use to prove Theorem 4.2. **Lemma 4.4**.: _Let \(k,m\) be odd positive integers satisfying \(k\leq m\). Define \(\mathcal{X}:=\{-1,1\}^{m}\) and define distribution \(\mathcal{D}\) as above. Let \(\alpha>0\) be a parameter satisfying_ \[\alpha\leq\frac{1}{3\pi}\cdot\sqrt{\frac{k}{m}}. \tag{5}\] _Then any function \(f\in\mathcal{J}_{m-k}(\{-1,1\}^{m})\) is not \((\mathcal{C},\alpha)\)-MA with respect to \(\mathcal{C}=\mathcal{J}_{k}(\mathcal{X})\)._ Proof.: We first show that for any function \(f\in\mathcal{J}_{m-k}(\{-1,1\}^{m})\), there exist \(i_{1},\ldots,i_{k}\in\{1,\ldots,m\}\) such that \[\mathbb{E}_{(x,y)\sim\mathcal{D}}[(y-f(x))\mathsf{MAJ}(x_{i_{1}},\ldots,x_{i_ {k}})]>\frac{1}{\pi}\cdot\sqrt{\frac{k}{m}}. \tag{6}\] By the definition of \(f\in\mathcal{J}_{m-k}(\mathcal{X})\), there exist \(j_{1},\ldots,j_{m-k}\in\{1,\ldots,m\}\) and \(g:\{-1,1\}^{m-k}\) such that \[f(x)=g(x_{j_{1}},\ldots,g_{j_{m-k}})\quad\text{for every $x\in\mathcal{X}$}.\] Now we choose distinct \(i_{1},\ldots,i_{k}\in\{1,\ldots,m\}\setminus\{j_{1},\ldots,j_{m-k}\}\). We have \[\mathbb{E}_{(x,y)\sim\mathcal{D}}[f(x)\mathsf{MAJ}(x_{i_{1}},\ldots,x_{i_{k}}) ]=\mathbb{E}[g(x_{j_{1}},\ldots,g_{j_{m-k}})\mathsf{MAJ}(x_{i_{1}},\ldots,x_{i _{k}})]=0, \tag{7}\] where the last equation holds because \((x_{i_{1}},\ldots,x_{i_{k}})\) is independent from \((x_{j_{1}},\ldots,x_{j_{m-k}})\). By Lemma 4.3 and our choice of distribution \(\mathcal{D}\), \[\mathbb{E}_{(x,y)\sim\mathcal{D}}[y\,\mathsf{MAJ}(x_{i_{1}},\ldots,x_{i_{k}}) ]>\frac{1}{\pi}\cdot\sqrt{\frac{k}{m}}. \tag{8}\] Combining (7) and (8) proves (6). Now we show that \(f\) is _not_\((\mathcal{C},\alpha)\)-MA with respect to \(\mathcal{C}=\mathcal{J}_{k}(\mathcal{X})\). Assume for the sake of contradiction that \(f\) is \((\mathcal{C},\alpha)\)-MA. Then for the function \(c:\mathcal{X}\to[0,1]\) such that \(c(x)=\frac{1}{2}(1+\mathsf{MAJ}(x_{i_{1}},\ldots,x_{i_{k}}))\), it holds that \[\mathbb{E}_{(x,y)\sim\mathcal{D}}[(y-f(x))c(x)]\leq\alpha.\] Also, \[\mathbb{E}_{(x,y)\sim\mathcal{D}}[(y-f(x))]\geq-\alpha.\] Therefore, \[\mathbb{E}_{(x,y)\sim\mathcal{D}}[(y-f(x))\mathsf{MAJ}(x_{i_{1}},\ldots,x_{i _{k}})]=\mathbb{E}[(y-f(x))(2c(x)-1)]\leq 3\alpha.\] This is a contradiction with (6) due to our assumption (5). We are now ready to prove our lower bound Theorem 4.2. Proof of Theorem 4.2.: For any positive integer \(k\), define \(k_{1}\) to be the largest odd integer that does not exceed \(k\). It is easy to verify that \(k_{1}\geq k/2>0\). For any \(\alpha\in(0,1/(6\pi)]\), choose \(m\) to be the largest odd integer smaller than \(k_{1}/(9\pi^{2}\alpha^{2})\). Our assumption that \(\alpha\leq 1/(6\pi)\) ensures that \(k_{1}/(9\pi^{2}\alpha^{2})\geq 4k_{1}\), and thus \(m\geq 3k_{1}\) and \(m\geq k_{1}/(18\pi^{2}\alpha^{2})\). Moreover, our choice of \(m\) ensures that \[\alpha\leq\frac{1}{3\pi}\sqrt{\frac{k_{1}}{m}}.\] By Lemma 4.4, for \(\mathcal{X}=\{-1,1\}^{m}\) and \(\mathcal{Y}=\{0,1\}\) there exists a distribution \(\mathcal{D}\) over \(\mathcal{X}\times\mathcal{Y}\) such that for every nonnegative integer \(n=0,\ldots,m-k_{1}\), any model \(f_{n}\in\mathcal{J}_{n}(\mathcal{X})\) is _not_\((\mathcal{C},\alpha)\)-MA with respect to \(\mathcal{C}=\mathcal{J}_{k_{1}}(\mathcal{X})\). Since \(\mathcal{J}_{k_{1}}(\mathcal{X})\subseteq\mathcal{J}_{k}(\mathcal{X})\), any \(f_{n}\in\mathcal{J}_{n}(\mathcal{X})\) is also _not_\((\mathcal{C},\alpha)\)-MA with respect to \(\mathcal{C}=\mathcal{J}_{k}(\mathcal{X})\). The number of such integers \(n\) is \[m-k_{1}+1\geq 2m/3\geq(2/3)(k_{1}/(18\pi^{2}\alpha^{2}))=k_{1}/(27\pi^{2} \alpha^{2})\geq k/(54\pi^{2}\alpha^{2}).\qed\] ## 5 Related Work The notion of multicalibration for multigroup fairness was introduced in Hebert-Johnson et al. (2018), see also Kearns et al. (2017), Kleinberg et al. (2017). This notion has proved to be unexpectedly rich, with connections to several other areas. The work of Dwork et al. (2021) relates it to indistinguishability, while Kim et al. (2022) connects it to domain adaptation. A line of work on omniprediction Gopalan et al. (2022); Gu et al. (2023); Hu et al. (2022) has shown that multicalibration for a class \(\mathcal{C}\) implies strong loss minimization guarantees when compared against benchmarks from \(\mathcal{C}\). This is the opposite direction to the one we study here: it shows settings where loss minimization results from multicalibration. A more recent work Gopalan et al. (2023) in fact shows an equivalence between multicalibration and certain swap loss minimization problems. Without getting into details, the model of loss minimization is inspired by internal regret in online learning, and is different from the standard notion that we study here. Perhaps the most related work to ours is that of Liu et al. (2019) and Barocas et al. (2019, Chapter 3), who provide MC guarantees for classifiers whose loss is near the absolute minimum possible loss of Bayes-optimal predictors, in the case of squared error \(f(x)=\mathbb{E}[y\mid x]\). Finally, there is a long history studying calibration (not MC) which can be viewed as a special case of MC where the groups are defined by \(f(x)\) only, i.e., \(c(f(x))\), ignoring the features \(x\) itself. In particular, a set of practical studies that have found that large NNs are often calibrated out "of the box" despite being optimized solely for loss Minderer et al. (2021); Hendrycks et al. (2020); Karandikar et al. (2021); Desai and Durrett (2020); Carrell et al. (2022). A concurrent work of Blasiok et al. (2022) attempts to explain this phenomenon by proving that: functions whose loss cannot be improved much by (a simpler) post-processing are exactly those that are close to calibrated. They then speculate that well-trained neural networks are likely to be loss-optimal in this sense, and thus calibrated. The present work can be seen as pursuing a similar line of reasoning, but in the more general setting of multicalibration. The work of Kim et al. (2019) showed that the performance of image classifiers on demographic subgroups can be improved by ensuring multiaccuracy. We are not aware of experimental work measuring the degree of multicalibration for large neural networks on massive training sets. There are numerous works on the representation ability of NNs Hornik et al. (1989) and about their accuracy and generalization (e.g., Zhang et al., 2021; Nagarajan and Kolter, 2019), too large to survey here. ## 6 Discussion We start by discussing some limitations of our work. We do not provide any guidance on selecting \(k\), which is an important theoretical and practical issue. Second, there is a blowup in the NN size \(n\) required to achieve MC with respect to NNs of size \(k\). Also, the model we study is highly unrealistic in that we assume that we have unbounded training data and computational resources at training time. Even though current pre-training efforts do involve massive amounts of data and compute, it is not clear that they are or will ever approach what could be done in this limit. Nonetheless, we feel that it still may be useful to understand the nature of different classifier representations and the tensions that they face. First of all, one conclusion of this work is that one can achieve MC with NNs-as a representation they are not limited in the same way as some other classifiers. In particular, simpler classifiers (which may enjoy other benefits such as interpretability) may face an inherent tension between accuracy and calibration overall and among different groups. If one leads a group of practitioners training NNs and one is concerned about multicalibration, our work suggests that incentivizing them to simply minimize loss may, to some extent, be aligned with MC. This is formal in the sense of Lemma 3.1: if one can identify a classifier for which the current predictor is miscalibrated, then one can further reduce the loss, escaping a local minimum if the classifier was trained with a local optimization algorithm. But this may naturally happen if they were incentivized to minimize loss. If it is not happening naturally, such a "check" could be suggested and it would be entirely compatible with the group's loss incentives. Future work.It would be interesting to empirically measure whether NNs used in practice are multicalibrated. If so, this might be viewed as one additional benefit of their use over simpler models. If not, it would be interesting to understand the reasons- the gaps between theory and practice. Another direction would be to prove a similar result for other classes of hypotheses. The key property of neural nets that we use is that the post-processing required to update the predictor can be incorporated into a predictor of larger size. It is not hard to see that other classes such as decision trees and branching programs (parametrized by size) do have this property. But they are not known to have provable algorithms for squared loss minimization. In contrast linear models do admit efficient loss minimization. But they are not powerful enough to be closed under the kinds of post-processing that multicalibration requires. Moreover, they cannot express the kind of predicates that are interesting for multicalibration, such as \(x\in S\) and \(f(x)=0.1\). An intriguing question is whether there is a hypothesis class that is indeed powerful enough to give interesting multicalibration guarantees and is closed under post-processing, but which admits efficient loss minimization. It is also possible that there exists a no-free-lunch flavor of result which rules out such a possibility. We leave formalizing and proving such results to future work. Risks.We conclude on a cautionary note. There is a risk that this and other similar work will be misinterpreted as "fairness/multicalibration comes for free if you just optimize loss in DNNs" but that is not a valid conclusion for multiple reasons. First of all, multicalibration is only one notion of fairness. It is particularly applicable in settings where and the groups of interest are identifiable from \(x\). Multicalibration cannot protect groups of concern that are not identifiable from \(x\), e.g., race is a complex feature that may not be explicitly coded or perfectly computable from existing features, and the protection gets weaker for smaller groups. If a practitioner was given an _explicit_ set of protected groups whose accuracy is to be prioritized, they ought to consider all steps in the machine learning pipeline and not just optimization: they might adjust their architectures, collect additional data, or expand the feature set so as to increase the family of protected subgroups and performance on those groups. For instance, explicitly investigating multicalibration may lead to discovering certain groups on which it is hard to achieve good calibration, which requires a different type of learning architecture, better datasets or more informative features. ## Acknowledgments We thank Ryan O'Donnell and Rocco Servedio for suggesting the current proof of Lemma 4.3. We also thank Barry-John Theobald for comments on an early draft. Part of this work was performed while LH was interning at Apple. LH is also supported by Moses Charikar's and Omer Reingold's Simons Investigators awards, Omer Reingold's NSF Award IIS-1908774, and the Simons Foundation Collaboration on the Theory of Algorithmic Fairness. JB is supported by a Junior Fellowship from the Simons Society of Fellows.
2304.13468
Comparison of artificial neural network adaptive control techniques for a nonlinear system with delay
This research paper compares two neural-network-based adaptive controllers, namely the Hybrid Deep Learning Neural Network Controller (HDLNNC) and the Adaptive Model Predictive Control with Nonlinear Prediction and Linearization along the Predicted Trajectory (AMPC-NPLPT), for controlling a nonlinear object with delay. Specifically, the study investigates the effect of delay on the accuracy of the two controllers. The experimental results demonstrate that the AMPC-NPLPT approach outperforms HDLNNC regarding control accuracy for the given nonlinear object control problem.
Bartłomiej Guś, Jakub Możaryn
2023-04-26T11:44:49Z
http://arxiv.org/abs/2304.13468v1
Comparison of artificial neural network adaptive control techniques for a nonlinear system with delay ###### Abstract This research paper compares two neural-network-based adaptive controllers, namely the Hybrid Deep Learning Neural Network Controller (HDLNNC) and the Adaptive Model Predictive Control with Nonlinear Prediction and Linearization along the Predicted Trajectory (AMPC-NPLPT), for controlling a nonlinear object with delay. Specifically, the study investigates the effect of delay on the accuracy of the two controllers. The experimental results demonstrate that the AMPC-NPLPT approach outperforms HDLNNC regarding control accuracy for the given nonlinear object control problem. Artificial Neural Network, Nonlinear object, Hybrid Deep Learning Neural Network, Adaptive Model Predictive Control, Time-Delay Object ## I Introduction The PID control algorithm is a commonly utilized controller in industrial applications. This wide utilization can be attributed to the limited number of adjustable parameters, including the proportional, integral, and derivative actions, simplifying the controller's operation. However, for nonlinear systems, accurate control using constant parameter values for the PID control algorithm is only possible at specific operating points. The limitations as mentioned above of the PID controller have driven the search for alternative control techniques that can ensure satisfactory performance over a larger operating range, especially for nonlinear objects with changing conditions. Various neural-network-based adaptive approaches have been proposed in the literature as promising solutions for controlling nonlinear systems. The Hybrid Deep Learning Neural Network Controller (HDLNNC) was proposed in [2][3]. This controller utilizes multiple types of artificial neural networks (ANN), including the self-organizing Kohonen map (SOM), Hebbian learning procedure [4], and adaptive learning rate derived from the direct Lyapunov method, to achieve precise control for nonlinear objects, even in the presence of time-varying parameters. An extension of this approach involves considering changes in the dynamics of the controlled object to enable a smooth transition of the control signal. Another adaptive control strategy gaining popularity in industry is based on the Model Predictive Control (MPC) algorithm, which has been recently extended using nonlinear models, including those in the form of ANN, as reported in [7][8]. Nonetheless, employing a nonlinear model directly results in a nonlinear quadratic optimization problem, necessitating more computational resources than a linear model. In [7], various approaches for efficient Model Predictive Control with nonlinear models have been proposed, among which the ANN-based Model Predictive Control with Nonlinear Prediction and Linearization along the Predicted Trajectory (MPC-NPLPT) technique stands out. In MPC-NPLPT, the predicted output is a linear approximation calculated along some assumed future control sequence, and to enhance prediction accuracy and control quality, linearization is performed repeatedly. In this paper, the Adaptive Model Predictive Control - Nonlinear Prediction and Linearization along the Predicted Trajectory (AMPC-NPLPT) with the ANN model was used to enhance prediction precision. ## II Hybrid Deep Learning Neural Network Controller Figure 1 illustrates the HDLNNC scheme, which comprises two distinct blocks that respectively correspond to the model (Deep Recurrent Neural Network - DRNN) and the controller (Hybrid Deep Learning Neural Network Controller - HDLNNC). ### _Controller_ The model block in HDLNNC scheme [2] is a deep learning model employing an Artificial Neural Network (ANN) comprising three layers in each of two parts. The first part consists of a self-organizing Kohonen map (SOM) with Hebbian learning, referred to as the Hybrid Deep Learning (HDL) layer. The Fig. 1: Scheme of HDLNNC. second part comprises a Multi-Layer Feed-Forward Neural Network (MLFFNN), incorporating an adaptive learning factor for weight updates. The input signals to the ANN are defined as the error signal, the rate of change of the error signal, and the rate of change of the error signal at each sampling instance. At the onset of each instance, the initial step involves computing the controller error, denoted by \(e_{con}\). Subsequently, the weight update for the first two layers of the HDL component is determined as \[W_{j}(k+1)=W_{j}(k)-h_{winner,j}(k)(X(k)-W_{j}(k))\in R^{N_{L}} \tag{1}\] Equation 1 is utilized in the SOM learning process, whereby the weight values are updated via the winner-takes-most (WTM) approach. The update of weight values \(W_{j}(k)\) is determined not only for the winning neuron, i.e., the one that exhibits weight values closest to the input values \(X(k)\in R^{N_{L}}\) of the ANN in a selected metric but also for the current iteration denoted by \(k\). Where \(N_{L}\) denotes the number of neurons in the previous layer. Function \(h_{winner,j}(k)\) is calculated as \[h_{winner,j}(k)=l(k)e^{-\frac{r_{winner,j}^{2}(k)}{2\xi(k)^{2}}}\in R^{N_{L}} \tag{2}\] where: \[l(k)=e^{-\frac{k}{K_{L}}}\in R \tag{3}\] \[\xi(k)=\xi_{0}\left(-\frac{\xi_{f}}{\xi_{0}}\right)^{\frac{k}{K_{L}}}\in R \tag{4}\] where \(r_{winner,j}\) denotes the distance between the \(j^{th}\) neuron and the winning neuron, \(K_{L}\) denotes the maximum number of learning samples and \(l_{0}\),\(\xi_{0}\), \(\xi_{f}\) are coefficients selected from range \((0;1>\). The weights in the last layer, i.e. in the third layer in HDL are updated using the Hebbian learning procedure as follows \[W_{j}(k+1)=W_{j}(k)+\gamma Y(k)X(k)-\delta Y(k)W(k)\in R^{N_{L}} \tag{5}\] Where \(Y(k)\in R^{N_{O}}\) means the previous output from the ANN, \(N_{O}\) the number of neurons in the layer, \(\delta\) and \(\gamma\) are coefficients from range (0,1). The part \(\delta Y(k)W(k)\) is responsible for forgetting a learned pattern. \[\begin{split} CV(k)=f(f(\left[\begin{array}{c}e_{con}(k)\\ \Delta e_{con}(k)\\ \Delta^{2}e_{con}(k)\end{array}\right]W_{HDL}^{I}(k))\\ W_{HDL}^{II}(k))W_{HDL}^{II}(k)\in R\end{split} \tag{6}\] Upon completion of the weight update procedure in the HDL component, the subsequent step involves computing the control variable, as specified in equation (6). Herein, \(W_{HDL}^{I}(k)\), \(W_{HDL}^{II}(k)\), and \(W_{HDL}^{III}(k)\) represent the weights of each layer at the current instant \(k\), as per equations (1) and (5). The activation function, denoted as \(f()\), is chosen as the tangent hyperbolic function. Assuming that the Mean Squared Error is the minimizing function, the weights in the MLFFNN are modified as \[\begin{array}{l}W(k+1)=W(k)+\eta(k)e_{con}(k)\\ \frac{\sigma PV_{process}(k)}{\sigma CV(k)}\frac{\sigma CV(k)}{\sigma W(k)}\in R ^{N_{L}\times N_{A}}\end{array} \tag{7}\] where \[\eta(k)=\frac{\alpha}{\phi(1+\frac{\phi}{\phi}(\frac{\sigma e_{con}(k)}{ \sigma W(k)})^{2})}\in R^{N_{L}\times N_{A}} \tag{8}\] Where \(N_{A}\) denotes the number of neurons in the actual layer. Equation (8) is the result of the selection of the Lyapunov function as (9) in which the value of \(\eta(k)\) is determined by one of the three conditions present: \(V(k+1)-V(k)\leqslant 0\) in the direct Lyapunov method and satisfies the other two \(V(k)>0,V(0)=0\) as \[V(k)=\frac{\alpha}{2}e_{con}(k)^{2}+\frac{\beta}{2}\Delta e_{con}(k)^{2}+ \frac{\phi}{2}\Delta W(k)^{2}\in R \tag{9}\] Where in Equation (8), (9) \(e_{con}\) means the error of control in current instant, \(\alpha\), \(\beta\), \(\phi\) are coefficients selected between (0:1\(>\), Jacobian of model can be estimated by \[\frac{\sigma PV_{process}(k)}{\sigma CV(k)}\approx\frac{\sigma PV_{model}(k)}{ \sigma CV(k)}\in R \tag{10}\] ### _Model_ The adaptive learning rate in the DRNN model [5] was calculated by \[\eta_{O}(k)=\frac{2}{N_{h}}\in R \tag{11}\] \[\eta_{D}(k)=\frac{2}{N_{h}(max||W^{0}(k)||)^{2}}\in R \tag{12}\] \[\eta_{I}(k)=\frac{2}{N_{h}(max||W^{0}(k)||)^{2}(max||I^{0}(k)||)^{2}}\in R \tag{13}\] Where \(N_{h}\) denotes the number of neurons in only the hidden layer, \(W^{O}(k)\) weights in the output layer, \(I^{O}(k)\) weights in input to the neural network model, \(\eta_{O}(k)\), \(\eta_{D}(k)\), \(\eta_{I}(k)\) adaptive learning rate respectively for output, diagonal, input layer. In this case, the selected Lyapunov function is \[V(k)=\frac{1}{2}e_{mod}(k)^{2}\in R \tag{14}\] Table I includes applied parameter values. Initial values for the weights of the controller and model, also the initial values of the diagonal layer in the DRNN model, were drawn from range (-0.1, 0.1). III Adaptive Model Predictive Control - Nonlinear Prediction and Linearization Along The Predicted Trajectory The MPC control algorithm offers several significant advantages, including its capacity to handle Multiple-Input Multiple-Output (MIMO) processes. Additionally, the algorithm is robust to process delays, and it delivers high-quality control performance even in the presence of such delays. Another advantage of the MPC algorithm is its ability to accommodate constraints on the input and output variables or state variables. This feature is particularly useful in practical control applications where constraints are commonly encountered and must be satisfied to ensure optimal performance and safety. The basic idea of MPC algorithm [7] is to use the online dynamics of the model of the process to calculate predicted errors over the given horizon and minimize the cost function -- \[\begin{split} J_{\text{CF}}(k)=\sum_{p=1}^{N}(& y_{sp}(k+p|k)-y_{\sim}(k+p|k))^{2}+\\ &+\lambda\sum_{p=0}^{N_{U}-1}(\Delta u(k+p|k))^{2}\in R\end{split} \tag{15}\] where \(y_{sp}(k+p|k)\) refers to the setpoint at step \(k+p\), which is known at the current step \(k\), for the process output, \(y_{\sim}(k+p|k)\) denotes the predicted value at step \(k+p\) for the output of the process model, known at the current step \(k\), \(\lambda\) is a user-defined weighting factor that is used to adjust the relative importance of the setpoint tracking and control effort optimization objectives, the prediction horizon is denoted by \(N\), and \(N_{u}\) is the control horizon, the quantity \(\Delta u(k+p|k)\) denotes the change in the control signal over the prediction horizon. The imposed constraints are represented by \[J_{\text{CF}}(k)=||Y_{sp}(k)-Y_{\sim}(k)||^{2}+||\Delta U(k)||_{\Lambda}^{2}\in R \tag{16}\] only if \[U_{min}\leq U(k)\leq U_{max} \tag{17}\] \[\Delta U_{min}\leq U(k)\leq\Delta U_{max} \tag{18}\] \[Y_{min}\leq Y_{\sim}(k)\leq Y_{max} \tag{19}\] where \[Y_{sp}(k)=[y_{sp}(k)\ldots y_{sp}(k+N)]^{T}\in R^{N} \tag{20}\] \[Y_{\sim}(k)=[y_{\sim}(k+1|k)\ldots y_{\sim}(k+N|k)]^{T}\in R^{N} \tag{21}\] \[U_{min}=[u_{min}\ldots u_{min}]^{T}\in R^{N_{u}} \tag{22}\] \[U_{max}=[u_{max}\ldots u_{max}]^{T}\in R^{N_{u}} \tag{23}\] \[\Delta U_{max}=[\Delta u_{max}\ldots\Delta u_{max}]^{T}\in R^{N_{u}} \tag{24}\] \[Y_{min}=[y_{min}\ldots y_{min}]^{T}\in R^{N} \tag{25}\] \[Y_{max}=[y_{max}\ldots y_{max}]^{T}\in R^{N} \tag{26}\] \[\Lambda=diag(\lambda\ldots\lambda)\in R^{N_{u}\times N_{u}} \tag{27}\] where \(u_{min}(k)\), \(u_{max}(k)\) denotes the minimum/maximum value of the control variable, \(y_{min}(k)\), \(y_{max}(k)\) denotes the minimum/maximum of the value of output variable. Regarding the MPC-NPLPT and AMPC-NPLPT control algorithms (as shown in Figure 2), an internal iteration technique was employed to enhance both the accuracy of the predicted process output and the control performance. This involved repeated model linearization and calculation of the future control increment. Specifically, the Taylor series expansion approximates the nonlinear output with a linear model. \[Y_{\sim}^{i}(k)=Y_{\sim}^{i-1}(k)+H^{i}(k)(U^{i}(k)-U^{i-1}(k)) \tag{28}\] where: \[Y_{\sim}^{i-1}(k)=[y_{\sim}^{i-1}(k+1|k)\ldots y_{\sim}^{i-1}(k+N|k)]^{T}\in R ^{N} \tag{29}\] \[\begin{split} H^{i}(k)&=\frac{dV_{\sim}^{i-1}(k)}{ dU_{\sim}^{i-1}(k)}=\\ &=\begin{bmatrix}\frac{dy_{\sim}^{i-1}(k+1|k)}{du^{i-1}(k|k)}& \ldots&\frac{dy_{\sim}^{i-1}(k+1|k)}{du^{i-1}(k+N_{u}-1|k)}\\ \vdots&\ddots&\vdots\\ \frac{dy_{\sim}^{i-1}(k+N|k)}{du^{i-1}(k|k)}&\ldots&\frac{dy_{\sim}^{i-1}(k+N|k)}{du^{i-1}(k+N_{u}-1|k)} \end{bmatrix}\in R^{N\cdot N_{u}}\\ \end{split} \tag{30}\] \[U^{i}(k)=[u^{i}(k|k)\ldots u^{i}(k+N|k)]^{T}\in R^{N_{u}} \tag{31}\] \[U^{i-1}(k)=[u^{i-1}(k|k)\ldots u^{i-1}(k+N|k)]^{T}\in R^{N_{u}} \tag{32}\] where \(i\) means the internal iteration of the MPC-NPLPT algorithm. Vector \(U^{i}(k)\) is calculated for \(i=0\) (i.e. the first iteration) as \[U^{0}(k)=U^{i-1}(k)=[u(k-1)\ldots u(k-1)]^{T}\in R^{N_{u}} \tag{33}\] Fig. 2: Scheme of AMPC-NPLPT. and for \(i\) greater than zero is calculated as \[U^{i}(k)=J\Delta U^{i}(k)+U(k-1)\in R^{N_{\text{u}}} \tag{34}\] where \(J\) is all one lower triangular matrix. This study utilised an Artificial Neural Network (ANN) model with an Elman structure to represent the control process. When investigating the impact of process delays on the MPC-NPLPT and AMPC-NPLPT algorithms, a modified Elman structure was employed [8], which delayed the input to account for the processing delay. The Armijo rule [1] was applied to determine the optimal learning rate for the model, both before and during the control process. The parameter values used for the AMPC-NPLPT algorithm are presented in Table I. Where \(\gamma\), \(\delta\) means values below which the internal iteration is interrupted due to either a small change in the control signal or sufficient control accuracy. Specifically, the initial weights and the initial values of the hidden layer output were randomized within the range of (-0.1, 0.1). ## IV Simulation Results The controllers HDLNNC, AMPC-NPLPT were used to control the following nonlinear process described as follows \[x_{1}(k)=A_{1}x_{1}(k-1)+A_{2}x_{2}(k-1) \tag{35}\] \[x_{2}(k)=\frac{x_{1}(k-1)}{A_{3}+x_{1}(k-1)^{2}+x_{2}(k-1)^{2}} \tag{36}\] \[y(k)=x_{1}(k) \tag{37}\] The initial values of the constants \(A_{1}\), \(A_{2}\), \(A_{3}\) were taken as: 0.2, 0.8, 1.1 and the values of states as \(x_{1}(0)=0\) and \(x_{2}(0)=0\). A sinusoidal signal with an amplitude of 1 and a frequency \(\frac{\pi}{4}\) was used as a reference signal from 0 to 100 seconds. In contrast, a rectangular signal with amplitudes between: -0.4, 0.4 was used and a cycle time of 4 seconds was used in 100-150 seconds, which was additionally filtered by an object with transfer function as \(\frac{1}{0.025\cdot s+1}\). In addition, in the \(100^{th}\) second the values of the constants: \(A_{1}\), \(A_{2}\), \(A_{3}\) were changed to: -0.2, 1.4, -15. An assessment of the control accuracy of the two controllers and a comparison between them was undertaken based on following Integral Control Quality Indices (ICQI) \[I_{IAE}=\int_{0}^{\infty}|e(t)|dt \tag{38}\] \[I_{ISE}=\int_{0}^{\infty}e(t)^{2}dt \tag{39}\] \[I_{ITAE}=\int_{0}^{\infty}t|e(t)|dt \tag{40}\] Before initiating control of the process, the Elman model used in the AMPC-NPLPT controller was trained by a sinusoidal signal with amplitudes of 0.8, 0.6, and 0.5, respectively, and a frequency of \(\frac{\pi}{4}\) for each of these signals. The learning signal was updated after every 8 seconds, corresponding to a full period of each sinusoidal signal. The training was stopped once the target function's mean squared error (MSE) value fell below \(10^{-15}\), achieved in approximately the \(22^{nd}\) second. This procedure was intended to initialize the weights of the Elman model, which would be further adapted during the control process. The simulation was conducted in Simulink with a calculation step of 1 ms for the nonlinear process without delay. In the AMPC-NPLPT controller, the only hidden layer had 5 neurons. The prediction horizon was set to 15 instants, and the control horizon was set to 3 instants. A weighting factor of 1 was used for \(\lambda\). The number of internal iterations was 10. Table II presents the quality indicators for the control actions taken by both controllers from 0 to 100 seconds. In almost every case, the AMPC-NPLPT controller produced smaller ICQI values, indicating more accurate control. Due to changes in the object's dynamics, which were calculated from changes in the DRNN's weights, the HDLNNC controller resulted in a smoother start of control than the AMPC-NPLPT controller. The AMPC-NPLPT controller adjusted its weights significantly in the initial phase based on the output of the nonlinear object (Fig. 3). After about 0.3 seconds, the AMPC-NPLPT controller produced more accurate tracking Fig. 3: Reference signal and process output for HDLNNC and AMPC-NPLPT in time from 0 to 4 seconds. of the reference signal than the HDLNNC controller. However, because the model inaccurately represented the object's behavior up to 0.3 seconds, it caused the output to exceed the acceptable limits of the \(y_{max}\) value. Figure 4 compares the position of the nonlinear object using the AMPC-NPLPT controller and the HDLNNC controller from 88 to 96 seconds. Figure 5 presents a comparison of the absolute error values at the same time. Figure 6 presents a close-up between 89.7 and 90.3 seconds, showing that the AMPC-NPLPT controller provided more precise control. Despite the change in the coefficients describing the behaviour of the nonlinear object as well as the reference signal, which occurred in the \(100^{th}\) second, an accurate control was obtained using both controllers. In this case, smaller values for all ICQI values were obtained using the controller: AMPC-NPLPT (Table II). Figure 8 shows a comparison of the absolute error values from 144 to 148 seconds. Figure 7 depicts a portion of the control cycle at the end of the control time, which shows that the AMPC-NPLPT predictive controller begins to decrease the output signal of the nonlinear object at approximately 145.98 seconds. number of weights for more accurate control. For the AMPC-NPLPT controller, the number of hidden layer neurons remained at 5, but the prediction horizon was increased to 30 and the control horizon to 5. The \(\lambda\) coefficient was changed to 0.8, the number of internal iterations increased to 20, and the value of the \(\Delta u\) parameter was reduced to \(3.5\cdot 10^{-2}\). The modification of the AMPC-NPLPT controller's input, which involved delaying it by as many steps as the output of a nonlinear object in an artificial neural network with an Elman structure, enabled the control of the process. However, the HDLNNC controller, despite an increase in the number of neurons in the hidden layers, was unable to follow the sinusoidal reference signal from time 0 to 200 seconds. To compensate for the delay and obtain the smallest possible ICQI, the CV signal was changed between the maximum values of -5 and 5. This course of the CV caused significant changes in the object position values. Our study compared the AMPC-NPLPT and HDLNNC controllers' performance for a delayed nonlinear object. We found that the AMPC-NPLPT controller adjusts the control signal's course in a way that reduces the Integrated Control Quality Index (ICQI) from cycle five without exceeding the maximum control signal values, which in this case were -1 to 1 (as seen in Fig. 9). Moreover, when we used a modified rectangular signal as the reference signal with the predictive algorithm, the AMPC-NPLPT controller achieved more accurate control than the HDLNNC controller, as evidenced by the smaller ICQI values in Table III. In contrast, the HDLNNC controller aimed to reduce the error by changing the control signal values from -5 to 5, as it did for the sinusoidal signal. However, we observed that the total absolute error between the nonlinear object output and the DRNN model was 55.3831, indicating an average error per instant of \(6.9228\cdot 10^{-3}\). ## V Conclusion The HDLNNC controller as well as the AMPC-NPLPT controller were successfully used to control the nonlinear object in the absence of delay. Using the AMPC-NPLPT controller, smaller ICQI values were obtained in most cases for the object in the absence of delay as well as with delay, even though it uses a single neural network and in the case of the HDLNNC controller the solution is more complex. Despite the increase in the number of neurons in both hidden layers, the HDLNNC controller was not able to control the selected nonlinear object with delay. Further research will be aimed at testing the performance of these controllers to other nonlinear objects even with delay as well as testing the absence of the previously learned AMPC-NPLPT controller.
2302.13080
Does a Neural Network Really Encode Symbolic Concepts?
Recently, a series of studies have tried to extract interactions between input variables modeled by a DNN and define such interactions as concepts encoded by the DNN. However, strictly speaking, there still lacks a solid guarantee whether such interactions indeed represent meaningful concepts. Therefore, in this paper, we examine the trustworthiness of interaction concepts from four perspectives. Extensive empirical studies have verified that a well-trained DNN usually encodes sparse, transferable, and discriminative concepts, which is partially aligned with human intuition.
Mingjie Li, Quanshi Zhang
2023-02-25T13:58:37Z
http://arxiv.org/abs/2302.13080v3
# Does a Neural Network Really Encode Symbolic Concept? ###### Abstract Recently, a series of studies have tried to extract interactions between input variables modeled by a DNN and define such interactions as concepts encoded by the DNN. However, strictly speaking, there still lacks a solid guarantee whether such interactions indeed represent meaningful concepts. Therefore, in this paper, we examine the trustworthiness of interaction concepts from four perspectives. Extensive empirical studies have verified that a well-trained DNN usually encodes sparse, transferable, and discriminative concepts, which is partially aligned with human intuition. _The code will be released when the paper is accepted._ ## 1 Introduction Understanding the black-box representation of deep neural networks (DNNs) has received increasing attention in recent years. Unlike graphical models with interpretable internal logic, the layerwise feature processing in DNNs makes it naturally difficult to explain DNNs from the perspective of symbolic concepts. Instead, previous studies interpreted DNNs from other perspectives, such as illustrating the visual appearance that maximizes the inference score [20, 17], and estimating attribution/importance/saliency of input variables [14, 15, 16]. Zhou et al. [21], Bau et al. [20], Kim et al. [20] visualized the potential correspondence between convolutional filters in a DNN and visual concepts in an empirical manner. **Unlike previous studies, a series of studies [13, 20, 21, 22] tried to define and propose an exact formulation for the concepts encoded by a DNN.** Specifically, these studies discovered that a well-trained DNN usually encoded various interactions between different input variables, and the inference score on a specific input sample could be explained by numerical effects of different interactions. Thus, they claimed that each interaction pattern was a symbolic concept encoded by the DNN. Specifically, let us consider a DNN given a sample with \(n\) input variables \(N=\{1,2,...,n\}\)_e.g._, given a sentence with five words "_he is a green hand._" The DNN usually does not use each individual input variable for inference independently. Instead, the DNN lets different input variables interact with each other to construct concepts for inference. For example, a DNN may memorize the interaction between words in \(S=\{\textit{green, hand}\}\) with a specific numerical contribution \(I(S)\) to push the DNN's inference towards the meaning of a "_beginmer._" Such a combination of words is termed an _interaction concept_. Each interaction concept \(S\subseteq N\) represents the AND relationship between input variables in \(S\). Only the co-appearance of input variables in \(S\) can make an interaction effect \(I(S)\) on the network output. In contrast, masking any word in \(\{\textit{green, hand}\}\) removes the interaction effect \(I(S)\). In this way, Ren et al. [20] proved that the inference score \(y\) of a trained DNN on each sample can be written as the sum of effects of all potential symbolic concepts \(S\subseteq N\), _i.e._\(y=\sum_{S\subseteq N}I(S)\). _However, the claim that "a DNN encodes symbolic concepts" is too counter-intuitive. Ren et al. [20] just formulated \(I(S)\) that satisfied \(y=\sum_{S\subseteq N}I(S)\). Current studies have not provided sufficient support for the claim that a DNN really learns symbolic concepts. In fact, we should not ignore another potential situation that the defined effect \(I(S)\) is just a mathematical transformation that ensures the decomposition of network output into concepts \(y=\sum_{S\subseteq N}I(S)\), rather than faithfully representing a meaningful and transferable concept learned by a DNN._ Therefore, in this paper, we aim to give a quantitative verification of the concept-emerging phenomenon, _i.e._, whether a well-trained DNN summarizes transferable symbolic knowledge from chaotic raw data, like what human brain does. Or the defined effect \(I(S)\) is just a mathematical game without clear meanings. To this end, we believe that if a well-trained DNN really encodes certain concepts, then the concepts are supposed to satisfy the following four requirements. * **Representing network inference using a few concepts.** If a DNN really learns symbolic concepts, then the DNN's inference on a specific sample is supposed to be concisely explained by a small number of salient concepts, rather than a large number of concepts, according to both Occam's Razor and people's intuitive understanding towards concepts. In fact, the sparsity of concepts in a specific sample has been discussed by Ren et al. (2021). In this paper, we further conduct extensive experiments on more diverse DNNs, in order to verify that a well-trained DNN usually extracts sparse concepts from each sample for inference. \(\bullet\)**A transferable concept dictionary through different samples.** If a DNN can use a relatively small set \(\mathbf{D}\) of salient concepts, namely a concept dictionary, to approximate inference scores on different samples in a category, \(\forall\mathbf{x},y\approx\sum_{S\in\mathbf{D}}I(S|\mathbf{x})\), then we consider the concept dictionary \(\mathbf{D}\) represents common features shared by different samples in the category. Otherwise, if Ren et al. (2021) extract a fully different set of concepts from each different sample in the same category, then these concepts probably represent noisy signals. In other words, convincing concepts must be stably extracted with high transferability through different samples in the same category. \(\bullet\)**Transferability of concepts across different DNNs.** Similarly, when we train different DNNs for the same task, different DNNs probably learn similar sets of concepts if they really memorize the defined "concepts" as basic inference patterns for the task. \(\bullet\)**Discrimination power of concepts.** Furthermore, if a DNN learns meaningful concepts, then these concepts are supposed to exhibit certain discrimination power in the classification task. The same concept extracted from different samples needs to consistently push the DNN towards the classification of a certain category. To this end, we conducted experiments on various DNNs trained on different datasets for classification tasks, including tabular datasets, image datasets, and point-cloud datasets. We found that all these trained DNNs encoded transferable concepts. On the other hand, we also investigated a few extreme cases, in which the DNN either collapsed into simple linear models or failed to learn transferable and discriminative concepts. In sum, although we cannot theoretically prove the phenomenon of the emergence of transferable concepts, this phenomenon indeed happened for most tasks in our experiments. **Contributions** of this paper can be summarized as follows. (1) Besides the sparsity of concepts, we propose three more perspectives to examine the concept-emerging phenomenon of a DNN, _i.e._, whether the DNN summarizes transferable symbolic knowledge from chaotic raw data. (2) Extensive empirical studies on various tasks have verified that a well-trained DNN usually encodes transferable interaction concepts. (3) We also discussed three extreme cases, in which a DNN is unlikely to learn transferable concepts. ## 2 Related works **Understanding the black-box representation of DNNs.** Many explanation methods have been proposed to explain DNNs from different perspectives. Typical explanation methods include visualizing patterns encoded by a DNN (Simonyan et al., 2013; Zeiler and Fergus, 2014; Yosinski et al., 2015; Dosovitskiy and Brox, 2016), estimating the attribution/importance/saliency of each input variable (Ribeiro et al., 2016; Sundararajan et al., 2017; Lundberg and Lee, 2017; Fong and Vedaldi, 2017; Zhou et al., 2016; Selvaraju et al., 2017), and learning feature vectors potentially correspond to semantic concepts (Kim et al., 2018). Some studies explained a DNN by distilling the network into another interpretable model (Frosst and Hinton, 2017; Che et al., 2016; Wu et al., 2018; Zhang et al., 2018; Vaughan et al., 2018; Tan et al., 2018). However, most explanation methods did not try to disentangle concepts encoded by a DNN. **Interaction encoded by DNNs.** Many recent studies have focused on quantifying interactions between input variables learned by a DNN (Sorokina et al., 2008; Murdoch et al., 2018; Singh et al., 2018; Jin et al., 2019; Janizek et al., 2020). In game theory, Grabisch and Roubens (1999); Sundararajan et al. (2020); Tsai et al. (2022) proposed in Figure 1: Visualization of interaction concepts \(S\) extracted by PointNet on different samples in the ShapeNet dataset. The histograms show the distribution of interaction effects \(I(S|\mathbf{x})\) over samples in the “motorbike” category, where \(S\) is extracted as a salient concept. teraction metrics from different perspectives. Recently, Ren et al. (2021) defined concepts encoded by a DNN as the interaction between input variables. Ren et al. (2023) further optimized baseline values of input variables based on such concepts. Besides, Deng et al. (2022) found that DNNs were less likely to encode interaction concepts of intermediate complexity. However, strictly speaking, there still lacks theoretical guarantee for the interaction to really represent concepts. Therefore, in this paper, we examine the trustworthiness of the interaction concepts from four perspectives. ## 3 Emergence of transferable concepts ### Preliminaries: representing network inferences using interaction concepts It is widely believed that the learning of a DNN can be considered as a regression problem, instead of explicitly learning symbolic concepts like how graphical models do. However, a series of studies (Ren et al., 2021, 2023; Deng et al., 2022) have discovered that given a sufficiently-trained DNN for a classification task, its inference logic on a certain sample can usually be rewritten as the detection of specific concepts. In other words, the DNN's inference score on a specific sample can be sparsely disentangled into effects of a few concepts. **Disentangling the DNN's output as effects of interaction concepts.** Specifically, let us consider a trained DNN \(v:\mathbb{R}^{n}\rightarrow\mathbb{R}\) and an input sample \(\mathbf{x}\) with \(n\) input variables indexed by \(N=\{1,2,...,n\}\). Here, we assume the network output \(v(\mathbf{x})\in\mathbb{R}\) is a scalar. Note that different settings can be applied to \(v(\mathbf{x})\). For example, for multi-category classification tasks, we may set \(v(\mathbf{x})=\log\frac{p(y=y^{\text{run}}|\mathbf{x})}{1-p(y=y^{\text{run}}|\mathbf{x})}\in \mathbb{R}\) by following (Deng et al., 2022). Then, given a function \(v(\mathbf{x})\), Ren et al. (2021) have proposed the following metric to quantify the interaction concept that is comprised of input variables in \(S\subseteq N\). \[I(S|\mathbf{x})\triangleq\sum\nolimits_{T\subseteq S}(-1)^{|S|-|T|}\cdot v(\mathbf{x} _{T}) \tag{1}\] where \(\mathbf{x}_{T}\) denotes the input sample when we keep variables in \(T\subseteq N\) unchanged and mask variables in \(N\backslash T\) using baseline values1. Footnote 1: For all tabular datasets and the image datasets (the _CelebA-eyeglasses_ dataset and the _CUB-binary_ dataset), the baseline value of each input variable was set as the mean value of this variable over all samples (Dabkowski and Gal, 2017). For grayscale digital images in the _MNIST-3_ dataset, the baseline value of each pixel was set as zero (Ancona et al., 2019). For the point-cloud dataset, the baseline value was set as the center of the entire point cloud (Shen et al., 2021). **Here, the interaction concept \(I(S|\mathbf{x})\) extracted from Figure 2: Visualization of interaction concepts \(S\) extracted by two _MLP-5_ networks3, which are trained on (a) the _wifi_ dataset3 and (b) the _tic-lac-toe_ dataset3. The histograms show (a) the distribution of interaction effects \(I(S|\mathbf{x})\) over samples in the \(4^{\text{th}}\) category, and (b) the distribution of interaction effects \(I(S|\mathbf{x})\) over samples in sub-categories4 with patterns \(x_{4}=x_{5}=x_{6}=1\) and \(x_{3}=x_{6}=x_{9}=1\). the input \(\mathbf{x}\) encodes an AND relationship (interaction) between input variables in \(S\). For example, let us consider three image regions of \(S=\{\textit{eyes, nose, mouth}\}\) that form the _"face"_ concept in a face classification task. Then, \(I(S|\mathbf{x})\) measures the numerical effect of the concept on the classification score \(v(\mathbf{x})\). Only when all image regions of _"eyes"_, _"nose"_, and _"mouth"_ co-appear in the input image, the _"face"_ concept is activated, and contributes a numerical effect \(I(S|\mathbf{x})\) to the classification score. Otherwise, if any region is masked, then the _"face"_ concept cannot be formed, which removes the interaction effect, making \(I(S|\mathbf{x}_{\text{masked}})=0\). Mathematically, the above definition for an interaction concept can be understood as the Harsanyi dividend [17] of \(S\)_w.r.t._ the DNN \(v\). It has been proven that the DNN's inference score \(v(\mathbf{x})\) can be disentangled into the sum of effects of all potential concepts, as follows. \[v(\mathbf{x})=\sum\nolimits_{S\subseteq N}I(S|\mathbf{x})\ \approx\sum\nolimits_{S\in \Omega_{\mathbf{x}}}I(S|\mathbf{x}) \tag{2}\] In particular, all interaction concepts can be further categorized into a set of **salient concepts**\(S\in\Omega_{\mathbf{x}}\) with considerable effects \(I(S|\mathbf{x})\), and a set of ignorable **noisy patterns** with almost zero effects \(I(S|\mathbf{x})\approx 0\). Note that the Harsanyi dividend \(I(S|\mathbf{x})\) also satisfies many desirable axioms/theorems, as introduced in Appendix A. The interaction effects can be further optimized using various tricks in [14] to pursue much more sparsity. ### Visualization of interaction concepts In this section, we visualize interaction concepts extracted from point-cloud data and tabular data. Note that a sample in the ShapeNet dataset [20] usually contains 2500 3D points. To simplify the visualization, we simply consider 8-10 semantic parts on the point cloud \(\mathbf{x}\), which has been provided by the dataset.2 Each semantic part is taken as a "single" input variable to the DNN. In this way, we visualize concepts consisting of semantic parts. Footnote 2: For example, the ShapeNet dataset has provided the annotated parts for the _motorbike_ category, including _gas tank_, _seat_, _handle_, _light_, _front wheel_, _back wheel_, _front frame_, _mid frame_, and _back frame_. Please see Appendix B.2 for details on the annotation of semantic parts. Fig. 1 shows interaction concepts \(S\) and the corresponding effects \(I(S|\mathbf{x})\) extracted by PointNet [20] from different samples \(\mathbf{x}\) in the ShapeNet dataset. We find that the interaction concept \(S=\{\textit{light, front wheel, mid frame}\}\) on five samples all makes positive effects \(I(S|\mathbf{x})>0\) to the PointNet's output, whereas the interaction concept \(S\ =\ \{\textit{handle, front wheel, front frame}\}\) usually makes negative effects \(I(S|\mathbf{x})<0\) to the PointNet's output. Similarly, Fig. 2 shows interaction concepts extracted from two tabular datasets, _i.e._, the _wifi_ dataset3, and the _tic-tac-toe_ dataset3. We visualize interactions between different _received signal strength indicators_ (RSSIs) in the _wifi_ dataset, and interactions between _board states_ in the _tic-tac-toe_ dataset. We also find that the same interaction concept usually makes similar effects to the network output on different input samples, which supports the conclusion in Section 3.3.2. Footnote 3: Please see the _experimental settings_ paragraph at the end of Section 3 for details on datasets and DNNs. ### Does a DNN really learn symbolic concepts? Although Ren et al. [2021] have claimed that the metric \(I(S|\mathbf{x})\) in Eq. (1) quantifies symbolic concepts encoded by a DNN, there is still no theory to guarantee a subset \(S\subseteq N\) with a salient effect \(I(S|\mathbf{x})\) faithfully represents a meaningful and transferable concept. Instead, we should not ignore the possibility that \(I(S|\mathbf{x})\) is just a mathematical transformation that ensures \(v(\mathbf{x})=\sum_{S\subseteq N}I(S|\mathbf{x})\) in Eq. (2) on each specific sample. Therefore, in this study, we examine the counter-intuitive conjecture that a DNN learns symbolic concepts from the following four perspectives. #### 3.3.1 Sparsity of the encoded concepts According to Eq. (2), the DNN may encode at most \(2^{n}\) symbolic concepts in \(2^{N}\triangleq\{S:S\subseteq N\}\)_w.r.t._ the \(2^{n}\) different combinations of input variables. **However, a distinctive property of symbolism, which is different from connectionism, is that people usually would like to use _a small number of explicit_ symbolic concepts to represent the knowledge, instead of using _extensive fuzzy_ features.** Thus, we hope to examine whether a DNN's inference score \(v(\mathbf{x})\) on a specific sample can be summarized into effects of a small number of salient concepts \(v(\mathbf{x})\approx\sum_{S\in\Omega_{\mathbf{x}}}I(S|\mathbf{x})\), rather than using an exponential number of concepts _w.r.t._ all subsets \(S\subseteq N\). To be precise, a faithful conceptual representation requires most concepts \(S\subseteq N\) to be noisy patterns with negligible effects \(I(S|\mathbf{x})\approx 0\). Only a few salient concepts \(S\) in \(\Omega_{\mathbf{x}}\) make considerable effects \(I(S|\mathbf{x})\). To this end, Ren et al. [2021] have made a preliminary attempt to explain a DNN's inference score \(v(\mathbf{x})\) on a specific sample \(\mathbf{x}\) as interaction effects \(I(S|\mathbf{x})\) of a small number of concepts. Specifically, they used a few top-ranked salient interaction concepts to explain the inference score of LSTMs [10] and CNNs [19] trained for sentiment classification and linguistic acceptance classification tasks on the SST-2 dataset [21] and the CoLA dataset [20]. **Experiments.** In this paper, we further examined whether most DNNs, which were trained for much more diverse tasks on different datasets, all encoded very sparse salient concepts. To this end, we trained various DNNs3 on tabular datasets (the _tic-tac-toe_ dataset3 and the _wifi_ dataset3), image datasets (the _MNIST-3_ dataset3 and the _CelebA-eyeglasses_ dataset3), and a point-cloud dataset (the _ShapeNet_ dataset3). The interaction effects can be further optimized using various tricks in [11] to pursue much more sparsity. Fig. 3 shows the normalized interaction strength of different concepts \(|\tilde{I}(S|\mathbf{x})|\triangleq|I(S|\mathbf{x})|/\max_{S^{\prime}}|I(S^{\prime}| \mathbf{x})|\) in a descending order for each DNN. Each curve shows the strength averaged over different samples in the dataset. We found that most concepts had little effects on the output \(|I(S|\mathbf{x})|\approx 0\), which verified the sparsity of the encoded concepts. Footnote 3: In this paper, when we needed to analyze of samples in a specific category, we used positive samples in the _MNIST-3_, _CelebA-eyeglasses_, and _CUB-binary_ datasets, samples in the 4th category in the _wifi dataset_, and samples in the “motorbike” category in the ShapeNet dataset. For the _ic-tac-tac-toe_ dataset, since there exists eight sub-categories among positive samples, we used samples in the sub-category with the pattern \(x_{4}=x_{5}=x_{6}=1\). **Salient concepts.** According to the above experiments, we can define the set of salient concepts as \(\Omega_{\mathbf{x}}=\{S:|I(S|\mathbf{x})|>\tau\}\), subject to \(\tau=0.05\cdot\max_{S}|I(S|\mathbf{x})|\). As Fig. 3 shows, there were only about 20-80 salient concepts extracted from an input sample, and all other concepts have ignorable effects on the network output. #### 3.3.2 Transferability over different samples Beyond sparsity, the transferability of concepts is more important. If \(I(S|\mathbf{x})\) is just a tricky mathematical transformation on \(v(\mathbf{x}_{S})\) without representing meaningful concepts, then each salient concept \(I(S|\mathbf{x})\) extracted from the input sample \(\mathbf{x}\) probably cannot be transferred to another input sample, _i.e.,_ we cannot extract the same salient concept consisting of variables in \(S\) in the second sample, due to sparsity of salient concepts. Therefore, in this section, **we aim to verify whether concepts extracted from a sample can be transferred to other samples.** This task is actually equivalent to checking whether there exists a common concept dictionary, which contains most salient concepts extracted from different samples in the same category. Given a well-trained DNN, we construct a relatively small dictionary \(\mathbf{D}_{k}\subseteq 2^{N}\) containing the top-\(k\) frequent concepts in different samples, and check whether such a dictionary contains most salient concepts in \(\Omega_{\mathbf{x}}\) extracted from each sample \(\mathbf{x}\). The concept dictionary \(\mathbf{D}_{k}\) is constructed based on a greedy strategy. Specifically, we first extract a set of salient concepts \(\Omega_{\mathbf{x}}\) from each input sample \(\mathbf{x}\). Then, we compute the frequency of each concept \(S\) being a salient concept over different samples. Finally, the concept dictionary \(\mathbf{D}_{k}\) is constructed to contain the top-\(k\) interaction concepts with the highest frequencies. Then, we design the metric \(\rho(k)\triangleq\mathbb{E}_{\mathbf{x}}[|\mathbf{D}_{k}\cap\Omega_{\mathbf{x}}|/| \Omega_{\mathbf{x}}|]\) to evaluate the average ratio of concepts extracted from an input sample that is covered by the concept dictionary \(\mathbf{D}_{k}\). Theoretically, if we construct a larger dictionary \(\mathbf{D}_{k}\) with more concepts (a larger \(k\) value), then the dictionary can explain more concepts. **Experiments.** We conducted experiments to show whether there existed a small concept dictionary that could explain most concepts encoded by the DNN. Specifically, we constructed a concept dictionary to explain samples in a certain category in each dataset4. In this experiment, we temporarily extracted salient concepts using \(\tau=0.1\cdot\max_{S}|I(S|\mathbf{x})|\) to construct \(\Omega_{\mathbf{x}}\)5. Fig. 4 shows the increase of the average explanation ratio \(\rho(k)\) along with the Figure 4: The change of the average explanation ratio \(\rho(k)\) along with the size \(k\) of the concept dictionary \(\mathbf{D}_{k}\). Figure 3: Normalized strength of interaction effects of different concepts in a descending order. DNNs trained for different tasks all encode sparse salient concepts. increasing size \(k\) of the concept dictionary \(\mathbf{D}_{k}\). We found that there usually existed a concept dictionary consisting of 30-100 concepts, which could explain more than 60%-80% salient concepts encoded by the DNN. Besides, Fig. 1(right) and Fig. 2(right) also show histograms of effects \(I(S|\mathbf{x})\) over different samples4, where \(S\) was extracted as a salient concept. We found that the same interaction concept usually made similar effects on different samples. This verified that the DNN learned transferable concepts over different samples. Footnote 4: We note that the a salient and negative effect on the classification score. In this way, the discrimination power of a salient concept \(S\) can be measured as \(\beta(S)=\max(m_{S}^{+},m_{S}^{-})/(m_{S}^{+}+m_{S}^{-})\). A larger value of \(\beta(S)\) indicates a higher discrimination power of the concept \(S\). **Experiments.** Note that different concepts are of different importance in the classification of a category. Some concepts frequently appear in different samples and make salient effects, while other concepts only appear in very few concepts. Therefore, we use the frequency of the concept \(\alpha(S)\) as a weight to compute the average discrimination power of all concepts, which is given as \(\bar{\beta}\triangleq\sum_{S}[\alpha(S)\cdot\beta(S)]/\sum_{S}[\alpha(S)]\). The frequency of a concept is defined as \(\alpha(S)\triangleq(m_{S}^{+}+m_{S}^{-})/m\). The selection of datasets and the training of DNNs are introduced in the _experimental settings_ paragraph at the end of Section 3. Fig. 6 shows the average discrimination power of concepts in different frequency intervals. We found that the average discrimination power \(\bar{\beta}\) of concepts was usually higher than \(0.8\), which verified the discrimination power of extracted concepts. ### When DNNs do not learn transferable concepts It is worth noting that all the above work just conducts experiments to show the concept-emerging phenomenon in different DNNs for different tasks. We do not provide, or there may even do not exist, a theoretical proof for such a concept-emerging phenomenon, although the concept-emerging phenomenon **does exist** in DNNs for most applications. Therefore, in this subsection, we would like to discuss the following three extreme cases, in which a DNN does not learn symbolic concepts. In the three extreme cases, DNNs may either collapse to simple models close to linear regressions, or learn non-transferable indiscriminative concepts, although the network output can still be represented as the sum of interaction effects of these concepts. \(\bullet\)**Case 1: When there exists label noise.** If the ground-truth label for classification is incorrectly annotated on some samples, then the DNN usually has to memorize each incorrectly-labeled training sample for classification without summarizing many common features from such chaotic annotations. Thus, in this case, the DNN usually encodes more non-transferable concepts. _Experimental verification._ In this experiment, we constructed datasets with noisy labels to check whether DNNs trained on these datasets did not learn transferable concepts with high discrimination power. To this end, given a clean dataset, we first selected and randomly labeled a certain portion \(r\) of training samples in the dataset, so as to train a DNN. Specifically, we constructed a series of datasets by assigning different ratios \(r\) of samples with incorrect labels. We used the _wifi_ dataset[3] to construct new datasets by adding different ratios \(r\) of noisy labels. Then, we trained an MLP-5 network[3] on each of these datasets. We examined the transferability and discrimination power of the extracted concepts[4] on each MLP-5 network. We extracted concept dictionaries of different sizes based on each MLP-5 network (please see Section 3.3.2 for details). Fig. 7(left) shows that if there was significant label noise in the dataset, the concept dictionary usually explained much fewer concepts encoded by the network, which indicated low transferability of the learned concepts. Besides, Fig. 7(right) shows the average discrimination power \(\bar{\beta}\) of the extracted concepts also decreased when we assigned more training samples with random labels. This verified that the DNN usually could not learn transferable and discriminative concepts from samples that were incorrectly labeled. \(\bullet\)**Case 2: When input samples are noisy.** In fact, this case can be extended to a more general scenario, _i.e._, when the task is difficult to learn, there is no essential difference between the difficult data and noisy data for the DNN. Specifically, when training samples are noisy and lack meaningful Figure 6: The average discrimination power of concepts in different frequency intervals, _i.e._\(\alpha\in(0.0,0.2],(0.2,0.4],...,(0.8,1.0]\). The weighted average discrimination power \(\bar{\beta}\) over concepts of all frequencies is shown beside the curve. Figure 7: The (left) transferability and (right) discrimination power of concepts decreased when we added more label noises. patterns, it is difficult for a DNN to learn transferable concepts from noisy training samples. _Experimental verification._ In this experiment, we injected noise into training samples to examine whether DNNs trained on datasets with noisy samples did not learn transferable concepts. Just like the experiment in "Case 1," we constructed such datasets by corrupting a clean dataset. To this end, we added Gaussian noises \(\mathbf{\epsilon}\sim\mathcal{N}(\mathbf{0},\mathbf{I})\) to each input sample \(\mathbf{x}\) in the clean dataset by modifying it to \((1-\delta)\cdot\mathbf{x}+\delta\cdot\mathbf{\epsilon}\), where \(\delta\in[0,1]\) denotes the strength of noise injected into the sample \(\mathbf{x}\). Each dimension of the clean sample \(\mathbf{x}\) was normalized to unit variance over the dataset beforehand. We constructed a series of datasets by injecting noises of different strength \(\delta\) into samples in the _wifi_ dataset3. We trained MLP-5's3 based on these datasets. Just like experiments in "Case 1," we examined the transferability and discrimination power of concepts. Fig. 8(left) shows that the transferability of concepts was usually low when the DNN was learned from noisy input data. Fig. 8(right) shows that the average discrimination power \(\bar{\beta}\) of concepts decreased along with the increasing strength \(\delta\) of injected noise. This verified that DNN usually did not learn transferable and discriminative concepts when input data were noisy. Footnote 3: [https://github.com/](https://github.com/) PointNet++ [Qi et al., 2017b]. Please see Appendix B.1 for the classification accuracy of the above DNNs. ## 4 Conclusion In this paper, we have analyzed the interaction concepts encoded by a DNN. Specifically, we quantitatively examine the concept-emerging phenomenon of a DNN from four perspectives. Extensive empirical studies have verified that a well-trained DNN usually encodes sparse, transferable, and discriminative interaction concepts. Our experiments also prove the faithfulness of the interaction concepts extracted from DNNs. Besides, we also discussed three cases in which a DNN is unlikely to learn transferable concepts.
2304.11519
Hierarchical Weight Averaging for Deep Neural Networks
Despite the simplicity, stochastic gradient descent (SGD)-like algorithms are successful in training deep neural networks (DNNs). Among various attempts to improve SGD, weight averaging (WA), which averages the weights of multiple models, has recently received much attention in the literature. Broadly, WA falls into two categories: 1) online WA, which averages the weights of multiple models trained in parallel, is designed for reducing the gradient communication overhead of parallel mini-batch SGD, and 2) offline WA, which averages the weights of one model at different checkpoints, is typically used to improve the generalization ability of DNNs. Though online and offline WA are similar in form, they are seldom associated with each other. Besides, these methods typically perform either offline parameter averaging or online parameter averaging, but not both. In this work, we firstly attempt to incorporate online and offline WA into a general training framework termed Hierarchical Weight Averaging (HWA). By leveraging both the online and offline averaging manners, HWA is able to achieve both faster convergence speed and superior generalization performance without any fancy learning rate adjustment. Besides, we also analyze the issues faced by existing WA methods, and how our HWA address them, empirically. Finally, extensive experiments verify that HWA outperforms the state-of-the-art methods significantly.
Xiaozhe Gu, Zixun Zhang, Yuncheng Jiang, Tao Luo, Ruimao Zhang, Shuguang Cui, Zhen Li
2023-04-23T02:58:03Z
http://arxiv.org/abs/2304.11519v1
# Hierarchical Weight Averaging for ###### Abstract Despite the simplicity, stochastic gradient descent (SGD)-like algorithms are successful in training deep neural networks (DNNs). Among various attempts to improve SGD, weight averaging (WA), which averages the weights of multiple models, has recently received much attention in the literature. Broadly, WA falls into two categories: 1) online WA, which averages the weights of multiple models trained in parallel, is designed for reducing the gradient communication overhead of parallel mini-batch SGD, and 2) offline WA, which averages the weights of one model at different checkpoints, is typically used to improve the generalization ability of DNNs. Though online and offline WA are similar in form, they are seldom associated with each other. Besides, these methods typically perform either offline parameter averaging or online parameter averaging, but not both. In this work, we firstly attempt to incorporate online and offline WA into a general training framework termed Hierarchical Weight Averaging (HWA). By leveraging both the online and offline averaging manners, HWA is able to achieve both faster convergence speed and superior generalization performance without any fancy learning rate adjustment. Besides, we also analyze the issues faced by existing WA methods, and how our HWA address them, empirically. Finally, extensive experiments verify that HWA outperforms the state-of-the-art methods significantly. Deep neural network, model averaging, weight averaging ## I Introduction Deep neural networks have evolved to the critical technique for a variety of computer vision problems, such as image classification [1, 2], object detection [3], semantic segmentation [4] and point cloud classification [5] since the breakthrough made in the ILSVRC competition [1]. Typically, DNNs are trained with variants of stochastic gradient descent (SGD) algorithms, in conjunction with a decaying learning rate. Various techniques such as adaptive learning rate schemes [6] and advanced learning rate scheduling strategies [7, 8] have been developed to improve SGD. Among these attempts to improve SGD, Weight Averaging (WA) is a simple but effective one and can be broadly categorized into two types: 1) online WA [9, 10, 11, 12, 13, 14], which is designed for reducing the gradient communication overhead of parallel mini-batch SGD and 2) offline WA [15], which is typically used to improve the generalization ability of DNNs. As illustrated in Figure 1(a), online WA averages multiple models trained in parallel every \(H\) iterations and then synchronizes the weights of each model to the averaged weights periodically. The interval between two parameter synchronization operations can be named as a _synchronization cycle_ and \(H\) is the corresponding _synchronization period_. The procedure of online WA is similar to parallel mini-batch SGD [16], which takes the average of gradients from multiple models in parallel, and then updates each local model using an SGD update with the averaged gradient. In other words, at every iteration, parallel mini-batch SGD can be interpreted as updating each local model with a single SGD step and then replacing each model with the averaged solution. Since parallel mini-batch SGD requires exchanging of local gradient information among all models at every iteration, the corresponding heavy communication overhead becomes one of its major issues. Unlike parallel mini-batch SGD, online WA has significantly less communication overhead as it evolves each model for \(H\) (e.g., \(H\in[1,64]\) in [9], \(H=10\) in [12], \(H\in[4,32]\) in [17]) sequential SGD updates before parameter synchronization. While online WA can speed up the training process, it does not perform very differently in terms of generalization performance. Unlike online WA, which periodically synchronizes the weights of each model to the averaged weights, offline WA (i.e., Stochastic Weight Averaging (SWA) [15]) does not participate in the training process directly, and the averaged weights are invisible to the optimizer. As illustrated in Figure 1(a), offline WA divides the training process into two stages, i.e., Stage I: normal training stage and Stage II: sampling stage. While there is no difference between offline WA and standard SGD at Stage I, offline WA samples a model checkpoint every \(H\) iterations periodically with _a cyclical or large constant learning rate scheduler_[7, 8] at Stage II, and then takes the average of the sampled model checkpoints to obtain the averaged model. Unlike online WA, offline WA evolves a model for more iterations (e.g., \(H=1000\)) before a model checkpoint is sampled. While standard SGD typically converges to a point near the boundary of local minima, offline WA is able to find a point centered in this region with better generalization performance. However, it does not exhibit better performance in terms of training efficiency than mini-batch SGD. Since offline WA performs averaging at the end of the training process, it requires choosing when to start sampling model checkpoints. A choice that is either too early or too late can be detrimental to the generalization performance of the averaged model. Besides, offline WA uses _a cyclical or large constant learning rate scheduler_ (WA_LR) to sample model checkpoints at the sampling stage. Since the learning rate has a significant impact on the locations of the sampled model checkpoints on the loss surface, the performance of offline WA is sensitive to the choice of WA_LR. As shown in Figure 2, the test accuracy of offline WA varies greatly when different constant learning rates are used at Stage II. With an improper setting, offline WA may even have a negative impact on the generalization performance (e.g., ResNet110 on CIFAR100 in Table II). To address the issues of offline WA, and combine the advantages of the two types of WA, in this work, we propose a novel weight averaging paradigm named Hierarchical Weight Averaging (HWA) to combine _online WA_ and _offline WA_ within a unified training framework. As illustrated in Figure 1 (c), HWA performs averaging in both online stage and offline stage. During the online stage, HWA trains multiple models in parallel with a normal decaying learning rate scheduler. After each model is evolved for \(H\) iterations, HWA synchronizes the weights of each model to the averaged weights \(\mathbf{W}_{e+1,1}^{k}\leftarrow\overline{\mathbf{W}}_{e}\), and then restraints training. However, unlike the existing high-frequency online WA, we propose to use _low-frequency online WA_ for HWA, which performs the parameter synchronization operation with a much lower frequency (i.e., larger synchronization period \(H\)). In practice, we observe that the low-frequency online WA simulates the'restart mechanism' (e.g. [7]) for DNN training and improves generalization performance. Later at the offline stage, HWA further takes the average of \(\overline{\mathbf{W}}_{e}\) at different synchronization cycles with a slide window of length \(I\), i.e., \(\overline{\mathbf{W}}_{e}=\frac{\sum_{i=e-I+1}^{I}}{I}\overline{\mathbf{W}}_{t}\). Unlike existing offline WA which requires a specific learning rate scheduler and takes the average of all the sampled model checkpoints, our proposed _slide-window based offline WA_ only averages the sampled model checkpoints within the slide window and works well with a regular learning rate scheduler (e.g., a cosine decay of learning rate over the entire budget [7]). Note that, _both online and offline WA is a special case of our proposed HWA_. In Table I we also provide a comparison of online WA, offline WA, and our proposed HWA. While online and offline WA can only serve a single purpose, i.e., Fig. 1: (a) Online WA periodically averages the weights of individual models in parallel \(\overline{\mathbf{W}}_{e}=\frac{\sum_{i=1}^{K}\mathbf{W}_{e,H}^{k}}{K}\) and then updates the weights of each model to the averaged weights \(\mathbf{W}_{e+1,0}^{k}\leftarrow\overline{\mathbf{W}}_{e}\). (b) Offline WA averages multiple points along the trajectory of SGD with a cyclical or large constant learning rate, and then takes the average. (c) HWA leverages both online and offline WA. At the online stage, it periodically synchronizes the weights of individual models trained in parallel with the averaged weights. At the offline stage, it also further averages the averaged solution \(\overline{\mathbf{W}}_{e}\) sampled at different synchronization cycles with a slide window of length \(I\), i.e., \(\overline{\mathbf{W}}_{e}=\frac{\sum_{i=e-I+1}^{I}}{I}\overline{\mathbf{W}}_{t}\). Fig. 2: The top-1 test accuracy of offline WA on CIFAR100 for ResNet56 with different constant learning rates (\(\{0.05,0.02,0.01\}\)) at Stage II (\(321-400\) epochs). improving training efficiency or generalization ability, the hybrid paradigm of HWA is able to achieve both of them with better performance. As an example, we plot the top-1 test accuracy of online WA, offline WA, and HWA on CIFAR100 for ResNet56 as a function of training time in Figure 3, where online WA and HWA apply a cosine annealing learning rate throughout the training process, and offline WA starts averaging from the \(320_{th}\) epoch with a constant learning rate. In sum, the contributions of this work are as follows. 1. We present a novel weight averaging scheme termed Hierarchical Weight Averaging (HWA) which incorporates two different types of WA techniques (i.e., online and offline WA), which are seldom associated with each other, into a unified training framework. By leveraging our designed _low-frequency online WA_ and _slide-window based offline WA_ in a hierarchical manner, HWA achieves several appealing benefits: 1) Unlike online or offline WA, which only serves a single purpose, HWA can improve training efficiency and generalization ability at the same time. 2) HWA outperforms online WA and offline WA in terms of training efficiency and generalization ability, respectively. 2. We also empirically analyze the issues faced by existing offline WA (e.g., the generalization performance is sensitive to the learning rate scheduler (WA_LR)) and how our HWA address them in Section IV. 3. Extensive experiments on CIFAR [2], Tiny-ImageNet [18], CUB200-2011 [19], CalTech256 [20] and ImagenNet [1] have been conducted to demonstrate the effectiveness of the proposed HWA. According to the results, HWA consistently outperforms the other related methods for a variety of architectures. For example, it outperforms the best state-of-the-art competitor by \(1.16\%\) on average across multiple architectures on CIFAR100 dataset. More experimental results could be found in Section V. The rest of the paper is organized as follows. In Section II, we introduce the related works. Section III gives the detailed procedure of our proposed HWA. In Section V, we discuss how HWA improves the training efficiency and the generalization ability of DNNs. In Section V, we evaluate HWA on several benchmark datasets and compare it with other related methods. Finally, Section VI concludes the paper. ## II Related Work Offline Weight AveragingAveraging a set of weights traversed by SGD offline can date back several decades in convex optimization [21, 22], but is not typically used to train neural networks. These techniques reduce the impact of noise and improve convergence rates. The Stochastic Weight Averaging (SWA) [15] is proposed to exploit the flatness of training objectives and improve generalization specific to deep learning. Based on the observation that weights of the networks sampled by FGE [23] are on the periphery of the most desirable solutions, SWA [15] creates a network with the averaged weights instead of forming an ensemble. While SGD tends to converge to the boundary of the low-loss region, SWA is able to find a point centered in this region with better generalization. Following up SWA, various extensions have been proposed for different purposes. SWAG [24] can approximate Bayesian model averaging in Bayesian deep learning and achieves the state-of-the-art uncertainty calibration results in various settings. SWALP [25] can match the performance of full-precision SGD training with quantized parameters. SWAP [26] greatly speeds up the training of neural networks by using large batch sizes. With a different motivation, SWAD [27] and DiWA [28] were proposed to improve the out-of-distribution (OOD) generalization performance of DNNs. In [29], the authors applies WA in the network pruning task. Online Weight AveragingThe classical parallel mini-batch SGD [30, 16] utilizes distributed hardwares to achieve fast and efficient training of large-scale DNNs. It typically samples gradients of different models in parallel and updates each model's weights using the averaged gradient in one step. The parallel mini-batch SGD can be interpreted as an online WA, where the local model updates its parameters to the averaged weights at every iteration. However, this algorithm imposes heavy communication overhead as it requires exchanging of local gradient information at every iteration. To reduce the communication overhead, model averaging techniques [9, 10, 11, 12, 13, 14] suggest performing the weight synchronization operation every \(H\) iterations. In order to balance the communication overhead and convergence speed, the value of parameter synchronization period \(H\) considered in these works is also relatively small, (e.g., \([1,64]\) in [9], \(10\) in [12], \([4,32]\) in [17]). One extreme case is the one-shot averaging [14], where weights are averaged only at the last iteration but may yield inaccurate solutions for certain non-convex optimization [12]. Theoretical analysis of the convergence speed of online WA could be found in [31, 13, 17]. While existing offline/online WA methods perform either offline parameter averaging or online parameter averaging, HWA performs both of them during the training procedure. Other Related WorksThe Lookahead optimizer [32] maintains a set of slow weights and fast weights, and updates the slow weights with the fast weights every \(H\) steps. The stochastic gradient descent with restarts (SGDR) [7] first introduces the idea of scheduling the learning rate cyclically as a modification to the common linear or step-wise decay Fig. 3: The top-1 test accuracy of online WA, offline WA, and HWA on CIFAR100 for ResNet56. strategy. Some studies [23] point out that SGDR can escape from local minimum and explore other regions. Recently, a training strategy named Improved Training of Convolutional Filters (RePr) [33] was proposed to improve the network on the filter level. RePr first freezes the overlapped filters to train the sub-network, and then restores the frozen filters and continues to train the full network. With a similar motivation, Filter Grafting (FG) [34] uses entropy-based criteria to measure the information of filters and grafts external information from other networks trained in parallel into invalid filters. SAM [35] is a novel optimizer that improves model generalization by simultaneously minimizing loss value and loss sharpness. ## III Detailed Procedure of HWA In this section, we introduce the detailed procedure of HWA and leave the analysis of how HWA works in Section IV. The general idea of HWA is given in Figure 1(c). In Algorithm 1 and 2, we also provide the pseudo-code of the online and offline modules of HWA, respectively. ### _Online Module of HWA_ At the online stage, HWA trains \(K\) models in parallel with different sampling orders. A standard SGD optimizer \(\mathcal{A}\) with a regular decaying learning rate scheduler is used to evolve each model by performing \(H\) sequential SGD updates to batches of training examples \(\psi\) sampled from the dataset \(\mathcal{D}\): \[\overbrace{\mathbf{W}_{e,t}^{\text{HWA}}}^{\text{Hwinds}} \leftarrow{\mathbf{W}_{e,t-1}^{k}}+\mathcal{A}\left(\mathcal{L}, \mathbf{W}_{e,t-1}^{k},\psi_{e,t}^{k}\right)\] \[\text{where }k\in\{1,2,\dots,K\}\text{, }t\in\{1,2,\dots,H\}\] Here \(\mathcal{L}\) is the loss function, and \(e\) denotes \(e_{th}\) averaging or synchronization cycle. After each model is updated for \(H\) iterations (\(\mathbf{W}_{e,0}^{k}\rightarrow\mathbf{W}_{e,H}^{k}\)), HWA takes the average of the weights of the \(K\) models in parallel to obtain the averaged weights for the \(e_{th}\) synchronization cycle \[\overbrace{\mathbf{W}_{e}}^{\text{Outer Weights}}=\frac{\sum_{k=1}^{K}\mathbf{W}_{e,H}^{k}}{K}\] Once completed, it synchronizes the weights of each model at the start of the next synchronization cycle \(\mathbf{W}_{e+1,0}^{k}\) to the averaged weights \[\mathbf{W}_{e+1,0}^{k}\leftarrow\overline{\mathbf{W}}_{e}\text{ \ where }k\in\{1,2,\dots,K\}\] Since \(\mathbf{W}_{e+1,t}^{k}\) is updated within a synchronization cycle and \(\overline{\mathbf{W}}_{e}\) is calculated outside of a synchronization cycle, we name them _Inner Weights_ and _Outer Weights_, respectively. ``` Input: Synchronization Period \(H\), Optimizer \(\mathcal{A}\), Loss Function \(\mathcal{L}\), Number of Models \(K\), Maximum Iterations \(T\) 1 Initialize Inner Weight \(\mathbf{W}_{0,0}^{k}\) for \(k\in\{1,2,\dots,K\}\) 2for\(i=1\) to \(T\)do 3\(e\leftarrow\lfloor(i-1)/H\rfloor\) (\(e_{th}\) synchronization cycle) 4\(t\gets i-e\times H\) (\(t_{th}\) step in the \(e_{th}\) synchronization cycle) 5fork = 1 to \(K\)do 6 Sample a batch of data \(\psi_{e,t}^{k}\) for model \(k\) 7\(\mathbf{W}_{e,t}^{k}\leftarrow\mathbf{W}_{e,t-1}^{k}+\mathcal{A}\left(\mathcal{ L},\mathbf{W}_{e,t-1}^{k},\psi_{e,t}^{k}\right)\) 8if\(t=H\)then 9\(\overline{\mathbf{W}}_{e}=\frac{\sum_{k=1}^{K}\mathbf{W}_{e,t}^{k}}{K}\) 10 Save checkpoint \(\overline{\mathbf{W}}_{e}\) 11fork = 1 to \(K\)do 12\(\mathbf{W}_{e+1,0}^{k}\leftarrow\overline{\mathbf{W}}_{e}\) ``` **Algorithm 1**Online Module of HWA ### _Offline Module of HWA_ At the offline stage, HWA also further averages the outer weights \(\overline{\mathbf{W}}_{e}\) saved at different synchronization cycles during the online stage. Unlike offline WA, HWA does not require a large constant or cyclical learning rate at the end of the training process. From our experiments, we find it works well with a regular decaying learning rate scheduler over the entire budget, e.g., a cosine decay or linear decay. While offline WA averages all the model checkpoints sampled from the time it starts averaging, HWA uses a slide window with a length of \(I\) and takes the average of outer weights at different synchronization cycles within the window. \[\overbrace{\overline{\mathbf{W}}_{e}}^{\text{HWA Weights}}=\frac{\sum_{t=e-I+1}^{e} \overline{\mathbf{W}}_{t}}{I}\] In practice, the offline WA module does not necessarily average all the outer weights \(\overline{\mathbf{W}}_{e}\) within the slide window. For example, it can take the average of outer weights \(\overline{\mathbf{W}}_{e}\) with index in multiples of a particular integer, e.g., \(\{\overline{\mathbf{W}}_{3},\overline{\mathbf{W}}_{6},\overline{\mathbf{W}}_{9 },\dots\}\). Besides, when we have sufficient training budget, we can try multiple possible \(I\in\mathbb{I}=\{I_{1},I_{2},\dots\}\) as the length of slide window also has a significant impact on the performance of the final averaged model \(\overline{\mathbf{W}}_{e}\). ``` Input: Checkpoints of Outer Weights \(\overline{\mathbf{W}}_{e}\) for \(e\in\{1,2,3...\}\), Slide Window Length \(I\). 1for\(e=1,2,\dots\)do 2\(\overline{\mathbf{W}}_{e}=\frac{\sum_{t=e-I+1}^{e}\overline{\mathbf{W}}_{t}}{I}\) Update batch normalization statistics if the DNN uses batch normalization ``` **Algorithm 2**Offline Module of HWA ## IV How HWA Works? In this section, we discuss how HWA improves the training efficiency and generalization ability of DNNs. ### _Convergence Condition of SGD_ In order to study how HWA improves SGD, here we first derive the convergence condition of SGD. Let \(R_{N}(\mathbf{W}_{e,t})=\frac{1}{N}\sum_{i=1}^{N}\mathcal{L}(\mathbf{W}_{e,t}, \psi_{i})\) denote the empirical risk of model \(\mathbf{W}_{e,t}\) and \(\psi_{i}=(x_{i},y_{i})\) denote a single training sample. Suppose the batch size is \(B\), then the gradient of a batch of samples is \[g(\mathbf{W}_{e,t},\psi_{e,t})=\frac{1}{B}\sum_{i=1}^{B}\nabla_{W}\mathcal{L}( \mathbf{W}_{e,t},\psi_{i})\approx\nabla_{W}R_{N}(\mathbf{W}_{e,t})\] On the assumption of Lipschitz-continuous gradient with Lipschitz constant \(L\) and the update at each iteration is \(\Delta W=-\eta g(\mathbf{W}_{e,t},\psi_{e,t})\), we have \[||\nabla_{W}R_{N}(\mathbf{W}_{e,t}+\Delta W)-\nabla_{W}R_{N}( \mathbf{W}_{e,t})||\leq L||\Delta W||_{2}\] \[\Rightarrow R_{N}(\mathbf{W}_{e,t}+\Delta W)-R_{N}(\mathbf{W}_{e,t})\] \[\quad\leq\frac{1}{2}L||\Delta W||_{2}^{2}+\nabla_{W}R_{N}( \mathbf{W}_{e,t})^{T}\Delta W\] \[\Rightarrow R_{N}(\mathbf{W}_{e,t+1})-R_{N}(\mathbf{W}_{e,t})\] \[\quad\leq\frac{1}{2}L\eta^{2}||g(\mathbf{W}_{e,t},\psi_{e,t})|| _{2}^{2}-\eta\nabla_{W}R_{N}(\mathbf{W}_{e,t})^{T}g(\mathbf{W}_{e,t},\psi_{e,t }),\] Suppose \(\Psi_{e,t}\) denotes the variable of mini-batch samples, the empirical risk is expected to decrease if \[\mathbb{E}_{\Psi_{e,t}}\left[R_{N}(\mathbf{W}_{e,t+1})\right]-R_ {N}(\mathbf{W}_{e,t})\leq 0\] \[\Rightarrow \frac{1}{2}\eta L\mathbb{E}_{\Psi_{e,t}}\left[||g(\mathbf{W}_{e,t},\Psi_{e,t})||_{2}^{2}\right]\] \[-\nabla_{W}R_{N}(\mathbf{W}_{e,t})^{T}\mathbb{E}_{\Psi_{e,t}} \left[g(\mathbf{W}_{e,t},\Psi_{e,t})\right]\leq 0\] \[\Rightarrow \frac{1}{2}\eta L||\mathbb{E}_{\Psi_{e,t}}\left[g(\mathbf{W}_{e,t},\Psi_{e,t})\right]||_{2}^{2}\] \[+\frac{1}{2}\eta L\mathbb{E}_{\Psi_{e,t}}[||g(\mathbf{W}_{e,t}, \Psi_{e,t})-\nabla_{W}R_{N}(\mathbf{W}_{e,t})||_{2}^{2}]\] \[\leq\nabla_{W}R_{N}(\mathbf{W}_{e,t})^{T}\mathbb{E}_{\Psi_{e,t}} \left[g(\mathbf{W}_{e,t},\Psi_{e,t})\right]\] \[\Rightarrow \frac{1}{2}L\mathbb{E}_{\Psi_{e,t}}[||g(\mathbf{W}_{e,t},\Psi_{e,t})-\nabla_{W}R_{N}(\mathbf{W}_{e,t})||_{2}^{2}]\] \[\leq(\frac{1}{\eta}-\frac{1}{2}L)||\nabla_{W}R_{N}(\mathbf{W}_{e,t})||_{2}^{2}\] For a fixed dataset \(\mathcal{D}\) and model \(\mathbf{W}_{e,t}\), the right hand side \((\frac{1}{\eta}-\frac{1}{2}L)||\nabla_{W}R_{N}(\mathbf{W}_{e,t})||^{2}\) is determined by the learning rate \(\eta\), and left hand side \(\frac{1}{2}L\mathbb{E}_{\Psi_{e,t}}[||g(\mathbf{W}_{e,t},\Psi_{e,t})-\nabla_{ W}R_{N}(\mathbf{W}_{e,t})||_{2}^{2}]\) is controlled by the batch size. As long as the learning rate \(\eta\) stays constant, model \(\mathbf{W}_{e,t}\) would converge only if the mini-batch gradient \(g(\mathbf{W}_{e,t},\Psi_{e,t})\) estimates \(\nabla_{W}R_{N}(\mathbf{W}_{e,t})\) accurately enough. Therefore, with a constant learning rate \(\eta\), the optimizer would converge to a certain point and then start to oscillate and explore around the minima. This phenomenon is clearly shown in Figure 4, where we plot the training and test accuracy of ResNet20 on CIFAR100 when it is trained by SGD with a constant learning rate \(\eta\in\{0.1,0.25\}\). As we can see, the training and test accuracy start to oscillate after dozens of epochs, which indicates that the optimizer is exploring around the local minima instead of progressing to the local minima. ### _How HWA Improves Training Efficiency_ Though the loss functions of DNNs are known to be nonconvex [36], the loss surfaces over the trajectory of SGD are approximately convex [37]. According to the convergence condition, SGD would oscillate and explore around the local minima after it converges to a certain point unless the learning rate \(\eta\) further decays. Therefore, by taking the average of the weights of multiple model checkpoints, the averaged solution would quickly progress to a point closer to the minima with training lower loss. This scenario is shown in Figure 5, where we use the visualization tool [38] to project model checkpoint \(\mathbf{W}^{1}_{101,H}\) and \(\mathbf{W}^{2}_{101,H}\) (two models in parallel) and their corresponding averaged weights \(\overline{\mathbf{W}}_{101}\) on the training loss surface of ResNet32 on CIFAR100. Note that, \(\mathbf{W}^{1}_{101,H}\) and \(\mathbf{W}^{2}_{101,H}\) are evolved by SGD for \(H=391\) steps (one epoch) from the same starting point \(\overline{\mathbf{W}}_{100}\), and hence they are within the same local minima. Through the online averaging operation, the averaged solution \(\overline{\mathbf{W}}_{e}\) immediately reaches a location closer to the minima on the training loss surface. Similar to the online averaging operation of HWA, the offline averaging operation of HWA also speeds up convergence in a similar way. However as the offline averaging operation of HWA is performed vertically at different synchronization cycles on top of the outer weights \(\widehat{\mathbf{W}}_{e}\) obtained during the online stage, the HWA weights \(\widehat{\overline{\mathbf{W}}}_{e}\) progresses to a point closer to the minima than \(\widehat{\mathbf{W}}_{e}\). To show this scenario, we also use the visualization tool [38] to project the offline averaging operation of HWA in Figure 6. Therefore, by performing the weight averaging operations in both horizontal and vertical directions hierarchically, HWA can progress to the local minima more quickly than online WA alone, which only performs the averaging operation horizontally. In Figure 7, we plot the top-1 test accuracy and test Fig. 4: The top-1 accuracy of ResNet20 on CIFAR100 with different constant learning rates. Fig. 5: The projection of the online averaging operation of HWA on the training loss surface of ResNet32 on CIFAR100. loss of _Inner Weights_\(\mathbf{W}_{e,H}^{k}\), _Outer Weights_\(\overline{\mathbf{W}}_{e}\), and _HWA Weights_\(\overline{\overline{\mathbf{W}}}_{e}\) for ResNet32 on CIFAR10 and CIFAR100, where the synchronization period is \(H=391\) (i.e., one epoch) and the length of slide window is \(I=20\). As we can observe, the _HWA Weights_\(\overline{\overline{\mathbf{W}}}_{e}\) achieves faster convergence than _Outer Weights_\(\overline{\mathbf{W}}_{e}\) and inner weights \(\mathbf{W}_{e,H}^{k}\). ### _How HWA Improves Generalization Ability_ One popular hypothesis about the _generalization ability_1 of DNNs [39, 40, 15] is that the generalization performance of DNNs is correlated with the flatness of its local minima, and a sharp local minimum typically tends to generalize worse than the flat ones [41]. While most existing works (e.g., [15, 42]) attribute the better generalization ability of neural networks to a wider local minimum, the location to which a network converges within a local minimum also greatly affects the generalization performance. As observed in [43], the loss landscape of local minima is asymmetric and exists both sharp and flat directions, and the solution locates at the flat side has better generalization performance due to the random shift between the training loss and test loss. Footnote 1: In this paper, we refer to generalization ability as the ability in predicting unseen, _in-distribution_ data (e.g., test data). According to the convergence condition of SGD, when the model checkpoints are sampled with the same learning rate, they would be distributed around the local minima with similar empirical risks (refer to Figure 4). As a result, as illustrated in Figure 8, the averaged model tends to be biased to the flat side of the local minima. Due to the shift between the training and test loss, the averaged model has better generalization ability than the model with the minimal training loss. Such an example is shown in Figure 9, which plots the accuracy and loss of ResNet20 on CIFAR100 along the direction between an averaged model (location \(x=0\)) and an individual model (location \(x=1\)). Apparently, all the models between \(x=0\) and \(x=1\) are in the same local minima because there is no sharp drop in training and test accuracy. Despite the lower training accuracy, the averaged model achieves higher test accuracy than the individual model, because it is biased to the flat side of the loss landscape. This also implies that the training accuracy is a poor indicator of the generalization ability. Figure 8 also explains why offline WA is sensitive to the choice of learning rate used to sample model checkpoints. According to the convergence condition of SGD, the learning rate determines the empirical risk or loss of the sampled model Fig. 8: A simple illustration of why averaged model tends to be biased to the flat side of the local minima. Fig. 6: The projection of the offline averaging operation of HWA on the training loss surface of ResNet32 on CIFAR100. Fig. 7: Top-1 test accuracy and test loss of _Inner Weights_\(\mathbf{W}_{e,H}^{k}\), _Outer Weights_\(\overline{\mathbf{W}}_{e}\), and _HWA Weights_\(\overline{\mathbf{W}}_{e}\) for ResNet32 on CIFAR10 and CIFAR100. The learning rate decays along a cosine curve. Fig. 9: The accuracy and loss on CIFAR100 along the direction between an averaged model (location \(x=0\)) and an individual model (location \(x=1\)). hese model. The average of checkpoints (refer to Figure 4) and hence their locations on the loss landscape. Since the averaged model is obtained by taking the average of these model checkpoints, its location within the local minima is also determined by the learning rate with which these model checkpoints are sampled. As a result, a choice of learning rate that is either too small or too large can be detrimental to the performance of offline WA, which leverages a large constant or cyclical learning rate to sample model checkpoints. For example in Figure 8, the averaged model obtained with an intermediate learning rate achieves the best test performance. Unlike offline WA, as illustrated in Figure 10, HWA takes the average of model checkpoints sampled with different learning rates with a slide window of length \(I\). As a result, the averaged model \(\overline{\overline{\mathbf{W}}}_{e}\) at different synchronization cycles is located at different positions with different distances to the minima of the training loss surface. Compared to offline WA, HWA is able to explore more locations on the flat side of the local minima and hence is more likely to find a better averaged model. Note that, the averaged model at the last synchronization cycle does not necessarily be the best averaged model. For example, as illustrated in Figure 10, the best averaged model \(\overline{\overline{\mathbf{W}}}_{7}\) is obtained at the \(7_{th}\) synchronization cycle. We also plot the training and test accuracy of \(\overline{\overline{\overline{\mathbf{W}}}}_{e}\) as a function of epochs for ResNet110 on CIFAR100 in Figure 11, where the synchronization period is one epoch and the length of slide window \(I=20\). As we can observe, the averaged model \(\overline{\overline{\mathbf{W}}}_{e}\) around the \(150_{th}\) synchronization cycle achieves the best test accuracy. Therefore, in practice, we use techniques such as early stopping to obtain the best averaged model. Though the averaged model with the minimal training loss does not necessarily be the averaged model with the best validation performance, in most cases, the best averaged model is located close to the minima of the training loss. Therefore, it is important for the optimizer to explore more locations close to the minima of the training loss. With the help of the online WA module, HWA progresses to the regions close to the minima of training loss more quickly than naive offline WA, which as a result, helps it to find a better averaged model. **Discussion:** The'restart' mechanism [7, 8], which switches the status of a model to a lower fitting level to the training data (i.e., higher training loss), is claimed to achieve a longer-term beneficial effect on generalization performance at the cost of short term benefit. While existing techniques [7, 8] restart the training by increasing the learning rate, we observe that the online averaging module of HWA also achieves a similar'restart' effect. We observe that, in general, the loss of the averaged model \(\overline{\overline{\mathbf{W}}}_{e}\) decreases over training time. However, within a synchronization cycle, the loss of inner weights \(\mathbf{W}_{e,t}^{k}\) would surprisingly increase with iteration times \(t\). For example, as shown in Figure 12, after each model is updated by the optimizer for \(H\) steps (\(\mathbf{W}_{100,0}^{k}\rightarrow\mathbf{W}_{100,H}^{k}\)), the training loss increases instead of decreasing. Note that the online averaging operation of HWA would result in a significant decrease in the empirical risk, i.e., \[R_{N}(\overline{\mathbf{W}}_{e})\ll R_{N}(\mathbf{W}_{e,H}^{k}), \ \mathbf{W}_{e+1,0}^{k}\leftarrow\overline{\mathbf{W}}_{e}\] \[\Rightarrow R_{N}(\mathbf{W}_{e+1,0}^{k})\ll R_{N}(\mathbf{W}_{e,H}^{k})\] As a result, the convergence condition at the start of the \(e+1_{th}\) synchronization cycle does not hold any more for \(\mathbf{W}_{e+1,0}^{k}\), and the optimizer \(\mathcal{A}\) would receive more noise information than gradient information within the synchronization cycle. That's why the empirical risk \(R_{N}(\mathbf{W}_{e+1,t}^{k})\) increases in general with the iteration times \(t\) within a synchronization cycle. While there is no consensus on how the'restart' mechanism improves the training of DNNs, we provide a possible explanation to the success of the'restart' mechanism: A neural network tends to generalize easy training samples and memorizes the "hard" samples through the massive parameters. Once the hard samples are memorized, their losses would decrease to Fig. 11: The training and test accuracy of \(\overline{\overline{\mathbf{W}}}_{e}\) as a function of epoch (the synchronization period is one epoch) for ResNet110 on CIFAR100. Fig. 12: The projection of the ‘restart’ effect of HWA on the training loss surface of ResNet32 on CIFAR100 Fig. 10: The averaged model \(\overline{\overline{\mathbf{W}}}_{e}\) at different synchronization cycles is located at different positions on the loss landscape zero quickly, and hence the network overfits the hard samples. On the other hand, restart techniques switch the network status back to a lower fitting level, and hence the hard samples memorized by the network are more likely to be forgotten. ## V Experiment In this section, we evaluate our HWA on several benchmark datasets CIFAR10 and CIFAR100 [2], Tiny-ImageNet [44], CUB200-2011 [19], CalTech256 [20] and ImageNet [1], and also compare it with other related methods. The two CIFAR datasets consist of images with a resolution of \(32\times 32\). CIFAR10 contains 10 classes and CIFAR100 contains 100 classes. Both datasets contain a train set of \(50000\) images and a test set of \(10000\) images. Tiny-ImageNet [44] comprises \(50000\) colored images over \(200\) classes with a resolution of \(64\times 64\). The CUB-200-2011 contains \(11788\) images of \(200\) categories belonging to birds. The CalTech256 is an object recognition dataset comprising \(30607\) real-world images with different sizes over 256 object classes and an additional clutter class. Imagenet is an image classification dataset with over 1.3 million images and contains 1000 classes. In particular, the following methods are involved in the experiments. 1. **Baseline**: the conventional SGD with step-wise learning rate decay (\(0.1\) at every \(60\) epochs). 2. **CA**: the cosine learning rate strategy, which is claimed to outperform other learning rate schedulers. 3. **FG**: filter grafting for deep neural networks [34]. 4. **RePr**: improved training of convolutional filters [33]. 5. **SWA**: stochastic weight averaging (i.e., offline WA). 6. **SAM**: shareness-aware minimization [35]. 7. **HWA**: our proposed HWA algorithm with default synchronization period \(H=N/B\), where \(N\) is the number of training samples and \(B\) is the batch size. _Among the above mentioned techniques, SWA is the primary work we aim to compare because both HWA and SWA are weight averaging strategies._ ### _Comparison with Other Methods_ In this section, we experimentally compare our HWA with other methods on CIFAR10 and CIFAR100 datasets in Table II2. We use bold font to highlight the best accuracy and blue color to denote the second-best result. For CIFAR, we evaluate our HWA on three popular networks: VGG, ResNet and MobileNetV2. All the networks are trained by SGD with a momentum of 0.9 and a weight decay of \(5\times 10^{-4}\). A cosine learning rate strategy over the whole budget is used by default. The initial learning rate is set to 0.1 for ResNets and VGG, and 0.05 for MobileNetV2. Footnote 2: The experimental results of RePr [33] reported in Table II come from the corresponding paper because the code of RePr [33] is not publicly available. “- denotes the result is not reported in the corresponding paper. For SWA [15] and FG [45], the experiments are conducted in our implementation using the code provided by the original group. The results in Table II demonstrate that HWA achieves the best performance among all the training schemes. On average, it improves the baseline by around \(1.8\%\) on CIFAR10 and \(3.8\%\) on CIFAR100. In particular, it outperforms the method with the second-best accuracy by \(1.16\%\) on CIFAR100 on average. Compared to SWA, the performance of HWA is more stable. For example, the test accuracy of SWA is even lower than the baseline on CIFAR100 for ResNet110. On the other hand, with the same experiment setting, SWA achieves the second-best results for ResNet20, ResNet56 and MobileNetV2. These results also support our claim that SWA is sensitive to the learning rate scheduler at the sampling stage. ### _Contribution of Online and Offline WA Module_ Both the online and offline WA module of HWA can improve the generalization performance of DNNs. In Table III, we report the contributions of the online WA module of HWA and the additional improvement from the offline WA module. On average, the online WA module provides an improvement around \(0.8\%\) and \(1.4\%\) on CIFAR10 and CIFAR100, respectively. By applying the offline WA module, we obtain an additional improvement around \(0.4\%\) and \(1.7\%\) on CIFAR10 and CIFAR100, respectively. As we can observe, the performance of the online WA module is not stable when we apply it alone. For example, it provides almost no notable improvement for ResNet32 on CIFAR100. However, by additionally applying the offline WA module, HWA outperforms CA by around \(2.5\%\). On the other hand, the online WA module of HWA improves CA by about \(1.1\%\) for MobileNetV2 on CIFAR10. However, the additional gain in test accuracy from the offline WA module is negligible (around \(0.2\%\)). In sum, the hybrid of online and offline WA can improve the stability of HWA. ### _Number of Models in Parallel_ In this section, we explore how the number of models in parallel affects the final generalization performance of HWA. In Table IV, we report the test accuracy of HWA on CIFAR10 and CIFAR100 with varying numbers of models trained in parallel during the online stage. As we can observe, though the best test accuracy is achieved when the number of models in parallel is \(K=3\) or \(K=4\), the improvement in test accuracy is not very notable as \(K\) increases from \(2\) to \(4\). Thus, in practice, we can simply set \(K=2\) when there is a limited training budget. ### _Slide Window Length_ In this section, we conduct several ablation experiments on CIFAR10 and CIFAR100 with ResNet20 and ResNet32 to study the influence from the length of slide window. Each experiment is repeated \(5\) times and a slide window with length of \(I=20\) or \(I=50\) is considered in the experiment. In Figure 13, we present the box-plot of the experimental results. As we can observe, the length of the slide window would exert different influences on the test accuracy for different datasets. Therefore, we may achieve further improvement by choosing a suitable slide window length for different datasets and architectures for the offline WA module of HWA. ### _Results on Other Datasets_ In this section, we evaluate our proposed HWA on several other datasets: Tiny-ImageNet, CUB200-2011 [19], CalTech256 [20] and ImageNet [1]. We use the models implemented in Torchvision in the experiment. For comparison, we also report the experimental results of the baseline and SWA, which is the primary technique we aim to compare. Unless mentioned otherwise, the experiment setting for CIFAR is also used in these experiments. **Tiny-ImageNet:** In Table V we show the top-1 test accuracy on Tiny-ImageNet, which comprises \(50000\) colored images over \(200\) classes with a resolution of \(64\times 64\). In the training process, a \(64\times 64\) crop is randomly sampled from the original image or its horizontal flip with a padding size of \(8\). The initial learning rate is \(0.1\) for ResNet18 and \(0.05\) for MobileNetV2 and ShuffleNetV2. **CUB200-2011:** Table VI shows the top-1 test accuracy of Fig. 14: Training and test accuracy of HWA as a function of epochs for VGG16, MobileNetV2 and ResNet110 on CIFAR100. Fig. 13: The box-plot of the test accuracy of ResNet20 and ResNet32 on CIFAR10 and CIFAR100. different models on CUB200-2011, which contains \(11788\) images of \(200\) categories belonging to birds. During training, a \(224\times 224\) crop is randomly sampled from the original image or its horizontal flip and no other data augmentation is applied. The initial learning rate is \(0.1\) for all models. online WA and offline WA into a unified training framework. Unlike online or offline WA, which only serves a single purpose, i.e., improving training efficiency or generalization ability, the hybrid paradigm of HWA is able to achieve both of them with better performance. By performing the weight averaging operations in both horizontal and vertical directions hierarchically, HWA outperforms online WA and offline WA alone. We also analyze how HWA improves the training efficiency and generalization ability of DNNs from the perspective of the loss landscape of DNNs. Finally, extensive experimental results demonstrate the effectiveness of the proposed HWA.
2303.01140
Cardinality Estimation over Knowledge Graphs with Embeddings and Graph Neural Networks
Cardinality Estimation over Knowledge Graphs (KG) is crucial for query optimization, yet remains a challenging task due to the semi-structured nature and complex correlations of typical Knowledge Graphs. In this work, we propose GNCE, a novel approach that leverages knowledge graph embeddings and Graph Neural Networks (GNN) to accurately predict the cardinality of conjunctive queries. GNCE first creates semantically meaningful embeddings for all entities in the KG, which are then integrated into the given query, which is processed by a GNN to estimate the cardinality of the query. We evaluate GNCE on several KGs in terms of q-Error and demonstrate that it outperforms state-of-the-art approaches based on sampling, summaries, and (machine) learning in terms of estimation accuracy while also having lower execution time and less parameters. Additionally, we show that GNCE can inductively generalise to unseen entities, making it suitable for use in dynamic query processing scenarios. Our proposed approach has the potential to significantly improve query optimization and related applications that rely on accurate cardinality estimates of conjunctive queries.
Tim Schwabe, Maribel Acosta
2023-03-02T10:39:13Z
http://arxiv.org/abs/2303.01140v2
# Cardinality Estimation over Knowledge Graphs with Embeddings and Graph Neural Networks ###### Abstract Cardinality Estimation over Knowledge Graphs (KG) is crucial for query optimization, yet remains a challenging task due to the semi-structured nature and complex correlations of typical Knowledge Graphs. In this work, we propose _GNCE_, a novel approach that leverages knowledge graph embeddings and Graph Neural Networks (GNN) to accurately predict the cardinality of conjunctive queries. _GNCE_ first creates semantically meaningful embeddings for all entities in the KG, which are then integrated into the given query, which is processed by a GNN to estimate the cardinality of the query. We evaluate _GNCE_ on several KGs in terms of q-Error and demonstrate that it outperforms state-of-the-art approaches based on sampling, summaries, and (machine) learning in terms of estimation accuracy while also having lower execution time and less parameters. Additionally, we show that _GNCE_ can inductively generalize to unseen entities, making it suitable for use in dynamic query processing scenarios. Our proposed approach has the potential to significantly improve query optimization and related applications that rely on accurate cardinality estimates of conjunctive queries. Cardinality Estimation Knowledge Graphs Graph Neural Networks Knowledge Graph Embeddings ## 1 Introduction A Knowledge Graph (KG) is a semi-structured data model that allows for representing interconnected data. In KGs, statements are represented in the form of a graph, where labeled nodes typically correspond to entities, and directed, labeled edges represent connections between the nodes. Nowadays, KGs are fueling diverse applications like question-answering and recommender systems and also serve as semantic databases [23]. Similar to other database technologies, the data encoded in a KG can be queried using a structured query language like SPARQL [12] or Cypher [16]. In particular, conjunctive queries over KGs can be formulated also as graphs, where nodes and edges can be either _constants_ (i.e., values matched over the KG) or _variables_ (i.e., placeholders). The computation of answers for a given conjunctive query is carried out as a graph pattern-matching process, where the query cardinality corresponds to the number of subgraphs in the KG that are isomorphic to the query graph. To efficiently execute a (conjunctive) query over a KG, query engines implement optimization techniques that rely on cardinality (alt. selectivity) estimates of sub-queries. Cardinality here is defined as the number of answers produced by an executed query. The optimizer relies on these estimates to determine the order in which the sub-queries are evaluated over the KG to minimize the number of intermediate results, thus, speeding up the query execution. One of the challenges in query optimization over KGs is that conjunctive queries typically contain many joins; in this context, a join occurs when subgraphs of the query graph are connected by the same variable. For example, each pair of edges connected to the same entity can be seen as a join. Another challenge is imposed by the semi-structured nature of KGs, which can lead to skewed data distributions and irregular correlations between entities and predicates. These are difficult to capture accurately in traditional statistical summaries [23, 24] for different classes of graph queries. To overcome the limitations of statistical summaries, recent approaches based on Machine Learning (ML) have been proposed to the problem of query cardinality estimation (Davitkova et al., 2022; Zhao et al., 2021). These models rely on a Neural Network (NN) or Graph Neural Network (GNN) to learn the underlying data distributions in a KG. For this, the models are trained in a supervised manner using sampled query graphs and their corresponding cardinalities. While it has been shown that these approaches are able to capture arbitrary correlations more effectively than other summaries, they still present several drawbacks. First, during learning, these approaches do not leverage individual characteristics of entities and predicates in the KG, i.e., the initial representations are given by vectors that lack meaning or relevant information about the elements. Second, some of these approaches do not perform well in _inductive cases_, i.e., when entities or predicates that were not seen by the model occur in queries. Inductive cases occur in KGs that are frequently updated with new elements. Third, the training of the state-of-the-art models requires the optimization of a large number of parameters, which means that a large number of training samples are required to perform accurate predictions. This considerably hinders the scalability of state-of-the-art ML approaches to large KGs. In this work, we present _GNCE_, _Graph Neural Cardinality Estimation_, a solution to mitigate the drawbacks of the state of the art. _GNCE_ is also based on a Graph Neural Network (GNN) as this is an expressive model (Xu et al., 2019) that can naturally capture the graph structure of the query. Furthermore, our approach exploits recent advances in Knowledge Graph Embeddings (KGE) (Rossi et al., 2021) to provide semantically meaningful features of the query elements to the GNN. KGE are low-dimensional vectors that represent entities and predicates that capture latent semantic information about the KG. KGE provide two key advantages to _GNCE_: to learn data correlations from compact yet meaningful representations, and to generalize to new (unseen) entities and predicates. In addition to KGE, _GNCE_ is equipped with a novel message-passing function tailored to directed graphs; this in turn supports maximal information flow in the GNN to capture latent structures of the graph more accurately than other GNN-based solutions. In this way, the combination of KGE and a modulated message-passing function allows _GNCE_ to address the first two drawbacks of the state of the art. Lastly, as both the meaning and structure of the query graph are largely covered by the KGE and the GNN, _GNCE_ can afford to have a relatively simple architecture in terms of the number of learnable parameters. This makes _GNCE_ applicable to large KGs thus overcoming the third limitation of current solutions. In summary, the contributions of this work are: 1. We present a novel supervised model, termed _GNCE_, for query cardinality estimation over KGs that effectively combines Graph Neural Networks and Knowledge Graph Embeddings. 2. We devise an inductive solution, i.e., new data can be added to the KG without retraining the whole model. 3. We assemble a fast and lightweight ML architecture that is parameter- and data-efficient, i.e., _GNCE_ can scale up to large KGs. 4. We show that _GNCE_ considerably outperforms the state of the art using well-known benchmarks. The remainder of this paper is organized as follows. Section 2 introduces the necessary concepts related to Knowledge Graphs and Graph Neural Networks. Related Work is presented in Section 3. A detailed description of our approach is given in Section 4. The experimental study and results are detailed in Section 5. Lastly, conclusions and outlook for future work are presented in Section 6. ## 2 Preliminaries ### Knowledge Graphs A knowledge graph (KG) is defined as a directed graph, where nodes and edges are identified with labels (Hogan et al., 2022). In addition, nodes can be assigned to classes1, which correspond to groups of nodes that share some characteristics. To represent KGs, there exist several data models including the Resource Description Framework (RDF) (Cyganiak et al., 2014) and Property Graphs (Angles, 2018). In this work, we follow the definition of RDF where every statement is modeled as a triple. Footnote 1: In the literature, sometimes classes are also referred to as _labels_ but these should not be confused with the labels/identifiers. **Definition 2.1**.: A knowledge graph is a directed, labeled graph \(\mathcal{G}=(V,E,L,\mathcal{L}_{\mathcal{G}})\), with \(V\) the set of nodes, \(E\) the set of edges, \(\mathcal{L}_{\mathcal{G}}\) the set of labels, and a mapping \(L:V\cup E\rightarrow\mathcal{L}_{\mathcal{G}}\). A triple \(t=(s,p,o)\) is a labelled edge, i.e., \((s,p,o)=(L(v_{i}),L(e),L(v_{j}))\) where \(e\in E\) and \(v_{i},v_{j}\in V\). The elements of a triple are referred to as atoms. Questions over KGs can be formulated as structured queries. We focus, in this work, on _conjunctive queries_ which can be defined also as a graph where atoms are either instantiated to (bound) _terms_ using labels, or _variables_ that act as placeholders that can be matched over the KG. **Definition 2.2**.: Consider the set of variables \(\mathcal{V}\) such that \(\mathcal{V}\cap\mathcal{L}_{\mathcal{G}}=\emptyset\). A query graph \(Q=(V_{Q},E_{Q},L_{Q},\mathcal{L}_{\mathcal{G}}\cup\mathcal{V})\) is a directed graph, where atoms (nodes or edges) can correspond to labels or variables, i.e., \(L_{Q}:V_{Q}\cup E_{Q}\rightarrow\mathcal{L}_{\mathcal{G}}\cup\mathcal{V}\). Specifically, the term triple pattern refers to an edge in the query graph. Answers to a query are then found by matching the corresponding query graph over the KG. This process is known as _pattern matching_, where atom variables are mapped to labels in the graph. A query solution is found when there exists a subgraph in the KG that is isomorphic to the query graph. In particular, in KGs with bound atoms (i.e., no variables in the KG), this is equivalent to simply replacing variables in the query and determining whether the resulting graph is a subgraph in the KG. **Definition 2.3**.: Given a KG \(\mathcal{G}\) and a query graph \(Q\), consider a mapping \(\mu:\mathcal{V}\mapsto\mathcal{L}_{\mathcal{G}}\). We denote \(\mu(Q)\) as the resulting graph of applying \(\mu(v)\) for each \(v\in\mathcal{V}\). If \(\mu(Q)\) is a subgraph of \(\mathcal{G}\), then \(\mu(Q)\) is a query solution to \(Q\) over \(\mathcal{G}\). The _cardinality_ of a query \(Q\) over \(\mathcal{G}\), denoted \(||Q||_{\mathcal{G}}\), is the number of different solutions as of Definition 2.3. Furthermore, we define the _selectivity_ of \(Q\) as its cardinality divided by the number of subgraphs in \(\mathcal{G}\) that have the _same structure or shape_ as \(Q\). To formally define this, consider \(Q_{\mathcal{V}}\) the query graph obtained by replacing all the atoms in \(Q\) with variables. We say that a solution \(\mu(Q_{\mathcal{V}})\) has the _same shape_ as \(Q\). Then, the selectivity of \(Q\) is given by \(\frac{||Q||_{\mathcal{G}}}{||Q_{\mathcal{V}}||_{\mathcal{G}}}\). ### Knowledge Graph Embeddings Knowledge Graph Embeddings (KGE) are low-dimensional vectors of the atoms (entities and predicates) in a KG. These vectors encode latent semantic information about the atoms that is not explicitly available in the KG. For this reason, KGE usually achieve superior results in downstream tasks [14], e.g., link prediction, entity classification, clustering, etc., in comparison to approaches that only rely on the (explicit) statements and the structure of the KG. To compute KGE, existing models for representation learning over KGs comprise an embedding space, a scoring function \(f\), and a suitable loss function \(l\). The embedding space is typically a vector space over real or complex numbers, with dimensions ranging from dozens to a few hundred. The scoring function \(f\) assigns a score to a triple \((s,p,o)\) where a larger score means that the triple is more probable in a KG \(\mathcal{G}\) under the model, while lower scores indicate a lower probability. The loss function \(l\) is used to actually fit the model and drives it to assign high scores to _true triples_ - statements that are assumed correct in the KG - and low scores to _false triples_ - statements that do not and should not exist in the KG. An overview of state-of-the-art KGE is provided by Rossi et al. [14]. Due to differences in their components and learning process, different KGE models are able to capture different latent aspects of KGs, which makes certain KGE more suitable for specific tasks. For instance, some KGE models (e.g., translational models [14]) learn from individual triples in the KG, which are well suited for link prediction. Other models (e.g., RDF2Vec [15] or Riddle [21]) are able to learn from larger structures like subgraphs, which are suited for tasks that account for the semantic similarity and relatedness of atoms like entity type prediction or clustering. In this work, we are interested in the latter group of KGE models, as learning from subgraphs allow for capturing the correlations of atoms in the KG effectively. This is achieved with Rdf2Vec [15] which implements the _skip-gram model_[15] based on random walks of atoms in a KG. A random walk over a KG is generated by traversing the graph starting from an arbitrary node, following an edge to another node, and so on. Given a random walk of atoms \(w_{1},...,w_{W}\) in a KG of length \(W\), the objective of RDF2Vec is to maximize the following log probability (i.e. minimize its negative, which can be seen as the loss function in KGE): \[\frac{1}{W}\sum_{t=1}^{W}\sum_{-c\leq j\leq c,j\neq 0}\log p(w_{t+j}|w_{t}) \tag{1}\] That is, given a target word \(w_{t}\), we try to maximize the probability of all words (summation over \(j\)) that are at most \(c\) hops away in the walk. We do that for every word in the random walk (summation over \(t\)). The conditional probability of a word \(w_{o}\) given another word \(w_{i}\), which can be seen as the analog to the scoring function in other KGE methods, is given as: \[p(w_{o}|w_{i})=\frac{\exp(v_{w_{o}}^{\prime\top}v_{w_{i}})}{\sum_{w=1}^{|V \cup E|}\exp(v_{w}^{\prime\top}v_{w_{i}})} \tag{2}\] Here, \(v_{w_{j}}\) denotes the input vector (embedding) of atom \(w_{j}\), while \(v_{w_{j}}^{\prime}\) denotes the so called output vector of \(w_{j}\). Those have the same dimension as the input vector but are not used as the final embeddings. They are introduced to make the model more expressive and have different representations for target words and context words. As we can see, the unnormalized conditional probability is estimated as the exponent of the dot product between the input and output vectors of both atoms. This dot product gets maximized if the angle between the 2 vectors is \(0\). That is the case if they are the same vector or lay on the same 1-D subspace. Thus, the optimization of Eq. (1) drives embeddings of atoms with the same context to be close to each other. That is especially true for atoms that occur together in the graph, i.e. when the joint probability of observing them is high. Note that a normalized probability is obtained by dividing by the sum of all possible probabilities (often termed partition function). That sum is difficult to calculate and in practice approximated (Ristoski and Paulheim, 2016). The important takeaway point here is that the embeddings generated by RDF2Vec encode the atom's relatedness and correlate with the joint probability of observing them. Our hypothesis is thus that RDF2Vec embeddings are suitable for atom representation in estimating query cardinalities over KGs. ### Graph Neural Networks A Graph Neural Network (GNN) is a special form of Neural Network (NN) that is tailored to graph-structured data. The distinct feature of GNNs is that they are invariant with respect to a permutation of the nodes of the input graph (Bronstein et al., 2021). This means that the output of the model is the same even if the atoms in the graph are reordered. Permutation invariance makes GNNs parameter and data efficient (Bronstein et al., 2021). The model is parameter efficient as it needs fewer learnable parameters because it is not necessary to learn different permutations of the same graph structure. It is also data efficient as the model needs a relatively low number of examples to perform well. One typical task GNNs are used for is graph-level prediction. Here, given a graph as input, the GNN predicts quantities that hold for the whole graph. E.g. if a molecular graph is toxic or a social network is racist. Important for us, predicting the cardinality given a query graph can be considered a graph-level prediction. GNNs work under the message-passing framework, where in every layer \(k\) in the GNN the input representations of the nodes are updated based on _messages_ from all connected neighbors. The most generic _message-passing function_ for a node is given by (Team, 2022): \[x_{i}^{(k)}=\gamma^{(k)}\left(x_{i}^{(k-1)},\square_{j\in\mathcal{N}(i)}\phi^ {(k)}\left(x_{i}^{(k-1)},x_{j}^{(k-1)},e_{j,i}\right)\right) \tag{3}\] Here, \(\gamma\) and \(\phi\) are differentiable functions, and \(\square\) is a differentiable as well as permutation invariant function. \(\mathcal{N}_{i}\) is the set of direct neighboring nodes of the \(i\)-th node. For a node \(x_{i}\), its previous representation denoted \(x_{i}^{(k-1)}\) gets non-linearly transformed to a new representation \(x_{i}^{(k)}\) by combining \(x_{i}^{(k-1)}\) with neighboring nodes' representations as well as the edges between them(the messages). In order to perform graph classification, the individual node features of all nodes need to be combined into a fixed-length vector. For that a function that is permutation-invariant and works with a varying number of nodes in the graph is suitable. Practically used examples here are max-pooling, mean-pooling or sum-pooling. The resulting vector represents the whole graph and can be used to predict the desired graph-level quantities (Wu et al., 2019). The initial representation of a node, \(x_{i}^{0}\), depends on the use case. Possible options are one-hot or binary encoding to denote the id of the node or more informative features. E.g. if the node represents a person in a social graph, one dimension could represent the height of the person, another the age, etc. More meaningful features are superior as they provide crucial information to the GNN to solve the desired problem. They also free the GNN from learning internal representations of the nodes, as would be the case for one-hot or binary encoding (as in that case the feature does not carry any meaning except of the identity of the node) where any semantics of the node would need to be learned from the data and integrated into the model. As KGE provide semantic information about the given entity, they are a promising option as initial node features. Hence we use them in our approach. ## 3 Related Work Cardinality estimation is a longstanding research problem in databases. The first approaches to treat this problem were developed for the relational data model and have since been taken as starting points for cardinality estimation in graph-structured data like KGs. Traditional approaches for cardinality estimation rely on computing (statistical) summaries of the dataset. More recently, learning-based approaches have been proposed. In the following, we present relevant work in both relational and graph-structured data. Approaches for Relational DatabasesTraditionally, cardinality estimation is based on sampling and histograms. Histograms can theoretically provide the full joint probability over attributes and join predicates, however, they are computationally prohibitive, since they grow exponentially with the number of attributes. Therefore, often lower dimensional histograms are used, and independence between attributes and join predicates is often assumed. To overcome this, sampling approaches (Cormode et al., 2011; Vengerov et al., 2150; Li et al., 2016) have been devised that do not make any independence assumptions about the data. By evaluating the query over a sample from the data, the full joint probability is evaluated on that sample. As the sample size approaches the size of the real data, the true cardinality over the data is approached. Yet, in practice, the sample size is usually much smaller than the dataset in order to run the estimate in a reasonable time. Therefore, the accuracy of the estimate highly depends on the sampling technique as well as the data distribution and the sampling might need to run long in order to generate a good estimate. Approaches in the context of sampling are, e.g., _Correlated Sampling_(Vengerov et al., 2150), _Wanderjoin_(Li et al., 2016), and _Join Sampling with Upper Bounds_(Zhao et al., 2018). Correlated Sampling (Vengerov et al., 2150) improves over simple Bernoulli sampling by sampling according to hashed values of the attributes, thus, reducing the variance of the estimate. _Wanderjoin_(Li et al., 2016) represents the query and database as a query graph and data graph and estimates cardinalities by performing random walks on the data graph in coherence with the query graph. _Join Sampling with Upper Bounds_ performs sampling similar to _Wanderjoin_ but extends the estimate to provide an upper bound of the cardinality. The methods are summarized in (Park et al., 2020). For a comprehensive introduction to sampling and histogram approaches to cardinality estimation, consider the survey by Cormode et al. (Cormode et al., 2011). To circumvent the exponential explosion of compute- and memory requirements by statistical summaries, learning approaches have been proposed. Sun et al. (Sun et al., 2021) group these approaches into the so-called _data models_ and _query models_. Data models first aim at predicting the probability of the data and then estimate the query cardinality by sampling from the learned probability distribution. Some examples of these solutions are based on Bayesian Networks (Getoor et al., 2001; Tzoumas et al., 2011; Halford et al., 2019). All these approaches aim at representing the joint probability by factorizing it into a product of smaller conditional probabilities (Halford et al., 2019). The problem here is that, in practice, the factorization can require capturing joint correlations of many attributes in the data, thus, growing the network size also exponentially. For this reason, in practice, Bayesian Networks still make independence assumptions to a great extent (Halford et al., 2019). To overcome these limitations, _Sum Product Networks_ implemented in DeepDB (Hilprecht et al., 2020) are used as graphical models to approximate the joint probability of the data. Compared to Bayesian networks the memory of Sum Product Networks grows polynomial w.r.t. the database size. Query models, instead, aim at directly predicting the cardinality given a query. Most of these approaches are based on Neural Networks (NNs). For example, Kipf et al. (Kipf et al., 2019) present _Multi-Set Convolutional Networks_ (MSCN), a model based on a NN that represents the query by several sets, concretely, table, join, and predicate sets. Woltmann et al. (Woltmann et al., 2019) also propose an NN-based approach but this focuses on local parts of the data. Zhao et al. (Zhao et al., 2022) present a solution based on NN Gaussian Processes (NNGP) that can handle uncertainty to improve the accuracy of predictions. While the latter solutions are closer to our work, these NNs are tailored to queries over relations and cannot directly be applied to graphs. Approaches for Graph-Structured DataEarly works on cardinality estimation for graphs take inspiration from solutions for relational databases by using histograms and assuming attribute independence (Stocker et al., 2008; Shironoshita et al., 2007; Neumann and Weikum, 2009). More recent approaches try to model correlations between structures of the query. Neumann et al. (Neumann and Moerkotte, 2011) propose _Characteristic Sets_(_CSET_), which are synopses that count the number of entities with the same set of predicates. _CSET_ provides exact cardinality estimates for star-shaped DISTINCT queries where all predicates are instantiated and objects are unbounded (variables). For other classes of queries, Neumann et al. (Neumann and Moerkotte, 2011) decompose the query into star-shaped subqueries, calculates their cardinality using _CSET_, and estimates the final cardinality by assuming independence between the sub-queries. Another approach based on graph summarization is _SUMRDF_(Stefanoni et al., 2018), which computes _typed_ summaries where nodes that belong to the same class2 and have similar predicate distributions are grouped together. In addition to summaries, sampling-based approaches have also been proposed for KGs. For example, _impr_(Chen and Lui, 2017) estimates the query cardinality through random walks on the data that match the query graph. Lastly, approaches based on Bayesian networks have also been proposed for KGs (Huang and Liu, 2011). All the solutions aforementioned are tailored to RDF KGs. However, similarly to their relational counterparts, the structures \begin{table} \begin{tabular}{l l l l l l l l} \hline \hline **Approach** & **ML Model** & **Atom Representation** & **Model Size** & **Inductive** & **Perm. Inv.** & **Assumptions** \\ \hline _LMKG_ & NN & Binary Encoding & \(O(|\mathcal{V}|+|\mathcal{E}|)\) & ✗ & ✗ & – \\ _LSS_ & GNN & ProNE & Constant & (✓) & ✓ & Typed entities, undirected graph \\ \hline _GNCE_ (Ours) & GNN & RDF2Vec & Constant & ✓ & ✓ & – \\ \hline \hline \end{tabular} \end{table} Table 1: Characteristics of the learned approaches computed with these approaches can quickly grow w.r.t. the size of the dataset, or are only accurate for specific classes of queries. Most similar to our work are _LMKG_[20] and _LSS_[22], which are approaches based on Machine Learning (ML). Table 1 presents an overview of these solutions, which are discussed in detail next. Davitkova et al. [20] present _LMKG_, a supervised model3 for learning cardinalities using Neural Networks (NNs) consisting of several nonlinear fully connected layers. The representation of the KG and queries in _LMKG_ works as follows. First, each atom in the KG is assigned an id which is subsequently transformed into a binary vector representation of that id. Then, a graph query with \(n\) nodes and \(e\) edges is represented with an adjacency tensor as well as featurization matrices to relate atoms in the query to atoms in the KG. The dimensions of these representations are proportional to the size of the query (given by \(n\) and \(e\)) and the dimensions of the KG (given by \(|V|\) and \(|E|\)). In practice, _LMKG_ assumes that the adjacency tensors and featurization matrices of all queries have the same dimensions, meaning that \(n\) and \(e\) are set to the size of the _largest_ query in a workload; this makes the resulting model unnecessarily large. A possible solution is to train several models for different query sizes [20], yet, this induces a managing overhead. Next, the input to the NN consists of the concatenation of the flattened query representations. Because of this, _LMKG_ is not permutation invariant, as the same query where the nodes and edges are provided in a different order yields different representations, thus, looking completely different to the model. That means that _LMKG_ needs a higher number of parameters and training data points to capture these permutations and produce accurate predictions. Footnote 3: There is another version of _LMKG_ with unsupervised learning, however, its performance was inferior in comparison to its supervised counterpart. Therefore, we focus only on the supervised setting of _LMKG_. Zhao et al. [22] present _LSS_, which applies a Graph Neural Network (GNN) to the graph query. For each node in a query, _LSS_ computes the tree induced by a \(l\)-hop BFS (Breadth-First Search) starting at that node. Then, the GNN is applied to all those trees; the results are aggregated by an attention mechanism to finally predict the cardinality. While _LSS_ has been empirically proven to be effective for cardinality estimations over (regular) graphs, the initial representation of query nodes in _LSS_ relies on two aspects that make it less suitable for KGS. First, _LSS_ computes the initial representation of the nodes in the graph query with ProNE [22] embeddings, which are tailored to graphs and not KGs. Second, each atom is represented with the embedding that results from summing up the embeddings of their corresponding classes in the KG. This makes _LSS_ partly inductive since the GNN itself can deal with representations of entities not seen during training. ProNE however is not inductive, as all embeddings need to be recalculated if new entities are added. A more general problem with the summed class representation is that queries with the same shape but different entities that belong to the same classes have the same representation. This is not ideal for cardinality estimation as the selectivity of these queries can greatly vary due to the different entities mentioned in the query. Additionally, _LSS_ employs a message-passing function that treats the graph as undirected. Furthermore, the attention mechanism introduces a large number of parameters, making the resulting model large (with over 2 million parameters in our experiments). Additionally, although splitting the query into several trees does not enlarge the number of parameters, it does increase the number of computations necessary by a factor proportional to \(l\). Overall, we find the architecture involving the splitting into trees and the attention mechanism overly complicated and unmotivated. The authors also introduce an active learning schedule alongside their approach. However, that is orthogonal to the architecture and could be applied to our model identically. Lastly, Wang et al. [20] present _NeurSC_, which applies several GNNs to both the query graph as well as subgraphs of the data graph. The latter provides additional information, but it is more costly since the graph needs to be sampled for every query. Furthermore, _NeurSC_ is tailored to undirected graphs without edge labels, which is not suitable for KGs. For this reason, we consider that the closest works to ours based on ML are _LMKG_ and _LSS_. ## 4 Our Approach We model the problem of cardinality estimation of conjunctive queries over a KG as a probability distribution estimation problem. In Section 4.1, we show the exact factorized probability of a query graph. In Section 4.2, we present our model architecture and how it approximates the probability from Section 4.1. ### Probability of a Query Graph Given a KG \(\mathcal{G}\), we now assume that there are underlying discrete probability distributions \(P_{s},P_{p},P_{o}\) that give the probability of a subject, predicate, or object in a triple taking a specific value from \(\mathcal{L}_{\mathcal{G}}\). Given the total number of triples in \(\mathcal{G}\), denoted as \(|\mathcal{G}|=|E|\), the probability of a subject having the label \(x\in\mathcal{L}_{\mathcal{G}}\) is given by \[P_{s}(x\in\mathcal{L}_{\mathcal{G}})=\frac{|\{(x,y,z)\mid\exists y,z:(x,y,z)\in \mathcal{G}\}|}{|\mathcal{G}|} \tag{4}\] The probabilities for predicates \(P_{p}\) and objects \(P_{o}\) are calculated similarly. Having defined the probabilities for atoms in triples, we can now define the probability of a triple pattern matching a triple in \(\mathcal{G}\). Given a triple pattern \(tp=(x_{1},x_{2},x_{3})\), this probability is expressed by the joint probability of its instantiated atoms using the chain rule of probability as well as the marginalization over all variables in the triple pattern. For that, we define \(l_{1}...l_{j}\) as labels such that, for each \(x_{i}\) in \(tp\) such that \(x_{i}\in\mathcal{V}\), \(\mu(x_{i})=l_{i}\in\mathcal{L}_{\mathcal{G}}\) (cf. Definition 2.3). We further define that \(\mu(x_{i})=x_{i}\), if \(x_{i}\in\mathcal{L}_{\mathcal{G}}\). That is, we transform every variable to an arbitrary label, and leave the bounded labels untouched. Then, \[\begin{split} P(tp)&=\sum_{l_{1}...l_{j}\in \mathcal{L}_{\mathcal{G}}}P(\mu(tp))\\ &=\sum_{l_{1}...l_{j}\in\mathcal{L}_{\mathcal{G}}}P(\mu(x_{1}), \mu(x_{2}),\mu(x_{3}))\\ &=\sum_{l_{1}...l_{j}\in\mathcal{L}_{\mathcal{G}}}P_{s}(\mu(x_{1} ))\cdot P_{p}(\mu(x_{2})|\mu(x_{1}))\cdot P_{o}(\mu(x_{3})|\mu(x_{2}),\mu(x_{1 }))\end{split} \tag{5}\] We can now in the same way express the probability of any query graph \(Q\) consisting of \(N\) triple patterns matching a subgraph in \(\mathcal{G}\)(i.e. the selectivity). For that, we define again the labels of all \(k\) variables in Q as \(l_{1}\cdots l_{k}\). \[\begin{split} P(Q)&=\sum_{l_{1}...l_{k}\in \mathcal{L}_{\mathcal{G}}}P(\mu(tp_{1}),\mu(tp_{2}),..,\mu(tp_{N}))\\ &=\sum_{l_{1}...l_{k}\in\mathcal{L}_{\mathcal{G}}}\prod_{i=1}^{N} P(\mu(tp_{i})|\mu(tp_{<i}))\end{split} \tag{6}\] We have shown how we can formalize the query cardinality estimation problem as a probability estimation problem. The question now is how to obtain or approximate the different conditional and unconditional probabilities. One way is to directly learn them in that functional form using autoregressive models like _LMKG-U_ or a Generative Flow Network (Bengio et al., 2021). However, using such generative models has the following disadvantages: slower inference process, large output dimension that scales linearly with the size of entities in the KG, non-inductive because of the aforementioned, difficulty treating variables in queries as they need to be summed over all possible entities. We thus decided to approximate the probability from Eq. (6) using a discriminative model instead of a generative one. Our model \(f\) directly predicts the cardinality of a query \(Q\) given the query graph featurization \(\mathcal{Q}\): \[f(\mathcal{Q})\approx||Q||_{\mathcal{G}}=P(Q)\cdot||Q_{\mathcal{V}}||_{ \mathcal{G}} \tag{7}\] Recall that \(Q_{\mathcal{V}}\) is the query graph obtained by replacing all the atoms in \(Q\) by fresh variables (cf. Section 2). In Eq. (7), the cardinality is formulated as the product of the probability of the query (with \(N\) triple patterns) times the number of possible subgraphs with the same shape as the query graph. Thus, our model still learns to assign probabilities to queries (modulated by the number of possible subgraphs). In the following, we describe a suitable and efficient model to learn this probability distribution. ### GNCE Architecture **Model Overview.** In order to approximate the complex distribution in Eq. (7), we choose a neural network for representing it, due to its ability to learn complex functions (Maiorov and Pinkus, 1999). Since queries over KGs naturally represent graphs, an appropriate model choice is a graph neural network (GNN). Hence, the core of our approach is a GNN that, given the featurization \(\mathcal{Q}\) of the query \(Q\), directly predicts the cardinality of the related query. By that, we have a model that is invariant to a permutation of the nodes in the query graph and, in turn, parameter and data efficient. An overview of our approach is shown in Figure 1. Given a KG \(\mathcal{G}\) that we want to estimate query cardinalities over, we first calculate embeddings for all atoms in \(\mathcal{G}\). Secondly, we create a query set consisting of queries and the corresponding cardinalities, for training our GNN to predict the cardinalities given the query, which we denote \(\widehat{||Q||}_{\mathcal{G}}\). We represent the query as the corresponding query graph, where the atoms are represented by their corresponding embedding. Since, as explained in Section 2.2, RDF2Vec embeddings encode relatedness and joint probability, we choose it as our embedding method. Furthermore, since embeddings can be calculated incrementally for new atoms added to the KG, our resulting GNN will be inductive, i.e., it can make accurate cardinality estimates on unseen atoms (validated in Section 5.5). Next, we train the GNN on the query representations such that the difference between the predicted cardinality and the true cardinality gets minimized (cf. Model Training and Predictions). Finally, the trained GNN model can be used to predict the cardinality of new queries. **Model Definition.** A detailed view of our GNN architecture is displayed in Figure 2. A given query \(Q\) (with variables denoted by '?') is represented by the corresponding query graph and embeddings of the atoms. This representation is the input to our GNN (\(k=0\)). First, 2 Message Passing Layers (\(k=1,k=2\)) are applied to the input. In a preliminary experiment, we found that using more than 2 layers does not improve the performance of the model. Possible explanations for this are that 1.) the query graphs are rather small so 2 steps of message-passing are sufficient, and 2.) fewer layers avoid the oversmoothing problem (Chen et al., 2020), where node representations become increasingly similar, which deteriorates the model performance. Our custom Message Passing function, which we term _TPN Message Passing_, is a modulation of the _GINECONV_(Hu et al., 2020) message passing function defined as \[x_{i}^{(k)}=h_{\theta}^{(k)}\left((1+\epsilon)x_{i}^{(k-1)}+\sum_{j\in\mathcal{ N}(i)}\mathrm{ReLU}(x_{j}^{(k-1)}+e_{j,i})\right) \tag{8}\] We initially evaluated several different Message Passing Layers but found _GINECONV_ to be superior to the others. This is in line with the theoretical findings from (Xu et al., 2019), which states that _GINECONV_ is strictly more expressive than all other Message Passing Layers. It also aligns with results from _LSS_(Zhao et al., 2021), which also uses _GINECONV_ as the Message Passing Function. In Eq. (8), each \(h_{\theta}^{(k)}\) is a multilayer perception with a ReLU Activation function. \(\mathcal{N}(i)\) are all neighboring nodes of node \(i\) with corresponding edges \(e_{j,i}\). The parameter \(\epsilon\) is an optionally learnable parameter that defaults to 0. Therefore, this function first sums up the neighboring nodes and edges individually, then aggregates those and the current representation of the node \(x_{i}^{(k-1)}\) again through summation to finally transform them nonlinearly through \(h_{\theta}\). Unfortunately, this Message Passing function treats the graph as undirected, as it aggregates the neighbors invariant under the direction of the edge. However, in cardinality estimation, the edge direction is of crucial information: The triples \((s\to p\to o)\) and \((o\to p\to s)\) can have vastly different cardinalities. One option to make the Figure 1: Overview of the GNCE framework. Given a Knowledge Graph, Embedding are learned for all existing atoms. Next, a GNN is trained on a set of representative queries over this KG. The Queries are represented using the embeddings and the occurrence of each atom. Finally, the trained model is used to estimate the cardinality of new queries. Figure 2: Architecture of the GNN for cardinality estimation. An initial query is represented by entity- and predicate embeddings and the connectivity between those atoms. For clarity, the TPN aggregation is only shown for one node. After node aggregation, the complete query graph is represented by summing all node embeddings. Finally, the query cardinality is estimated by mapping the query representation through a multilayer perception to a single dimension. message passing directional is to only aggregate incoming edges at each node, i.e., instead of summing over \(\mathcal{N}(i)\), summation happens over \(\mathcal{N}^{+}(i)\). However, we found that this yields worse results than just summing over \(\mathcal{N}(i)\), presumably because it restricts information flow. Hence, we use the following customized message passing function: **Definition 4.1** (TPN Message Passing).: The Triple Pattern Network (TPN) Message Passing transforms a node representation \(x_{i}^{(k-1)}\) by separately transforming incoming messages (from \(\mathcal{N}^{+}(i)\)) and outgoing messages (from \(\mathcal{N}^{-}(i)\)) like \[x_{i}^{(k)}=h_{\theta}^{(k)}\bigg{(}x_{i}^{(k-1)} +\sum_{j\in\mathcal{N}^{+}(i)}\mathrm{ReLU}(\mathbf{W}(x_{i}^{(k- 1)}||e^{j,i}||x_{j}^{(k-1)}))+\] \[+\sum_{j\in\mathcal{N}^{-}(i)}\mathrm{ReLU}(\mathbf{W}(x_{j}^{(k- 1)}||e^{i,j}||x_{i}^{(k-1)}))\bigg{)}\] This function makes a case distinction between incoming and outgoing edges. Instead of aggregating the node and edge features through summation, we concatenate them (\(||\)) and linearly project them to the same dimensionality as \(x_{i}\) using the matrix \(\mathbf{W}\). The MLP \(h_{\Theta}^{(k)}\) receives as input sums of the kind \(\mathbf{O}||\mathbf{P}||\mathbf{S}\), where \(\mathbf{O}\) is the feature of the node where the edge points to, \(\mathbf{P}\) is the edge feature between the nodes, and \(\mathbf{S}\) is the feature of the node where the edge originates. After the graph nodes have been transformed by the two Message Passing layers, they need to be aggregated into a fixed-length vector. For that, we apply _Global Sum Aggregation_ to them. That is, the representations of the nodes are summed up dimension-wise, resulting in a single vector \(x\) with the same dimensionality as the node embeddings: \(x=\sum_{l}x_{l}^{(k=2)}\). Finally, this vector is transformed through a final 2-Layer MLP (with a ReLU activation in the hidden layer and linear activation in the final layer) into one single dimension. This dimension represents the predicted cardinality of the query. **Data and Featurization.** In order to obtain a model that accurately predicts the cardinality of queries, it needs to be trained on a set of queries. For that, given a KG \(\mathcal{G}\), we randomly sample queries according to some shape criterion (e.g. star/path with N triple patterns). It is important to sample uniformly across the KG in order to cover the distribution of data as best as possible and not only fit some regions of likely user queries. For each query \(Q\), we first calculate the individual occurrences \(o(x)\) in \(\mathcal{G}\) of each bound atom \(x\) appearing in the queries. That is, the number of triples in \(\mathcal{G}\) this atom occurs in any position, i.e., subject, predicate, or object. In Section 4.1, we saw that those quantities are part of the joint probability and, thus, will be informative to the approximation of the overall query cardinality. This is intuitively clear: the higher the number of atom occurrences, the higher the prior probability that a subgraph of \(\mathcal{G}\) will match the query graph. As the \(o(x)\) values are easy to obtain, it is much better to provide them to the model instead of the model having to learn them. Note also that removing them would make the model non-inductive, as the embeddings presumably do not encode that value. Next, we calculate embeddings \(e(x)\) for all occurring atoms in \(Q\) using RDF2Vec. Note that we are only training on the entities occurring in our queries instead of the full KG, which greatly improves training speed for large graphs. As the final input feature \(i(x)\) for each atom, we use the concatenation of embedding and occurrence, i.e., \(i(x)=e(x)||o(x)\). The featurization \(\mathcal{Q}\) of the query is then given by the \(i(x),\forall x\). Variable atoms in the query graph require a special vector representation. First, we assign a numerical id to each variable. Then, we build the vectors as follows. The first dimension of the vector is set to the id. The rest of the dimensions are all set to \(1\). **Model Training and Predictions.** As mentioned above, our GNN is trained on the provided set of queries and true cardinalities. We aim to minimize the difference between the predicted cardinality and the true value. For that, as loss function, we employ the Mean Average Error (MAE) between our model output \(f(\mathcal{Q})\) and the logarithm of the true cardinality \(||Q||_{\mathcal{G}}\): \(\mathcal{L}=||f(\mathcal{Q})-\log(||Q||_{\mathcal{G}})||\). Thus, the model learns to predict logarithms of cardinalities, which stabilizes the training due to the large range of possible cardinalities. Although the model is evaluated in terms of q-Error, we found that using MAE as a loss function yields better results than using q-Error directly. We train the model with a batch size of \(32\) and for 100 epochs in all experiments. For optimization of the network, we use the Adam optimizer (Kingma and Ba, 2015) with a learning rate of \(e^{-4}\). After training, given the featurization of a new query, the model can directly be used to predict the cardinality of that query. ## 5 Experiments We empirically assess the performance of _GNCE_ for cardinality estimation. Concretely, we want to investigate the following questions: **Q1** What is the effectiveness of _GNCE_ compared to related methods? **Q2** Does _GNCE_ generalize to unseen entities? **Q3** How does the prediction time of _GNCE_ compare to the other methods? The raw datasets, queries, results, and code to reproduce the plots are available on GitHub4. Footnote 4: [https://github.com/TimEricSchvabe/GNCE_Reproducibility](https://github.com/TimEricSchvabe/GNCE_Reproducibility) ### Experimental Setup **Datasets and Queries.** We evaluate our approach on SWDF** **(**Moller et al.**,** 2007**)****, LUBM** **(**Guo et al.**,** 2005**)****, and YAGO** **(**Suchanek et al.**,** 2008**)****. For LUBM and SWDF, we use the datasets provided in the supplementary material by** **Davitkova et al.** **(**Davitkova et al.**,** 2022**)****. For YAGO, we use the dataset provided by the benchmark tool** _G-CARE_****(**Park et al.**,** 2020**)****. LUBM is a synthetic benchmark modeling a university domain. SWDF is a small size but dense real-world dataset that models authors, papers, and conferences. Lastly, YAGO is a larger KG comprising common human knowledge. Table** 2 **summarizes the statistics about these datasets. We generate star and path queries with 2-8 triple patterns for each dataset, resulting in varying numbers of queries (see Table** 3**). The code for query generation can also be found on GitHub5**. The cardinality of the queries is in the range** \([e^{0},e^{6}]\) **for LUBM and SWDF, and** \([e^{0},e^{8}]\) **for YAGO. We randomly shuffle all queries and use 80% of them for training and evaluate all approaches on the remaining 20%.** Footnote 5: [https://github.com/maribelacosta/subgraph-sampler](https://github.com/maribelacosta/subgraph-sampler) **Compared Methods.** We compare _GNCE_ to summary-based approaches (_SUMRDF_****(**Stefanoni et al.**,** 2018**)**** and Characteristic Sets** _(CSET)_****(**Neumann and Moerkotte**,** 2011**)****, sampling-based approaches (_impr_****(**Chen and Lui**,** 2017**)****,**_Wanderjoin_****(**Li et al.**,** 2016**)****, and** _jsub_****(**Zhao et al.**,** 2018**)****), and learning-based approaches (_LMKG_****(**Davitkova et al.**,** 2022**)****and** _LSS_****(**Zhao et al.**,** 2021**)****). For the sampling-based approaches, we report on their average performance of using 30 different samples (the default setting in** _G-CARE_**. For the learning-based approaches, we trained one model per dataset and query type and set up the number of parameters as recommended by the authors. The following table summarizes the number of parameters for the learning-based approaches per dataset. Note that** _GNCE_ **has the lowest number of parameters, with 18x less compared to LSS. A smaller number of parameters typically means a smaller memory footprint of the approach as well as a faster execution time. It also indicates that the model's inductive bias aligns better with the problem's underlying nature and is less prone to overfitting.** \begin{table} \begin{tabular}{|l|r|r|r|r|r|r|} \hline KG & \multicolumn{3}{c|}{Star Queries} & \multicolumn{3}{c|}{Path Queries} \\ \hline \hline \multirow{3}{*}{SWDF} & \multicolumn{3}{c|}{Overall: 116645} & \multicolumn{3}{c|}{Overall: 60739} \\ \cline{2-7} & 2tp & 3tp & 5tp & 8tp & 2tp & 3tp & 5tp & 8tp \\ \cline{2-7} & 27843 & 29461 & 29690 & 29651 & 538 & 19033 & 550 & 40618 \\ \hline \hline \multirow{3}{*}{LUBM} & \multicolumn{3}{c|}{Overall: 113855} & \multicolumn{3}{c|}{Overall: 55336} \\ \cline{2-7} & 2tp & 3tp & 5tp & 8tp & 2tp & 3tp & 4tp & 8tp \\ \cline{2-7} & 25356 & 29127 & 29727 & 29645 & 17784 & 33047 & 4505 & 0 \\ \hline \hline \multirow{3}{*}{YAGO} & \multicolumn{3}{c|}{Overall: 91162} & \multicolumn{3}{c|}{Overall: 87775} \\ \cline{2-7} & 2tp & 3tp & 5tp & 8tp & 2tp & 3tp & 5tp & 8tp \\ \cline{1-1} \cline{2-7} & 13968 & 24416 & 24509 & 28269 & 19378 & 33807 & 17990 & 16600 \\ \hline \end{tabular} \end{table} Table 2: Dataset characteristics \begin{table} \begin{tabular}{|l|r|r|r|r|} \hline \multicolumn{4}{|c|}{**Number of model parameters**} \\ \hline KG & GNCE (Ours) & LMKG & LSS \\ \hline SWDF & \(1.2\cdot e^{5}\) & \(4.5\cdot e^{5}\) & \(2.2\cdot e^{6}\) \\ \hline LUBM & \(1.2\cdot e^{5}\) & \(2.9\cdot e^{5}\) & \(2.2\cdot e^{6}\) \\ \hline YAGO & \(1.2\cdot e^{5}\) & \(3.8\cdot e^{5}\) & \(2.2\cdot e^{6}\) \\ \hline \end{tabular} \end{table} Table 3: Datasets and queries used for training and evaluating the approaches, grouped by the number of triples per query **Implementation Details.**_Gnce_ is implemented using Python 3.8 and Pytorch Geometric [20] and the source code is available at GitHub6. For computing the RDF2Vec embeddings, we use the implementation by Vandewiele et al. [21]. Here, we used an embedding dimension of 100 for _Gnce_. For the non-learning-based approaches, we use the implementation provided by _G-CARE_. All experiments, except for LSS on YAGO, have been conducted on a machine with 16 GB RAM, Intel Core i7-11800H @ 2.30GHz and an NVIDIA GeForce RTX 3050 GPU. Since LSS requires extensive amounts of RAM as it loads the whole KG into memory for training, it was trained on a machine with 512 GB of RAM,an Intel Xeon Silver 4314 CPU @ 2.40GHz as well as an Nvidia A100 GPU. Footnote 6: [https://github.com/TimEricSchwabe/Gnce](https://github.com/TimEricSchwabe/Gnce) **Evaluation Metrics.** Similar to previous works [18], we evaluate the effectiveness of the approaches in terms of the q-Error between the true cardinality and the predicted cardinality: \[\text{q-Error}(Q)=\max\left(\frac{||Q||_{\mathcal{G}}}{||Q||_{\mathcal{G}}},\frac{||\overline{Q}||_{\mathcal{G}}}{||Q||_{\mathcal{G}}}\right) \tag{9}\] ### Overview: Results of Learned Approaches In this section, we look at the initial impressions on the effectiveness of the learned approaches (**Q1**), which are the closest to our work. Per approach, Figure 3 shows scatterplots of the true and predicted cardinalities for queries with a cardinality of up to \(e^{6}\). Overall, _Gnce_ performs the best among the three methods as a clear correlation between prediction and true cardinality can be observed. The reported Pearson correlation coefficients also indicate that the correspondence between predicted and true cardinality is significantly higher for _Gnce_ (\(r=0.8\)). _LMKG_ also exhibits a moderate correlation (\(r=0.54\)), but also a significant amount of strong over-and underestimations. The situation is qualitatively different for _LSS_. Here, queries in the small cardinality range are overestimated, while queries in the moderate to higher cardinality range are severely underestimated. This behavior is also reflected in the low correlation coefficient of LSS (\(r=0.12\)). To better understand how those initial impressions translate into q-Error, and how the methods perform within different ranges of the true cardinalities, we investigate the performance of all approaches for star queries (SS 5.3) and path queries (SS 5.4) separately. ### Cardinality Estimation for Star Queries In this section, we study the effectiveness of the approaches (**Q1**) for star queries, where the subject position is the join variable. In Table 4, we report the mean q-Error of all approaches in each dataset. 7 Overall, we observe that the q-Error increases along with the size of the KGs. This behavior is expected, as capturing correlations in larger datasets is more challenging, and queries with large cardinalities naturally occur more frequently in these datasets. These aspects negatively impact the estimations. The sampling and summary methods behave similarly to some extent, except for _jsub_ which produces large errors in YAGO. _CSET_ does not perform well in the tested star queries as these may have Figure 3: Overall performance of learned approaches. The Plots show true and predicted cardinalities for learned approaches and correlation \(r\). Queries across all datasets and query types are combined per approach. bound objects, which can create overestimations in _CSET_. Among the learned approaches, _GNCE_ exhibits the best overall performance. Interestingly, _LSS_ does not perform well in these KGs. We hypothesize that this is because the learned node representations based on classes of _LSS_ cannot distinguish between queries with similar shapes but with different cardinalities. This behavior of LSS is clearly observed in the results for SWDF. While all the other approaches achieve their best performance in SWDF (smallest dataset), _LSS_ produces large q-Errors because the number of typed entities is considerably small (only 22%, cf. Table 2). In the case of untyped entities, the _LSS_ entity representation defaults to a generic vector of zeros, which does not contain any information. In contrast, _GNCE_ does not make any assumption about the types of entities, and can still encode them through the embeddings if available. To further understand the performance of the approaches, we analyze the distributions of q-Errors. Figure 4 shows the distribution of q-Errors as boxplots; under- and overestimations are depicted by values below and above the horizontal line (perfect q-Error), respectively. We start by looking at the sampling methods (_Wanderjoin_, _impr_, and _jsub_), which tend to underestimate the cardinalities, in particular _impr_. This behavior was already observed by Park et al. (Park et al., 2020) for other datasets. The summary-based approaches also tend to produce underestimations, except for _CSET_ in YAGO. A closer inspection of the results reveals that _CSET_ largely overestimates the cardinalities for highly selective queries with bound objects. For the learned-based methods, the q-Errors are concentrated around the optimal value of 1 for _GNCE_ and _LMKG_. _LSS_ tends to overestimate slightly on large parts of the queries, but also shows \begin{table} \begin{tabular}{|l|l|l|l|l|l|l|l|} \cline{3-8} \multicolumn{1}{c}{} & \multicolumn{4}{c|}{Star Queries} & \multicolumn{4}{c|}{Path Queries} \\ \cline{2-8} \multicolumn{1}{c|}{} & **Approach** & **SWDF** & **LUBM** & **YAGO** & **SWDF** & **LUBM** & **YAGO** \\ \hline \multirow{3}{*}{Sampling} & _WanderJoin_ & 129 & 232 & 18713 & 21.7 \(\cdot e^{4}\) & 388.9 & 9730 \\ \cline{2-8} & _impr_ & 141 & 237 & 2605 & \(73.7\cdot e^{4}\) & 428.7 & 1722 \\ \cline{2-8} & _jsub_ & 169 & 409 & 15 \(\cdot e^{0}\) & \(37.4\cdot e^{4}\) & 414.36 & 10952 \\ \hline \multirow{3}{*}{Summary} & _CSET_ & 94 & 904 & 41586 & \(1.2\cdot e^{47}\) & \(63\cdot e^{0}\) & \(2.2\cdot e^{29}\) \\ \cline{2-8} & _SUMRDF_ & 130 & 233 & - & \(2\cdot e^{5}\) & \(393\cdot e^{0}\) & \(\cdot\) \\ \hline \multirow{3}{*}{Learned} & _LMKG_ & 2.7 & 1.85 & 8.78 & 1819.9 & 2.37 & 69 \\ \cline{2-8} & _LSS_ & 1187 & 283 & 502.1 & 1187.1 & 179 & 1075 \\ \cline{1-1} \cline{2-8} & _GNCE_ & **1.42** & **1.22** & **1.96** & **12.5** & **1.14** & **3.78** \\ \hline \end{tabular} \end{table} Table 4: Mean q-Errors for path queries Figure 4: Boxplots of q-Errors of star queries Figure 5: q-Errors for star-shaped queries, grouped by the true cardinalities of the queries severe underestimation (consistent with the results from Section 5.2). In comparison to _LSS_ and _LMKG_, the maximum under-and overestimations of _GNCE_, as well as the quantiles, are more symmetric around the origin than for the other methods, indicating a more stable behavior across all datasets. Next, we analyze the average q-Error of the approaches at different cardinality sizes (cf. Figure 5). The results show that the q-Error grows with increasing query cardinality, except for _GNCE_ and _LMKG_. Non-learning-based approaches exhibit good performance in highly-selective queries with a result size range < 5. These queries typically have many bound atoms, for which sampling-based methods like _impr_ and _Wanderjoin_ might have collected (nearly) exact statistics. The only exception is _CSET_ in YAGO, yet, these results are due to the large q-Errors produced by overestimations of _CSET_ in highly-selective queries as previously explained. For learning-based approaches, the low number of training queries in the higher cardinality range can contribute to large errors. Still, _GNCE_, with its inductive bias tailored to the graph nature of queries and more informative feature representation due to embeddings, requires less training data to produce accurate predictions. For this reason, _GNCE_ consistently has the lowest q-Error across all result sizes, with the only exception being the result size range < 5 in YAGO, where it is slightly outperformed by _Wanderjoin_. ### Cardinality Estimation for Path Queries Next, we examine the effectiveness of the approaches (**Q1**) for path queries, with joins occurring between subjects and objects of triple patterns. We begin by analyzing the mean q-Error of the approaches, as presented in Table 4. The first observation is that all methods have higher q-Errors in comparison to the star-shaped queries (cf. Table 4). This is consistent with previous results reported by Park et al. (Park et al., 2020). Also interestingly, all methods are at least an order of magnitude worse on SWDF compared to the other datasets. This can be due to the high density of the SWDF graph, i.e., there are lots of possible paths from each start point which makes cardinality estimation significantly more error-prone. The effectiveness of the learning-based approaches is also affected by the fewer (training) queries in the dataset (cf. Table 3).8 Overall, the learned approaches exhibit the best performance, followed by sampling-based methods, and lastly summary-based methods. Still, _GNCE_ outperforms the state of the art in path queries by several orders of magnitude. Figure 6: Boxplots of q-Errors for path queries Figure 7: q-Errors for path queries, grouped by the true cardinalities of the queries Next, we analyze the distribution of q-Errors in Figure 6. All the sampling methods tend to underestimate the query cardinalities, especially in SWDF as previously explained due to the density of this dataset. Furthermore, their performance greatly deteriorates for YAGO (in comparison to LUBM) due to the size and the known semi-structuredness of this KG. In the summary-based approaches, the estimates computed by _CSET_ are unrealistically high, a phenomenon that was already reported by Davitkova et al. (Davitkova et al., 2022). These results confirm that _CSET_ summaries do not perform well at capturing join correlations between subjects and objects, as expected. In the learning-based approaches, _LSS_ tends to produce overestimations. This was already observed in the star queries (cf. Section 5.3), indicating that this is a recurrent behavior of _LSS_. In contrast, both _GNCE_ and _LSS_ tend to underestimate. Still, the spread of the errors shown by the whiskers is smaller for _GNCE_ than _LMKG_. In Figure 7, we examine the q-Errors categorized by query cardinality. Please note that in Figure 6(a), the bars for _CSET_ are omitted due to the extremely high values. Similar to the trend observed for star-shaped queries, we found that the q-Error increases with the cardinality of queries for all approaches except for _GNCE_, which exhibited a mostly consistent mean q-Error. Second, in SWDF and YAGO, the sampling-based methods marginally outperform _GNCE_ in the small cardinality range <5. Interestingly, on SWDF, for queries with cardinalities between \(5^{4}\) and \(5^{5}\), _LSS_ performs best out of all approaches in this particular case. ### Inductive Case: Results of Learned Approaches In this section, we assess the effectiveness of learned approaches in the inductive case (**Q2**), i.e., when test queries involve atoms that were not seen during training. For the sake of space, we conduct this experiment only on star queries for SWDF and proceeded as follows. The query set was partitioned into two disjoint sets, such that the entities in both sets were mutually exclusive, i.e., each query in one set did not involve any entity present in the other set. This resulted in two sets with 111K and 2.1K queries each. Then, we trained the three learned approaches, _GNCE, LMKG, LSS_, on the larger of the two sets and evaluate on the other. The average of q-Errors of the approaches is presented in Figure 8. Compared to the non-inductive case in Figure 4(a), all methods experience a performance deterioration. However, the increase of the q-Error is significantly smaller for _GNCE_ compared to the other two methods. One notable observation in Figure 8 is that for queries with a cardinality smaller than \(5^{2}\), the performance of _LSS_ is improved in comparison to its performance in the non-inductive case. This is because the test set primarily consists of queries with two triple patterns - as it is hard to find larger queries that do not contain entities from the other set - which are easier to evaluate for _LSS_. For _LMKG_, the inductive case is challenging as its architecture completely relies on node representations computed from the queries seen during training, while _GNCE_ and _LSS_ use (knowledge) graph embeddings. Because of this, _LMKG_ is the method affected the most in the inductive case. In summary, the results of this experiment show that _GNCE_ can be used in the inductive setting, when new queries are constantly processed, without frequently retraining the model. ### Prediction Efficiency To be of practical use during query optimization, a cardinality estimator needs to produce results with minimal runtime (**Q3**). Therefore, in this experiment, we measure the runtime of prediction for the different queries from the smallest and largest datasets, i.e., SWDF and YAGO. To measure the runtime we use the _time_ library (Foundation, 2021) in python. For the learned techniques, we evaluate the propagation of the query representation through the network's forward pass. For the methods provided by _G-CARE_(Park et al., 2020), we use the implemented _evaluate_ function of the different methods. All measurements were performed on the same machine, except for _LSS_ on YAGO, which had to be executed on the larger cluster (described in Section 5.1). Figure 8: Mean q-Errors on queries consisting of unseen entities for star-shaped queries on the SWDF dataset. We present the results in Figure 9, grouped by the number of triple patterns in the query (_query size_). The grey bars indicate the 95% confidence interval of the data. Comparing the results between SWDF and YAGO, we observe that the runtime of the non-learning-based approaches is impacted by the size of the dataset as well as the type of query. The sample-based methods, i.e. _impr_, _jsub_, and _WanderJoin_, show higher efficiency mainly on the smaller SWDF dataset. The performance of _CSET_ and _RDFSUM_ is similar to the sample-based approaches, as they require several accesses to (large) summaries to perform the predictions. Among the learned methods, _GCNCE_ consistently has the lowest runtime. From the learned approaches, we report stable behavior across the datasets, query sizes, and types. This is observed in both the mean values as well as the narrow confidence interval indicating almost no variations in prediction time. In particular, _GCNCE_ exhibits the best performance from the learned approaches and even outperforms the majority of the non-learning ones except for _impr_ on YAGO. Overall, the runtime of _GCNCE_ is competitive with other established methods and is small enough to be employed in a real-time query optimization setting. It is noteworthy that these measurements were obtained using unoptimized prototypical code. In a production environment, neural networks are typically compiled, which results in a further reduction of execution time. ## 6 Conclusion and Outlook In this work, we presented _GCNCE_, a novel method for accurate cardinality estimation over Knowledge Graphs (KG) based on KG Embeddings and Graph Neural Networks (GNN). The Embeddings are used to provide semantically meaningful features to the GNN, which directly predicts the cardinality of the embedding-enhanced query graph. By design, our method is lightweight, tailored to the graph structure of queries, requires few training data, and allows for inductive generalization to unseen entities. On differently sized real-world datasets and a synthetic benchmark, our approach consistently outperforms the state-of-the-art _LSS_ and _LMKG_ in terms of q-Error over different query shapes and sizes. _GCNCE_ is also robust in the sense that it does not produce severe prediction errors. An experiment on inductive cases shows that _GCNCE_ generalizes to unseen entities, making it a suitable solution for actual deployment in a quickly changing query processing setting. In that context, we also showed that our model is lightweight with fewer parameters than all other learned approaches, leading also to smaller and almost constant runtime for predictions below 1 ms. Further research directions include the transferability of one model to other datasets, to minimize the training efforts. We also plan to deploy _GCNCE_ in a query optimizer to test its effect on actual query execution time as well as ease of integration and operationality in a real-world setting.
2310.06717
Improving Pseudo-Time Stepping Convergence for CFD Simulations With Neural Networks
Computational fluid dynamics (CFD) simulations of viscous fluids described by the Navier-Stokes equations are considered. Depending on the Reynolds number of the flow, the Navier-Stokes equations may exhibit a highly nonlinear behavior. The system of nonlinear equations resulting from the discretization of the Navier-Stokes equations can be solved using nonlinear iteration methods, such as Newton's method. However, fast quadratic convergence is typically only obtained in a local neighborhood of the solution, and for many configurations, the classical Newton iteration does not converge at all. In such cases, so-called globalization techniques may help to improve convergence. In this paper, pseudo-transient continuation is employed in order to improve nonlinear convergence. The classical algorithm is enhanced by a neural network model that is trained to predict a local pseudo-time step. Generalization of the novel approach is facilitated by predicting the local pseudo-time step separately on each element using only local information on a patch of adjacent elements as input. Numerical results for standard benchmark problems, including flow through a backward facing step geometry and Couette flow, show the performance of the machine learning-enhanced globalization approach; as the software for the simulations, the CFD module of COMSOL Multiphysics is employed.
Anouk Zandbergen, Tycho van Noorden, Alexander Heinlein
2023-10-10T15:45:19Z
http://arxiv.org/abs/2310.06717v1
# Improving Pseudo-Time Stepping Convergence for CFD Simulations With Neural Networks ###### Abstract Computational fluid dynamics (CFD) simulations of viscous fluids described by the Navier-Stokes equations are considered. Depending on the Reynolds number of the flow, the Navier-Stokes equations may exhibit a highly nonlinear behavior. The system of nonlinear equations resulting from the discretization of the Navier-Stokes equations can be solved using nonlinear iteration methods, such as Newton's method. However, fast quadratic convergence is typically only obtained in a local neighborhood of the solution, and for many configurations, the classical Newton iteration does not converge at all. In such cases, so-called globalization techniques may help to improve convergence. In this paper, pseudo-transient continuation is employed in order to improve nonlinear convergence. The classical algorithm is enhanced by a neural network model that is trained to predict a local pseudo-time step. Generalization of the novel approach is facilitated by predicting the local pseudo-time step separately on each element using only local information on a patch of adjacent elements as input. Numerical results for standard benchmark problems, including flow through a backward facing step geometry and Couette flow, show the performance of the machine learning-enhanced globalization approach; as the software for the simulations, the CFD module of COMSOL Multiphysics(r) is employed. keywords: Computational fluid dynamics, Newton's method, pseudo-time stepping, neural network, hybrid algorithm Msc: [2020] 35Q30, 65H10, 65N12, 65N22, 68T07 + Footnote †: journal: ## 1 Introduction Computational fluid dynamics (CFD) simulations are highly relevant for a wide range of applications, including the fields of aerospace, environmental, and biological engineering as well as weather predictions and medicine. Numerical simulations of Newtonian fluids, that is, fluid with a linear correlation of the local viscous stresses and strain rate, involves the solution of the Navier-Stokes equations. Depending on the flow regime, the Navier-Stokes equations exhibit strong nonlinearities, which pose challenges to the numerical nonlinear solver employed. In this work, we consider two-dimensional stationary CFD simulations using a mixed finite element method (FEM) as the discretization. The nonlinear system of equations resulting from discretizing the steady-state Navier-Stokes equations is then solved using Newton's method, that is, via solving a sequence of linearized problems. Whereas Newton's method provides quadratic convergence near the solution, the iteration may only converge slowly or even diverge farther away from the solution. In order to improve global convergence of the method, globalization techniques have been developed; see [1] for an overview of globalization techniques for the Navier-Stokes equations. In [1], the authors categorize globalization techniques into the classes of _backtracking methods_ and _trust region methods_; cf. [2; 3]. Other examples of methods to improve the robustness of the nonlinear solver include homotopy, continuation, pseudo transient continuation, mesh sequencing methods, or nonlinear preconditioning methods; cf. [4; 5; 6; 7; 8; 9; 10; 11; 12; 13]. The combination of scientific computing and machine learning, which is also denoted as scientific machine learning (SciML), is a new field [14], which has gained a lot of attention over the past few years. One popular application area for SciML techniques are CFD simulations; see, for instance, the review paper [15]. Successful examples for the use of SciML techniques in the context of CFD are, for instance, discretization approaches using neural networks (NNs) [16; 17; 18], surrogate models [19; 20; 21; 22], and model discovery [23; 24; 25]. In [26], the temporal evolution of dynamic systems is learned via long short-term memory (LSTM) NNs. Approaches for the enhancement of CFD simulations via machine learning include the generation of optimized meshes [27], the improvement of the resolution of the simulation results [28; 29; 30; 31], or the detection of troubled cells in simulation meshes due to Gibbs oscillations arising from the use of higher-order methods [32]. We note that, in [29; 30; 31; 32], the network inputs and output are specifically chosen from local patches of elements to achieve generalizability of the machine learning model; we will apply a similar approach in this work. The use of machine learning models for the enhancement of numerical solvers has also been investigated in several works. In the context of linear solvers, [33] and [34] have employed features generated by the proper orthogonal decomposition (POD) to develop a modified conjugate gradient (CG) solver or preconditioning techniques, respectively. The enhancement of the CG method by a nonlinear convolutional NN-based preconditioner has been investigate in [35]. In [36; 37], NNs have been employed to improve domain decomposition methods, and in [38; 39; 40; 41; 42], components of multigrid methods are selected or generated using machine learning models. In the early works [43; 44; 45; 46; 47], suitable numerical solution algorithms are being selected using machine learning techniques. Related to that, [48] investigated the prediction of a suitable combination of preconditioner and iterative method for solving a given sparse linear system. Fewer works have considered the improvement of the nonlinear solver convergence using machine learning. In [49], the nonlinear convergence of numerical solvers for nonlinear partial differential equations (PDE) is improved using POD features in a nonlinear preconditioning approach, and the proposed method is tested specifically for CFD problems. Moreover, in [50], dimensionless numbers and simulation properties are used as input to a random forest model to predict a relaxation parameter to accelerate a convergence of the Picard iteration for multiphase porous media flow. To the best of the authors' knowledge, there is currently no work that directly addresses the improvement of the nonlinear convergence of Newton's method for CFD simulations using NNs. The only exception is the master thesis of the first author [51], which laid the foundation for this paper. In particular, we enhance the pseudo-transient continuation [8], or pseudo-time stepping, approach for improving the robustness of the nonlinear convergence for the steady-state Navier-Stokes equations using an NN model. Similar to previous approaches [29; 30; 31; 32], the model is trained to predict the local pseudo-time step size for each mesh element using only local input features; this aims at ensuring generalizability of our approach. We test the performance and generalizability of our approach for different geometries and flow configurations using CFD simulations with the software package COMSOL Multiphysics(r); as a reference, we compare our approach against two default pseudo-time step control mechanisms implemented in the FEM software package COMSOL Multiphysics(r). As the machine learning framework, we employ Matlab, which enables us to access data from COMSOL via an available interface between the two packages. The paper is organized as follows. First, the Navier-Stokes equations and pseudo-time stepping are briefly recalled and discussed in section 2 respectively section 3. In section 4 the NN for the local element pseudo-time step prediction is described. The numerical results are given in section 5. Lastly, the conclusions are presented in section 6. ## 2 Navier-Stokes equations The Navier-Stokes equations are a system of partial differential equations (PDEs) that describes the flow of Newtonian fluids, that is, fluids with a linear correlation of the viscous stresses and the local strain rate. In particular, we consider incompressible fluids, that is, fluids with a constant density; cf. [52]. The stationary Navier-Stokes equations for incompressible flow read \[\begin{array}{rcl}\rho(\mathbf{u}\cdot\nabla)\mathbf{u}-\mu\nabla^{2}\mathbf{ u}&=&-\nabla p+\mathbf{f},\\ \rho\nabla\cdot\mathbf{u}&=&0,\end{array} \tag{1}\] describing the conservation of momentum and mass, respectively. In these equations, \(\mathbf{u}\) is the flow velocity, \(\mu\) is the dynamic viscosity of the fluid, \(\rho\) is the density, which is assumed to be constant, \(p\) is the pressure, and \(\mathbf{f}\) is the body force acting on the flow [52]; in all our experiments, the body force is assumed to be zero. Due to the convective term \(\rho(\mathbf{u}\cdot\nabla)\mathbf{u}\), eq. (1) is nonlinear, and the numerical treatment of this nonlinearity is the subject of this research. Very strong nonlinearities are generally related to turbulent flow. However, already in the regime of laminar flow, the nonlinearities may become severe enough to cause nonlinear solvers to diverge; hence, we will focus on the laminar case. Flow remains laminar as long as the Reynolds number is below a critical value in the order of \(10^{5}\); see, e.g., [53]. The Reynolds number \(\mathrm{Re}\) is given by \[\mathrm{Re}=\frac{\rho UL}{\mu}. \tag{2}\] Here, \(U\) and \(L\) are the typical velocity and length scale. The Reynolds number describes the ratio between inertial and viscous forces; cf. [54]. At low Reynolds numbers, the flow remains laminar as the viscous forces are able to damp out disturbances in the flow. At high Reynolds numbers, the inertial forces become more important resulting in nonlinear interactions to grow, which causes turbulence. In order to solve the stationary Navier-Stokes equations in eq. (1) on a computational domain \(\Omega\subset\mathbb{R}^{2}\) numerically, we consider a triangulation of \(\Omega\) into linear triangles. Then, we discretize eq. (1) using piecewise linear finite elements for both the velocity \(\mathbf{u}\) and the pressure \(p\) and stabilize using Galerkin least-squares (GLS) streamline diffusion and Hughes-Mallet type shock-capturing [55; 56]. This yields a discrete but nonlinear system of equations \[N(\mathbf{u}_{h})+B^{\top}p_{h} =0, \tag{3}\] \[B\mathbf{u}_{h} =0,\] where we denote the discrete velocity and pressure fields as \(\mathbf{u}_{h}\) respectively \(p_{h}\). The linear operators \(B\) and \(B^{\top}\) correspond to the divergence and gradient, respectively, and the nonlinear operator \(N\) corresponds to the convection-diffusion of the velocity field. By combining the fields \(\mathbf{u}_{h}\) and \(p_{h}\) into a single field \(\mathbf{v}\), we can simply formulate the discrete nonlinear problem eq. (3) as \[F(\mathbf{v})=0.\] We solve this system using Newton's method, that is, by solving a sequence of linear systems of the form \[-F^{\prime}(\mathbf{v}^{n})\Delta\mathbf{v}^{n}=F(\mathbf{v}^{n}),\] where \(n\) is the iteration index of the Newton iteration and \(F^{\prime}(\mathbf{v}^{n})\) is the Jacobian at the linearization point \(\mathbf{v}^{n}\). Close to the solution, Newton's method converges with quadratic rate. However, for an arbitrary initial guess, the method might also diverge. As we will see in our numerical results, this may happen for a relatively wide range of cases for the stationary Navier-Stokes equations. In order to make the nonlinear iteration more robust, globalization techniques can be employed; see, e.g., [1] for an overview of globalization techniques for Newton's method for the Navier-Stokes equations. Here, we will consider the pseudo-time stepping approach [8], which we will discuss in more detail in the next section. ## 3 Pseudo-time stepping Solving stationary nonlinear equations using Newton's method requires an initial guess close enough to the root. Globalization techniques are designed to give a result for a wider range of initial guesses, but can stagnate at local minima [8]. Pseudo-time stepping, or pseudo-transient continuation, is an alternative to Newton's method for computing stationary solutions of time-dependent partial differential equations. The idea is to obtain a solution more robustly by solving the time-dependent equation instead of the stationary one. The idea behind the method is to frame the problem in a time-depending setting, \[\frac{\partial\mathbf{v}}{\partial t}=-F(\mathbf{v}), \tag{4}\] with \(F(\mathbf{v})=0\) the system of nonlinear equations of which a solution must be determined. Now the algorithm for pseudo-time stepping can be described as the numerical integration with a variable time step method of the initial value problem \[\frac{\partial\mathbf{v}}{\partial t}=-F(\mathbf{v}),\quad\mathbf{v}(0)= \mathbf{v}_{0}; \tag{5}\] cf. [8]. The idea is that this time integration converges to a steady state for a wider range of initial values \(\mathbf{v}_{0}\) than the standard Newton method. In addition, the method tries to increase the time step as \(F(\mathbf{v})\) approaches \(0\), such that when the iterations get closer to a steady state, the convergence becomes (close to) quadratic. The iterations of the pseudo-time stepping algorithm are given by \[\mathbf{v}^{n+1}=\mathbf{v}^{n}-\left((\Delta t^{n})^{-1}I+F^{\prime}(\mathbf{ v}^{n})\right)^{-1}F(\mathbf{v}^{n}), \tag{6}\] with \(F^{\prime}(\mathbf{v}^{n})\) the Jacobian. To understand how (6) is obtained from (5) consider an Euler backward step starting from \(\mathbf{v}^{n}\) for equation (5): \[\mathbf{z}^{n+1}=\mathbf{v}^{n}-\Delta t^{n}F(\mathbf{z}^{n+1}). \tag{7}\] Note that \(\mathbf{z}^{n+1}\) is a root of \[G(\xi):=\xi+\Delta t^{n}F(\xi)-\mathbf{v}^{n}, \tag{8}\] as a function of \(\xi\). The first Newton iterate for solving \(G(\xi)=0\) with initial guess \(\xi_{0}=\mathbf{v}^{n}\) gives \[\xi_{1} =\mathbf{v}^{n}-\left(I+\Delta t^{n}F^{\prime}(\mathbf{v}^{n}) \right)^{-1}(\mathbf{v}^{n}+\Delta t^{n}F(\mathbf{v}^{n})-\mathbf{v}^{n}),\] \[=\mathbf{v}^{n}-\left((\Delta t^{n})^{-1}+F^{\prime}(\mathbf{v}^{ n})\right)^{-1}F(\mathbf{v}^{n}).\] From this corrector iteration, we have obtained the formula in (6). The pseudo code of the method is the given by Algorithm 1. ### Applying pseudo-time stepping to the weak form of the Navier-Stokes equations The weak form of the Navier-Stokes equations is given by: find velocity and pressure fields \((\mathbf{u},p)\in X\) such that \[\begin{array}{rcl}\int_{\Omega}(\rho\partial_{t}\mathbf{u}+\rho( \mathbf{u}\cdot\nabla)\mathbf{u})\cdot\phi-(\mu\nabla\mathbf{u}\cdot\nabla \phi-p\nabla\cdot\phi)&=&\int_{\Omega}\mathbf{f}\cdot\phi+\int_{ \Gamma_{N}}\mathbf{h}\cdot\phi,\\ \int_{\Omega}\rho\nabla\cdot\mathbf{u}\psi&=&0,\end{array} \tag{9}\] for all test functions \((\phi,\psi)\in Y\), with \(X\) and \(Y\) suitable function spaces, e.g., \(X=Y=H_{0}^{1}(\Omega)^{2}\times L^{2}(\Omega)\). Here \(\mathbf{f}\) is a forcing term, and \(\mathbf{h}\) encodes the boundary conditions. To apply pseudo-time stepping to this weak form, we first discretize in space using finite elements by replacing the function spaces \(X\) and \(Y\) by finite dimensional subspaces \(X_{h}\subset X\) and \(Y_{h}\subset Y\), consisting of continuous functions that are piecewise linear on a finite element mesh of the domain \(\Omega\) with maximum mesh size \(h\). Then, in order to apply pseudo-time stepping to the stationary form of the spatially discretized system, the same conceptual idea as described in the previous section is used, which can be summarized by first writing the time-discretized equations for one Euler backward step, and then linearizing this system for the new time step around the current time step. The Euler backward formula with time step \(\Delta t^{n}\) for the discretized weak form of (9) gives the following (discretized) nonlinear problem: find \((\mathbf{u}_{h},p_{h})\in X_{h}\) such that \[\sum_{e\in E}\Biggl{(}\int_{\Omega^{e}}(\rho\frac{\mathbf{u}_{h} ^{n+1}-\mathbf{u}_{h}^{n}}{\Delta t^{n}}+\rho(\mathbf{u}_{h}^{n+1}\cdot\nabla) \mathbf{u}_{h}^{n+1})\cdot\phi_{j}-(\mu\nabla\mathbf{u}_{h}^{n+1}\cdot\nabla \phi_{j}-p_{h}^{n+1}\nabla\cdot\phi_{j})+\] \[-\!\!\int_{\Omega^{e}}\!\!\mathbf{f}\cdot\phi_{j}-\int_{\Gamma_{ N}^{e}}\!\!\mathbf{h}\cdot\phi_{j}\Biggr{)} =0, \tag{10}\] \[\sum_{e\in E}\Biggl{(}\int_{\Omega^{e}}\!\!\rho\nabla\cdot\mathbf{ u}_{h}^{n+1}\psi_{j}\Biggr{)} =0,\] for all test functions \((\phi_{j},\psi_{j})\in Y_{h}\), where the summation is over the set of all mesh elements \(E=\{e_{1},e_{2},\ldots,e_{m}\}\), with the number of elements \(m\). Linearizing this system around \((\mathbf{u}_{h}^{n},p_{h}^{n})\) results in \[\sum_{e\in E}\Biggl{(}\int_{\Omega^{e}}(\rho\frac{\mathbf{u}_{h }^{n+1}-\mathbf{u}_{h}^{n}}{\Delta t^{n}}+\rho(\mathbf{u}_{h}^{n}\cdot\nabla) \mathbf{u}_{h}^{n+1}+\rho(\mathbf{u}_{h}^{n+1}\cdot\nabla)\mathbf{u}_{h}^{n}- \rho(\mathbf{u}_{h}^{n}\cdot\nabla)\mathbf{u}_{h}^{n})\phi_{j}+\] \[-\!\!\int_{\Omega^{e}}(\mu\nabla\mathbf{u}_{h}^{n+1}\cdot\nabla \phi_{j}-p_{h}^{n+1}\nabla\cdot\phi_{j})-\int_{\Omega^{e}}\!\!\mathbf{f}\cdot \phi_{j}-\int_{\Gamma_{N}^{e}}\!\mathbf{h}\cdot\phi_{j}\Biggr{)} =0, \tag{11}\] \[\sum_{e\in E}\Biggl{(}\int_{\Omega^{e}}\!\!\rho\nabla\cdot\mathbf{ u}_{h}^{n+1}\psi_{j}\Biggr{)} =0.\] Solving this linear system for \((\mathbf{u}_{h}^{n+1},p_{h}^{n+1})\) constitutes one pseudo-time step. We write eq. (10) in matrix format \[\frac{1}{\Delta t^{n}}M(\mathbf{v}^{n+1}-\mathbf{v}^{n})+F(\mathbf{v}^{n+1})=0, \tag{12}\] where the coefficients of \((\mathbf{u}_{h}^{n},p_{h}^{n})\) w.r.t. the chosen basis of \(X_{h}\) are again combined into a single vector \(\mathbf{v}^{n}\), and where \(M=\begin{bmatrix}M_{\mathbf{u}}&\mathbf{0}\\ \mathbf{0}&\mathbf{0}\end{bmatrix}\) is a singular mass matrix with the velocity mass matrix \(M_{\mathbf{u}}\). Then, we can also write the solution of eq. (11) in the more compact form \[\mathbf{v}^{n+1}=\mathbf{v}^{n}-(\frac{1}{\Delta t^{n}}M+F^{\prime}(\mathbf{v} ^{n}))^{-1}F(\mathbf{v}^{n}). \tag{13}\] ### Choice of the pseudo-time step The idea is that the pseudo-time step \(\Delta t^{n}\) is initially small, such that its influence in (6) is large. When the iteration approaches convergence, the magnitude of the pseudo-time steps becomes small, such that (6) performs more like the standard Newton iteration. This has the benefit that, in the beginning, the method depends less on the initial guess, and in the end, it may converge quadratically. There are several possibilities to define a pseudo-time step that fits this property. In addition to that, it is possible to use a pseudo-time step that uses local, i.e. mesh element dependent, information. This amounts to replacing the global pseudo-time step \(\Delta t^{n}\) in (11) by a local, mesh element dependent, pseudo-time step \(\Delta t^{n}_{e}\). In this case the mass matrix \(M\) in (13) will depend on the vector of local pseudo-time steps \(\overline{\Delta t}^{n}=(\Delta t^{n}_{e_{1}},\ldots,\Delta t^{n}_{e_{m}})\), so that (13) becomes \[\mathbf{v}^{n+1}=\mathbf{v}^{n}-(M(\overline{\Delta t}^{n})+F^{\prime}( \mathbf{v}^{n}))^{-1}F(\mathbf{v}^{n}). \tag{14}\] In COMSOL, for instance, the following local pseudo-time step is used: \[\Delta t^{n}_{e}=\text{CFL}(n)\frac{h_{e}}{\|\mathbf{u}_{h}^{n}\|_{e}}, \tag{15}\] with \(h_{e}\) the size of mesh element \(e\), \(\|\mathbf{u}_{h}^{n}\|_{e}\) the Euclidean norm of the velocity field \(\mathbf{u}_{h}^{n}\) in the mesh element \(e\), and \(\text{CFL}(n)\) a global Courant-Friedrichs-Lewy (CFL) number [54]. This global CFL number may depend on the iteration count \(n\), for instance, \[\text{CFL}_{iter}(n)=\begin{cases}1.3^{\min(n,9)}&1\leq n\leq 20,\\ 1.3^{9}+9\cdot 1.3^{\min(n-20,9)}&20<n\leq 40,\\ 1.3^{9}+9\cdot 1.3^{9}+90\cdot 1.3^{\min(n-40,9)}&n>40;\end{cases} \tag{16}\] see [54, p. 1108]. Alternatively, it can be given by a controller based on the nonlinear error estimate \(e_{n}\) for iteration \(n\), the given target error estimate "tol", and control parameters \(k_{P}\), \(k_{I}\), and \(k_{D}\), which are positive constants: \[\text{CFL}_{e}(n)=\left(\frac{e_{n-2}}{e_{n-1}}\right)^{kp}\left(\frac{\text{ tol}}{e_{n-1}}\right)^{k_{I}}\left(\frac{e_{n-2}/e_{n-1}}{e_{n-3}/e_{n-2}} \right)^{k_{D}}\text{CFL}_{e}(n-1), \tag{17}\] these options are available for controlling the global CFL number in COMSOL. For both cases, in the initial iterations of pseudo-time stepping, the method starts with a small global CFL number and gradually increases it as the solution reaches convergence [54]. In eq. (16) this is because the CFL number increases each iteration, also shown in Figure 1. For eq. (17), when the solution is near convergence, the error estimates \(e_{n}\) will be smaller and thus the CFL number increases. In this paper we investigate replacing these two pseudo-time step control algorithms by the use of an NN to control the local, mesh element dependent, pseudo-time step \(\Delta t_{e}^{n}\). In order to make the method easily generalizable to different meshes, the NN is provided with local information from the corresponding mesh element and its adjacent mesh elements. One could think of local information about the solution, residuals, mesh and the cell Reynolds number. For example, elements with high local residuals could then have smaller local pseudo-time steps compared to elements with low residuals, which could accelerate convergence in areas which already have low residuals. So, treating each mesh element individually using local information can accelerate convergence for the whole simulation. ## 4 Neural network for the local pseudo-time step prediction In order to predict an element-wise local pseudo-time step for the pseudo-time stepping that yields fast and robust Newton convergence, we employ a data-based approach based on machine learning techniques; more specifically, we use artificial neural networks (ANNs). The most basic form of an ANN is a multilayer perceptron (MLP) and is given as a composed function \[\mathcal{NN}\left(x\right)=W_{n+1}\,\,f_{n}\circ\cdots\circ f_{1}\left(x \right),\] with \[f_{i}\left(x\right)=\sigma\left(W_{i}x+b_{i}\right). \tag{18}\] Here, the \(W_{i}\in\mathbb{R}^{n_{i}\times n_{i-1}}\) and \(b_{i}\in\mathbb{R}^{n_{i}}\) are the so-called weight matrices and bias vectors, which represent the linear parts of the NN function \(\mathcal{NN}\); see Figure 6 for an exemplary net Figure 1: A plot of CFL\({}_{iter}\) depending on the nonlinear iteration count, as defined in eq. (16). work architecture of an MLP. Given a specific network architecture, that is, the dimensions \(\left(n_{i}\right)_{i}\), the MLP is determined by the coefficients of the weight matrices and bias vectors, also denoted as the network parameters. The MLP becomes nonlinear due to composition with the activation function \(\sigma\). Here, we will employ the rectified linear unit (ReLU) function \(\sigma\left(x\right)=\max\left(0,x\right)\). MLPs, and NNs in general, are well-suited for approximating nonlinear functions; see, e.g., [57]. In order fit an NN to input data \(X=\left\{x_{i}\right\}\) and corresponding output data \(Y=\left\{y_{i}\right\}\), a loss function \(\mathcal{L}\) is minimized with respect to the network parameters: \[\arg\min_{W_{i},b_{i}}\mathcal{L}\left(\mathcal{NN}\left(X\right),Y\right)\] The loss function penalizes deviation of the network function from the reference output data \(Y\). In order to optimize the NN parameters (a.k.a. network training), we employ a stochastic gradient descent (SGD) method using adaptive moment estimation (Adam) [58]; the gradients are computed using the backpropagation algorithm [59]. For a more detailed introduction to deep learning and NNs; see, e.g., [60]. In this section, we will discuss how the local pseudo-time steps used as reference data in the root mean squared error (RMSE) loss function are computed as well as the composition of our training data set and the network architecture. ### Loss and optimal local pseudo-time step Our goal is to predict local pseudo-time steps that enhance the pseudo-time stepping method in accelerating convergence of a given flow problem. In particular, we try to predict the vector of local pseudo-time steps \(\overline{\Delta t}_{opt}\) such that the next iterate is as close as possible to the solution of the nonlinear problem. We will denote this as the _the optimal local pseudo-time step_ for an iterate \(\mathbf{v}^{n}\), \(\overline{\Delta t}_{opt}(\mathbf{v}^{n})\), defined by \[\overline{\Delta t}_{opt}(\mathbf{v}^{n}):=\arg\min_{\overline{\Delta t}}|| \mathbf{v}^{n}-\left(M(\overline{\Delta t})+F^{\prime}(\mathbf{v}^{n})\right)^ {-1}F(\mathbf{v}^{n})-\mathbf{v}^{*}||, \tag{19}\] where \(\mathbf{v}^{*}\) satisfies \(F(\mathbf{v}^{*})=0\). The norm that is used here is the \(L^{2}\) norm of the reconstructed velocity components. Figure 2: The local pseudo-time step optimized by SNOPT; the difference between the obtained solution and the converged solution was minimized up to a value of 3.1\(\cdot\)10\({}^{-5}\). Since the optimal local pseudo-time step cannot be computed explicitly, we compute an approximation via an optimization procedure, using the sparse nonlinear optimizer (SNOPT) software package [61; 62]. This optimization is performed within COMSOL; see [51] for more details. For the example of a back-step geometry with laminar flow, we obtain the optimal local pseudo-time step as shown in Figure 2 by using this two step procedure. Once we have computed the local optimal pseudo-time step for all elements in the data set, we optimize the squared error of the network prediction against these reference values. The whole data set consists of a large number of optimal local pseudo-time steps \(\Delta t_{e_{i},opt}(\mathbf{v}^{n})\) computed from various problem configurations, nonlinear iterates \(\mathbf{v}^{n}\), and elements \(e_{i}\) computed using the optimization in COMSOL. To define the complete loss, let \(\Delta t^{(i)}_{pred}\) and \(\Delta t^{(i)}_{opt}\) be the network prediction and optimized pseudo-time steps, respectively, for the \(i\)th data point in a data set with \(n\) data points. The full RMSE loss, is then given as: \[\text{loss}=\sqrt{\frac{1}{n}\sum_{i=1}^{n}\Big{(}\Delta t^{(i)}_{pred}-\Delta t ^{(i)}_{opt}\Big{)}^{2}}. \tag{20}\] ### Neural network input NNs are universal function approximators and can theoretically approximate any continuous nonlinear function up to arbitrary precision; see, for instance, [57; 63; 64]. Therefore, we expect that it is possible to predict the optimal local pseudo-time step, given sufficient input data. On the other hand, we want to limit the complexity of the input data and train a model with strong generalization properties. Therefore, similar to other approaches for NN-enhanced simulations [29; 30; 32], we employ local input data to predict the local optimal pseudo-time step. This means that we do not include any information about the specific global boundary value problem but only data that is given on a local patch of elements around the element of interest, that is, where the local optimal pseudo-time step is to be predicted. As a result, the trained NN model is applicable to any considered laminar flow problem. An additional benefit of using only local data is that the dimensionality and complexity of the data is being limited. Note that, as also noted in [29], due to the local Figure 3: Data point which contains information of a patch of four elements \(e_{j,1}\) to \(e_{j,4}\) with their vertices \(v_{j,1}\) to \(v_{j,6}\); see Table 1 for all input features for the NN model on each element patch. data approach, a single simulation already generates a rich data set: each simulation yields data on a large set of elements over a number of Newton iterations. However, to generate a training data set with sufficient variation to allow for generalization of the model, the training data may be sampled from different simulations with varying flow conditions, induced by different boundary conditions and geometries as well as mesh refinement levels. Let us now discuss the specific data included in the model input. As mentioned before, we employ data from a patch of elements \[P_{j}=\bigcup_{i=1}^{4}e_{j,i}.\] In particular, the patch consists of the element for which we want to compute the local optimal pseudo-time step, \(e_{j,1}\), as well as the (up to) three adjacent elements \(e_{j,2}\), \(e_{j,3}\), and \(e_{j,4}\); cf. figure 3. Specifically, we denote two elements as adjacent if they are connected via an element edge. On each patch, we sample the data listed in table 1 with their respective location. The nodal information is explicitly available from the mixed finite element discretization used in our simulations; cf. the description of our simulation setup in section 2. Let us briefly motivate our choices. Firstly, we include the element size, which is implied by the element edge lengths, and \(\mathbf{u}\) since they are also employed in the computation of the pseudo-time step approach in eq. (15). We complement this \(\mathbf{u}\) by \(p\) to provide a complete description of the finite element solution on the local patch. Moreover, the local information describing the convergence of the Newton iteration is supplied in the form of two different \begin{table} \begin{tabular}{|l|l|l|} \hline **variable** & **unit** & **location** \\ \hline \hline element edge length & m & - \\ \hline \(u\) & \(\nicefrac{{\mathrm{m}}}{{\mathrm{s}}}\) & \(v_{j,1}\), \(v_{j,2}\), \(v_{j,3}\) \\ \hline \(v\) & \(\nicefrac{{\mathrm{m}}}{{\mathrm{s}}}\) & \(v_{j,1}\), \(v_{j,2}\), \(v_{j,3}\) \\ \hline \(p\) & Pa & \(v_{j,1}\), \(v_{j,2}\), \(v_{j,3}\) \\ \hline \(R_{u}\) & & \(v_{j,1}\), \(v_{j,2}\), \(v_{j,3}\) \\ \hline \(R_{v}\) & & \(v_{j,1}\), \(v_{j,2}\), \(v_{j,3}\) \\ \hline \(R_{p}\) & & \(v_{j,1}\), \(v_{j,2}\), \(v_{j,3}\) \\ \hline \(r_{u}\) & \(\nicefrac{{\mathrm{N}}}{{\mathrm{m}^{3}}}\) & \(v_{j,1}\), \(v_{j,2}\), \(v_{j,3}\) \\ \hline \(r_{v}\) & \(\nicefrac{{\mathrm{N}}}{{\mathrm{m}^{3}}}\) & \(v_{j,1}\), \(v_{j,2}\), \(v_{j,3}\) \\ \hline \(r_{p}\) & \(\nicefrac{{\mathrm{kg}}}{{\mathrm{(m^{3}\cdot s)}}}\) & \(v_{j,1}\), \(v_{j,2}\), \(v_{j,3}\) \\ \hline cell Reynolds number & & \(e_{j,1}\) \\ \hline \end{tabular} \end{table} Table 1: Variables used for input for the NN with their given unit and location on one element in the patch, in this case the central element. One data point contains information of four elements, with a non-structured order of the adjacent elements. The two different types of residuals \(r_{\alpha}\) and \(R_{\alpha}\), \(\alpha=u\), \(v\), \(p\) are given in eqs. (21) and (22). types of residuals, i.e., the residual of the discretized system of nonlinear equations \[F(\mathbf{v})=\begin{pmatrix}R_{u}\\ R_{v}\\ R_{p}\end{pmatrix}=\begin{pmatrix}N(u,v)+B^{\top}p\\ B(u,v)\end{pmatrix}=\begin{pmatrix}N(\mathbf{u})+B^{\top}p\\ B(\mathbf{u})\end{pmatrix} \tag{21}\] and the residual obtained by substituting the approximate solution into the system of PDEs eq. (1): \[r_{u} =\rho(u\partial_{x}u+v\partial_{y}u)-\mu(\partial_{x}^{2}u+ \partial_{y}^{2}u)+\partial_{x}p+f_{x},\] \[r_{v} =\rho(u\partial_{x}v+v\partial_{y}v)-\mu(\partial_{x}^{2}v+ \partial_{y}^{2}v)+\partial_{y}p+f_{y}, \tag{22}\] \[r_{p} =\rho(\partial_{x}u+\partial_{y}v).\] The local Reynolds number, as given in equation eq. (2), provides additional information about the local nonlinearity of the flow; it is also used in papers [29; 30; 50] as input for the machine learning model. The input is normalized to have mean 0 and standard deviation by computing the z-score defined as \[z(\sigma)=\frac{x-\mu}{\sigma},\] with \(x\) the evaluated input data, \(\mu\) the mean of the input, and \(\sigma\) the standard deviation of the input [65]. The the mean and standard deviation for centering and scaling the data are saved and later on used to normalize input data from other simulations. Note that, for practical reasons, in our implementation in COMSOL, we collect all input information, as listed in table 1, element by element from each patch. This means that vertex- and edge-based information is duplicated where the elements in the patch touch. As a result, we obtain a total of \(n_{0}=124\) input features for our network model. In practice, one may want to omit the redundant data, however, this is currently not straightforward based on the data structures in our interface from Matlab to COMSOL since the elements in each patch cannot be easily retrieved in a consistent ordering. Moreover, the redundant information implicitly encodes connectivity information, which could alternatively be encoded by a consistent ordering of the elements within the patch. Our numerical results in section 5 indicate that this handling of the input data does not prevent our model to learn from the data. However, in future work, we plan to investigate if using unique input data with a consistent ordering may have a positive effect on our model. Finally, elements which are adjacent to the boundary of the computational domain \(\Omega\), may only have one or two neighboring elements, resulting in patches consisting of two or three elements only. In order to encode this in the data, we set any data of the vertices and edges outside the domain to zero; other approaches for encoding this information are possible and will, again, be considered in future work. ### Generation of training data We train our model based on simulation data from several boundary value problems defined on back-step geometries; see Figure 2 for an exemplary back-step geometry. The boundary conditions for the back-step flow are defined as follows: We impose a parabolic inflow velocity profile at the inlet \(\Gamma_{in}\) and a constant pressure at the outlet \(\Gamma_{out}\) on the right side of the geometry. For the other parts of the boundary, \(\Gamma_{wall}\), a no-slip boundary condition is prescribed. As discussed in section 4.2, due to the locality of the input features, we expect that it suffices to use training data for a single type of geometry, as long as there is enough variation in the data with respect to the individual patches. In particular, we will consider two different base cases of back-step geometries, which we denote as B1 and B2. For both cases, we consider meshes with different levels of refinement and inflow velocities. This also results in flow fields with different Reynolds numbers. Moreover, we use data from different Newton iterations since, as can be seen in Figure 8, the iterate changes quite drastically between different Newton iterations. Additionally, we consider scaled variants of B1 and B2, which we denote as B1S and B2S, respectively. These are obtained by scaling the geometric dimensions of B1 and B2 by a factor of 0.1 and increasing the inflow velocity by a factor of 10; cf. Table 2 for the dimensions of the four different geometries. As a result the Reynolds number remains the same, and we would expect the nonlinear convergence to be similar. By adding the scaled versions to the training configurations, we try to force the model to learn the dependence of the nonlinearity on the Reynolds number. We summarize all configurations considered for the generation of training data in Table 3. In total, we obtain 79 256 data points from all configurations listed in Table 3. To arrive at a balanced distribution of the training data set, we perform the sampling such that we obtain roughly the same number of data points for each element size in the data set; that is, \begin{table} \begin{tabular}{|l|c|c|c|c|} \hline **back-step geometry** & **dim. inflow tunnel (m)** & **dim. outflow tunnel (m)** & **range inflow velocity (m/s)** & **range maximum element size (m)** \\ \hline \hline **B1** & 0.05 \(\times\) 0.25 & 0.12 \(\times\) 1.15 & 0.001 – 0.015 & 0.0106 – 0.0256 \\ \hline **B1S** & 0.005 \(\times\) 0.025 & 0.012 \(\times\) 0.115 & 0.01 – 0.15 & 0.00106 – 0.00256 \\ \hline **B2** & 0.08 \(\times\) 0.25 & 0.22 \(\times\) 1.15 & 0.001 – 0.01 & 0.0126 – 0.0206 \\ \hline **B2S** & 0.008 \(\times\) 0.025 & 0.022 \(\times\) 0.115 & 0.01 – 0.1 & 0.00126 – 0.00206 \\ \hline \end{tabular} \end{table} Table 2: Dimensions of the back-step geometries considered for the training and test data; see Figure 4 for the base geometry. Figure 4: Back-step geometries employed: B1, B1S, B2, and and B2S vary in the width of the inlet \(\Gamma_{in}\) (red), where a parabolic velocity profile is prescribed, and the length of the blue wall segment; cf. Table 2. At the outlet \(\Gamma_{out}\), we prescribe a constant pressure boundary condition, and at all other parts of the boundary, which are denoted as \(\Gamma_{wall}\), a no-slip boundary condition is enforced. For an exemplary flow field, see Figure 8. we select exactly \(3\,500\) data points from all configurations with the same maximum element size. In total, we can categorize \(14\) different simulations based on the maximum element size, which gives a data set of \(49\,000\) data points. To make it easier to applied batch learning for the NN, \(1\,000\) data points are discarded at random. So, in total there are \(48\,000\) data points, of which \(70\%\) are used for training our network model, \(15\%\) are used for testing and \(15\%\) are used for validation. In section 5, we will first discuss how this model performs on configurations with back-step geometry in section 5.1. Then, in sections 5.2 and 5.3, we \begin{table} \begin{tabular}{|l|r|r|r|r|} \hline **back-step** & **number of** & **max. element** & **inflow velocity** & **\# iterations** \\ \cline{2-5} **geometry** & **elements** & **size (m)** & **(m/s)** & **\# iterations** \\ \hline \hline \multirow{6}{*}{**B1**} & \multirow{6}{*}{\(3\,908\)} & \multirow{6}{*}{\(0.0206\)} & \(0.001\) & \(1\), \(10\) \\ & & & \(0.005\) & \(10\) \\ & & & \(0.01\) & \(10\) \\ \cline{2-5} & & & \(0.003\) & \(1\), \(10\) \\ \cline{2-5} & \multirow{3}{*}{\(3\,908\)} & \(0.0206\) & \(0.006\) & \(10\) \\ & & & \(0.009\) & \(10\) \\ \cline{2-5} & & & \(0.002\) & \(1\), \(10\) \\ & & & \(0.007\) & \(10\) \\ & & & \(0.008\) & \(2\), \(4\) \\ & & & \(0.015\) & \(10\) \\ \cline{2-5} & \multirow{3}{*}{\(13\,828\)} & \multirow{3}{*}{\(0.0106\)} & \(0.004\) & \(2\), \(10\) \\ & & & \(0.008\) & \(2\), \(10\) \\ \hline \multirow{6}{*}{**B1S** (scaled B1)} & \multirow{6}{*}{\(3\,908\)} & \multirow{6}{*}{\(0.00206\)} & \(0.01\) & \(1\), \(10\) \\ & & & \(0.05\) & \(10\) \\ \cline{2-5} & & & \(0.1\) & \(10\) \\ \cline{2-5} & \multirow{3}{*}{\(3\,558\)} & \multirow{3}{*}{\(0.00266\)} & \(0.03\) & \(1\), \(10\) \\ & & & \(0.06\) & \(10\) \\ \cline{2-5} & & & \(0.09\) & \(10\) \\ \cline{2-5} & \multirow{3}{*}{\(13\,828\)} & \multirow{3}{*}{\(0.00106\)} & \(0.02\) & \(1\), \(10\) \\ & & & \(0.07\) & \(10\) \\ \cline{2-5} & & & \(0.08\) & \(2\), \(4\) \\ \cline{2-5} & & & \(0.15\) & \(10\) \\ \cline{2-5} & \multirow{3}{*}{\(13\,828\)} & \multirow{3}{*}{\(0.00106\)} & \(0.04\) & \(2\), \(10\) \\ \cline{2-5} & & & \(0.00106\) & \(0.08\) & \(2\), \(10\) \\ \cline{2-5} & & \(5\,808\) & \(0.0156\) & \(0.005\) & \(1\), \(10\) \\ \cline{2-5} & \multirow{3}{*}{\(4\,134\)} & \(0.0186\) & \(0.05\) & \(1\), \(10\) \\ \cline{2-5} & & \(4\,134\) & \(0.00186\) & \(0.1\) & \(2\), \(10\) \\ \cline{2-5} & & \(4\,134\) & \(0.0186\) & \(0.01\) & \(2\), \(10\) \\ \cline{2-5} & \multirow{3}{*}{\(8\,790\)} & \(0.00126\) & \(0.013\) & \(3\), \(10\) \\ \cline{2-5} & & \(5\,808\) & \(0.00156\) & \(0.05\) & \(1\), \(10\) \\ \cline{2-5} & & \(4\,134\) & \(0.00186\) & \(0.1\) & \(2\), \(10\) \\ \cline{2-5} & \multirow{3}{*}{\(8\,790\)} & \(0.00126\) & \(0.13\) & \(3\), \(10\) \\ \cline{2-5} & & & \(0.00126\) & \(0.13\) & \(3\), \(10\) \\ \hline \end{tabular} \end{table} Table 3: Different combinations of mesh sizes and flow velocities of the back-step simulations to create data. The number of obtained data points is given in column 2, which are sampled from the nonlinear iteration steps given in the last column. The dimensions of the four back-steps can be found in Table 2. will also discuss the generalization to other configurations, that is, to Couette flow and flow around an obstacle, respectively. ### Network architecture and training The architecture of the network model employed in this work is depicted in Figure 6: the model consists of an input layer with 124 neurons, two hidden layers with 16 neurons each, and an output layer with the neuron representing prediction of the local optimal pseudo-time step; the composition of the input data has been discussed in section 4.2. We determined the network architecture as follows: We first performed a grid search with 6-fold cross validation on the search space given in Table 4 to determine three different network architectures with an acceptable average validation loss. Note that the loss is defined based on the prediction of the local optimal pseudo-time step; that means a low validation loss does not necessarily result in a low solution residual when the network is used. From the grid search, we determined one network with small, one with medium, and one with high networks capacity, that is, networks with: * 2 hidden layers and 16 neurons per layer, * 3 hidden layers and 64 neurons per layer, \begin{table} \begin{tabular}{|l|l|} \hline **hyper parameter** & **search space** \\ \hline \hline \# hidden layers & \(\{2,3,4,5\}\) \\ \# neurons per hidden layer & \(\{2^{4},2^{5},2^{6},2^{7},2^{8}\}\) \\ \hline \end{tabular} \end{table} Table 4: Hyper parameters and search space for the grid search. \begin{table} \begin{tabular}{|l|l|l|} \hline **geometry** & **inflow/wall** & **max. element size (m)** \\ **type** & **velocity (\(\nicefrac{{m}}{{s}}\))** & \\ \hline \hline **B1** & \(0.001,0.004,0.007\), & \(0.0106:0.005:0.0256\) \\ & \(0.01,0.012,0.015\) & \\ \hline **B1S** & \(0.01,0.04,0.07\), & \(0.00106:0.0005:0.00256\) \\ & \(0.1,0.12,0.15\) & \\ \hline **B2** & \(0.001:0.003:0.01\) & \(0.0126,0.0156,0.0186\), \\ & & \(0.0206\) \\ \hline **B2S** & \(0.01:0.03:0.1\) & \(0.00126,0.00156,0.00186\), \\ & & \(0.00206\) \\ \hline **C** & \(0.01,0.03,0.04\), & \(0.014:0.002:0.022\) \\ & \(0.05,0.07,0.1\) & \\ \hline **CS** & \(0.01,0.03,0.05\) & \(0.0028:0.0004:0.0044\) \\ \hline \end{tabular} \end{table} Table 5: Combinations of velocities and mesh sizes for simulations used to test the NN performance, with the back-step configurations B1–B2S in Table 2 and the Couette flow configurations C1 and C2 in Table 6. * 4 hidden layers and 256 neurons per layer. Then, in order to find the best model for accelerating the Newton convergence, we compare them when applied to several back-step and Couette simulations, further explained in section 5.1 and section 5.2. The combinations of the inflow or wall velocities with the maximum element size used for these simulations are given in Table 5. For each network, the required number of nonlinear iterations per simulation was compared. Surprisingly, the largest network now performed much worse, while the smallest network performed best, which could be explained by an overfitting behavior. Each network is trained based on the different back-step simulations given in Table 2. As mentioned before, the local optimal pseudo-time steps obtained using the SNOPT optimizer are used as the reference. In particular, the network output is compared to these optimized local pseudo-time steps via the RMSE loss function eq. (20). As the optimizer, we use Figure 5: Training plot of network trained on the optimized pseudo-time step targets. Figure 6: Exemplary NN with 124 inputs, 2 hidden layers with 16 neurons and an output layer. The arrows are associated with weights in the weight matrices \(W_{i}\); cf. eq. (18). stochastic gradient descent with adaptive moments (Adam) [58] with an initial learning rate of \(0.001\). As the stopping criterion and regularization, we employ early stopping with a patience of \(150\) epochs. ## 5 Numerical results In this section, we discuss numerical results for our NN-enhanced pseudo-time stepping approach, which we have introduced in the previous section 4. As discussed in section 4.3, we have trained the model only for back-step geometries. Our model is designed such that only local features are used as input in order to enable generalizability. First, we test our model on the _back-step flow_ training cases, with varying mesh sizes and inflow velocities within the range of the training data; cf. section 5.1. In addition to that, we investigate the performance on flipped and rotated cases. Then, in order to further test the generalization properties of the model, we test our model on _Couette cylinder flows_ in section 5.2 as well as for _flow around an obstacle_ cases in section 5.3. For the Couette cases, we vary the geometry, the mesh size, and the velocity of the inner rotating wall, and for the flow around an obstacle, back-step and Couette cylinder geometries with different kinds of obstacles are \begin{table} \begin{tabular}{|l|r|r|r|r|} \hline **Couette** & **radius outer** & **radius inner** & **range wall** & **range maximum** \\ **geometry** & **circle (m)** & **circle (m)** & **velocity (m/s)** & **element size (m)** \\ \hline \hline **C** & 0.4 & 0.2 & 0.01 – 0.1 & 0.014 – 0.022 \\ \hline **CS** & 0.08 & 0.04 & 0.01 – 0.05 & 0.0028 – 0.0044 \\ \hline \end{tabular} \end{table} Table 6: Geometrical dimensions of the two different Couette cylinders with corresponding ranges of velocities for the boundary conditions and maximum element sizes. Figure 7: Convergence plot of a B1 simulation for all three strategies for the local pseudo-time step under consideration: using the NN model as well as the strategies defined in eqs. (16) and (17). considered. In particular, we compare the convergence of our hybrid approach with the convergence of two classical strategies for the choice of the local pseudo-time step described in section 3.2, that is, the strategy denoted by \(\text{CFL}_{iter}\), as given by eqs. (15) and (16), and the strategy denoted by \(\text{CFL}_{e}\), as given by eqs. (15) and (17). Furthermore, in the appendix, the convergence of the network is also compared with two variants of Newton's method, that is, the standard Newton method with a constant damping factor and a variant with an adaptive choice of the damping factor; see appendix A for more details. The \(L^{2}\) norm of the "reconstructed" residual \(\tilde{R}\) \[\|\tilde{R}\|_{L^{2}(\Omega)}=\sqrt{\int_{\Omega}\tilde{R}_{u}^{2}+\tilde{R}_{ v}^{2}+\tilde{R}_{p}^{2}\,dx} \tag{23}\] is used as the stopping criterion. Here, \((\tilde{R}_{u},\tilde{R}_{v})\) and \(\tilde{R}_{p}\) are the residual velocity and pressure fields in \(X_{h}\) reconstructed by using the components of the residual vector \(R=(R_{u},R_{v},R_{p})\), as defined in eq. (21), as coefficients w.r.t. the chosen basis of \(X_{h}\). Note that COMSOL uses a scaled version of the residual eq. (23) in the stopping criterion, such that the tolerance may differ depending on the problem configuration. However, when reporting the convergence results, we make sure that the same tolerance for the unscaled residual eq. (23) is used to determine convergence for the different approaches. All simulations have been performed using COMSOL Multiphysics(r) version 6.1. ### Back-step geometries In this subsection, we discuss the performance of our model on the same four back-step geometries which we also used for the training; cf. section 4.3 and table 2. In particular, we Figure 8: Iterations of B1 with inflow velocity \(0.001\,\text{m/s}\) and maximum element size \(0.0156\,\text{m}\) using NN, with velocities (left) and corresponding distribution of the predicted local pseudo-time step prediction (right). investigate if the network can accelerate the convergence when varying inflow velocity and mesh size on those configurations; cf. Table 5. As a result of those variations, a total of 80 Figure 9: The results of the back-steps for each method; the simulations are ordered from smallest required number of nonlinear iterations to largest separately for each approach. The horizontal lines indicate the average nonlinear iteration counts for the different approaches. different simulations for the back-step geometries are analyzed. Exemplary, we plot the convergence history for the back-step geometry B1 with inflow velocity \(0.001\,\nicefrac{{m}}{{s}}\) and a maximum element size of \(0.0156\,\mathrm{m}\) in Figure 7; in particular, we compare the local optimal pseudo-time step predicted by the network model, which we denote as NN, against the \(\mathrm{CFL}_{iter}\) and \(\mathrm{CFL}_{e}\) approaches based on the iteration count and the evolution of the residual norm. It can be observed that the network speeds up the convergence significantly compared with the two reference approaches; moreover, whereas the residual norm oscillates strongly for \(\mathrm{CFL}_{iter}\), the convergence is almost monotonous for the network and \(\mathrm{CFL}_{e}\) approaches. The qualitative behavior observed in Figure 7, where the classical choices for the CFL number yield slow convergence or even strong oscillations in the residual, is not an exception; similar convergence behavior can also be observed for Couette flow and flow around an obstacle configurations; cf. sections 5.2 and 5.3. Furthermore, in Figure 8, we depict four iterates during the Newton iteration using the network approach as well as the corresponding predicted local optimal pseudo-time step. It can be observed that both the iterate and predicted local optimal pseudo-time step still vary during the first iterations and both become stationary in the later iterations. In Figure 9, we compare the performance with respect to the numbers of Newton iterations resulting from the different choices NN, \(\mathrm{CFL}_{iter}\), and \(\mathrm{CFL}_{e}\) for the pseudo-time step on different back-step configurations; cf. section 4.3 and table 2. Furthermore, as a first investigation of the generalizability, we additionally consider cases resulting from mirroring (BM) or anti-clockwise rotating by 90 degrees (BR) the B1 cases. see appendix A for the results for the Newton methods. This can also be seen in the average number of iterations for the configurations B1, B2, BM, and BR; see Figures 9 and A.17. For B1S, the network performs equally well as \(\text{CFL}_{iter}\). In particular, for cases with lower velocities (B1 and B2), the network performs best. For cases with higher velocities (B1S and B2S) but the same Reynolds numbers, the network model performs clearly worse compared to the low velocity cases. Moreover, it could be observed that, for B1S and B2S, convergence was generally less robust; in particular, we observed a relatively high ratio of cases for which none of the pseudo-time step approaches converged. Since the nonlinearity should be mostly determined by the Reynolds number rather than the magnitude of the velocities, we would like to investigate in future research whether a scaling/normalization of the network inputs can improve the performance. The same behavior can also be observed for the Newton methods, although these methods converge in more cases; cf. appendix A. Even though the mirrored and rotated configurations, of course, yield the same but mirrored respectively rotated results, we observe slight variations in the performance of the network model. This shows a slight overfitting with respect to the B1 configurations as shown exemplarily in Figure 8, where, for instance, the velocities in positive \(x\) direction are dominant; this clearly changes when the geometry is mirrored or rotated. However, the performance of the network model is only slightly worse compared to the B1 cases, which shows that the overfitting is not severe with respect to the prediction of suitable local pseudo-time steps. In the future, we may consider group invariant networks [66] to prevent these geometric overfitting effects. Figure 11: Convergence plot of a C simulation for all three strategies for the local pseudo-time step under consideration: using the NN model as well as the strategies defined in eqs. (16) and (17). ### Couette Next, we discuss the generalization of our hybrid globalization approach to a different type of geometries, that is, Couette cylinders. We consider two different geometries and a range of configurations resulting from varying the wall rotation velocity and refinement of the mesh; cf. table 6. In total, we obtain 45 different configurations of Couette simulations, and in table 5, the corresponding boundary conditions and maximum element sizes for the back-step configurations previously used for training the NN model can be found. Again, we present the iterates and corresponding predicted local pseudo-time steps during the Newton iteration for one exemplary case with C geometry; see figure 10. As for the back-step configuration in figure 8, we observe that both the solution and local pseudo-time step prediction approach a stationary distribution. For this configuration, we observe a significant speed-up of Newton convergence when using the local pseudo-time step prediction by our NN, which has only been trained on back-step geometries; cf. figure 11. Figures 12 and A.18 confirm that the use of our NN-based approach is beneficial for most of the Couette flow cases. First of all, we notice that, for the Couette flow simulations considered, all choices for the local pseudo-time step yield convergence. However, the NN-based approach accelerates convergence in \(70\,\mathrm{\char 37}\) of the C cases and even \(93.3\,\mathrm{\char 37}\) of the CS cases. The fact that the network seems to perform better for CS than for C cases, compared with the \(\mathrm{CFL}_{iter}\) and \(\mathrm{CFL}_{e}\) choices, is remarkable because the CS cases contain higher velocities and smaller mesh element sizes compared to C. For the back-step geometries, we observed the opposite; cf. figure 9, where the network performed worse on B1S and B2S than B1 and B2 configurations. Also when taking the two variants of Newton's method into account in the results in appendix A, the NN approach remains competitive. In particular, the NN is on average close to the best method (for the C configurations) or as good as the best method Figure 12: The results of the Couette flow for each method; the simulations are ordered from smallest required number of nonlinear iterations to largest separately for each approach. The horizontal lines indicate the average nonlinear iteration counts for the different approaches. (for the CS configurations). ### Flow around an obstacle As the final type of test examples, we consider Couette and back-step flow around an obstacle. In particular, we place an obstacle inside the computational domain of the back-step B1 and Couette C configurations; cf. Table 7, where three different obstacle geometries are considered: a circle with radius of \(0.03\,\mathrm{m}\), an ellipse with a-semiaxis \(0.03\,\mathrm{m}\) and b-semiaxis \(0.02\,\mathrm{m}\), and an ellipse with a-semiaxis \(0.02\,\mathrm{m}\) and b-semiaxis \(0.03\,\mathrm{m}\). We denote the resulting configurations as back-step with obstacle (BO) and Couette cylinder with obstacle (CO); see table 7 for more details on the configurations and figure 13 for exemplary flow fields for the three different obstacle geometries in Couette flow. In total, we obtain 30 BO and 45 CO configurations. The results of the simulations with obstacles are given in Figures 16 and A.18. Qualitatively, the NN approach compares to \(\mathrm{CFL}_{iter}\) and \(\mathrm{CFL}_{e}\) similarly as before. It performs better on \(83.3\,\mathrm{\char 37}\) of the BO cases and on more than \(73.3\,\mathrm{\char 37}\) of the CO cases; it can also be observed that the CO cases are more difficult, as in more than \(11\,\mathrm{\char \begin{table} \begin{tabular}{|l|l|l|l|l|} \hline **geometry type** & **x (m)** & **y (m)** & **inflow/wall velocity (m/s)** & **max. element size (m)** \\ \hline \hline **BO** & \(0.37\) & \(0.035\!:\!0.005\!:\!0.08\) & \(0.008\) & \(0.0126\) \\ \hline **BO** & \(0.3,1.1\) & \(0.04\) & \(0.008\) & \(0.0126\) \\ \hline **CO** & \(0.1\) & \(0.4\) & \(0.014\!:\!0.002\!:\!0.022\) & \(0.01,0.03,0.05\) \\ \hline \end{tabular} \end{table} Table 7: Combinations of object center coordinates, velocities and mesh. Here, BO are B1 back-steps in table 2 with obstacles: a circle with radius \(0.03\,\mathrm{m}\), an ellipse with a-semiaxis \(0.03\,\mathrm{m}\) and b-semiaxis \(0.02\,\mathrm{m}\), and an ellipse with a-semiaxis \(0.02\,\mathrm{m}\) and b-semiaxis \(0.03\,\mathrm{m}\). The Couette flow has geometry of C1 in table 6 with obstacles: a circle with radius \(0.04\,\mathrm{m}\), an ellipse with a-semiaxis \(0.03\,\mathrm{m}\) and b-semiaxis \(0.02\,\mathrm{m}\), and an ellipse with a-semiaxis \(0.02\,\mathrm{m}\) and b-semiaxis \(0.03\,\mathrm{m}\). Figure 13: Velocity solutions for Couette flow with different kinds of obstacles. The wall rotation is \(0.07\,\mathrm{\SIUnitSymbolMicro m}\) and the maximum element size is \(0.02\,\mathrm{m}\). The center of the obstacle is x = \(0.1\,\mathrm{m}\) and y = \(0.4\,\mathrm{m}\). approaches converges. Also the average number of iteration is best for the NN approach for the BO and CO configurations. For one of the considered simulations of CO with an elliptic obstacle, we again plot iterates and corresponding distributions of the local pseudo-time step in figure 14. In figure 15, we plot the residual history over the Newton iteration, showing the acceleration from the NN approach. Finally, also compared with the Newton methods in appendix A, the NN performs clearly best, that is, both in terms of robustness and in terms of acceleration of convergence. ## 6 Conclusion We have introduced a novel NN-based approach to improve the pseudo-time stepping algorithm. Instead of using local pseudo-time steps based on predefined global CFL numbers, optimal local pseudo-time step predictions of the network are used to compute the local pseudo-time step. The network uses local information in order to make these local pseudo-time step predictions and to achieve generalizability. As a result, it can accelerate the convergence for the simulations on which it has been trained as well as for simulations which it has not seen before. In all considered simulations, the network was able to perform better or equally well compared to the standard CFL number based pseudo-time stepping strategies in most cases; the same is true in comparison with the variants of Newton's method. In future work, we would like to extend the method to turbulent and three-dimensional Figure 14: Iterations of CO with wall velocity 0.04 m/s and maximum element size of 0.022 m using NN, with velocity (above) and local pseudo-time step prediction (below). The obstacle is an ellipse with a-semiaxis 0.03 m and b-semiaxis 0.05 m, with center x = 0.1 m and y = 0.4 m. flow cases. Furthermore, we will try to improve the method presented here, for example, by generating a more diverse training data set, combining the heuristic strategies for choosing the pseudo-time step with our network approach the default CFL number based strategies and the network, or removing redundancies in the input features. ## Appendix A Comparison against variants of Newton's method In Figures 17 and 18, we show results for all configurations considered, comparing our novel NN approach with four nonlinear solvers implemented in COMSOL, that is, the two default CFL number strategies defined in eqs. (16) and (17) as well as two variants of Newton's method. As variants of Newton's method, we employ the standard Newton method with damping factor of one and an adaptive choice of the damping factor, depending on the intermediate iterates. We denote the two approaches as Newton constant (NC) and automatic Newton (AN), respectively; cf. [54, p. 1627]. Different from Figures 9, 12, and 16, the ordering of the simulations for the different methods is the same for each approach. The simulations are first organized into different blocks, and within each block the ordering is based on the number of nonlinear iterations needed for the NN approach. The blocks are as follows: before the first vertical dashed line, the NN performed best; between the first and second vertical dashed line, the NN performed best with the same number of iterations as at least one other method; between the second and third vertical dashed line, the network performed worse than at least one other method; after the third vertical line, none of the methods converged. The results are mostly in alignment with the previous results as the NC and AN methods often perform similarly to one of the classical CFL strategies considered. In particular, when Figure 15: Convergence plot of a CO simulation with an ellipse with a-semiaxis 0.03 m and b-semiaxis 0.05 m, with center x = 0.1 m and y = 0.4 m for the local pseudo-time step under consideration: using the NN model as well as the strategies defined in eqs. (16) and (17). inspecting the average iteration count, both NC and AN perform quite similarly to CFL\({}_{iter}\) for B1, B1S, BM, BR, CS, and BO configurations; in all those cases the NN approach is clearly competitive. For the CO and B2 cases, AN performs better than NC, while the NN approach performs best. Only for the B2S configuration, where the NN approach generally performed worst, AC seems to perform clearly best; however, all approaches struggle for the B2S cases. Finally, for the C configurations, all methods perform similarly well, except for NC, which fails in most of the cases. In summary, adding the NC and AN approaches to the picture does not change the qualitative comparison much; only for the B2S cases, AN performs clearly better than the NN approach. In future work, this should be taken into account for further improving the NN model.
2301.10152
How Jellyfish Characterise Alternating Group Equivariant Neural Networks
We provide a full characterisation of all of the possible alternating group ($A_n$) equivariant neural networks whose layers are some tensor power of $\mathbb{R}^{n}$. In particular, we find a basis of matrices for the learnable, linear, $A_n$-equivariant layer functions between such tensor power spaces in the standard basis of $\mathbb{R}^{n}$. We also describe how our approach generalises to the construction of neural networks that are equivariant to local symmetries.
Edward Pearce-Crump
2023-01-24T17:39:10Z
http://arxiv.org/abs/2301.10152v2
# How Jellyfish Characterise Alternating Group Equivariant Neural Networks ###### Abstract We provide a full characterisation of all of the possible alternating group (\(A_{n}\)) equivariant neural networks whose layers are some tensor power of \(\mathbb{R}^{n}\). In particular, we find a basis of matrices for the learnable, linear, \(A_{n}\)-equivariant layer functions between such tensor power spaces in the standard basis of \(\mathbb{R}^{n}\). We also describe how our approach generalises to the construction of neural networks that are equivariant to local symmetries. Machine Learning, ICML ## 1 Introduction There has been a growing research effort in deep learning to develop neural network architectures that can be used to efficiently learn from data that possesses an underlying symmetry. These architectures guarantee that the functions that are learned are subject to a geometric property connected with the symmetry group known as _equivariance_. Group equivariant neural networks are important due to the additional advantages that they possess over traditional multilayer perceptron models. They commonly display high levels of parameter sharing within each layer, resulting in significantly fewer parameters overall. This often results in models with improved prediction performance on new data. The symmetry group that has received the most attention, in terms of it being explicitly incorporated into neural network architectures, is the group of all permutations on some fixed number of objects, called the symmetric group. Creating neural networks that are equivariant to permutations is important as many data structures, such as sets and graphs, exhibit natural permutation symmetry. It is easily understood that the labelling of the elements of a set or of the vertices of a graph is arbitrary; hence, it is crucial to ensure that the functions that are learned from such data do not depend on how the data is labelled. In this paper, we look instead at how to construct neural networks that are equivariant to the alternating group. The alternating group is an index two subgroup of the symmetric group consisting solely of all the even permutations in the symmetric group. We give a full characterisation of all of the possible alternating group equivariant neural networks whose layers are some tensor power of \(\mathbb{R}^{n}\) by finding a basis of matrices for the learnable, linear, alternating group equivariant layer functions between such tensor power spaces in the standard basis of \(\mathbb{R}^{n}\). This makes the neural networks in question simple to implement. Our approach is similar the one presented in the papers written by Pearce-Crump (2022a; 2022b). They used different sets of set partition diagrams to characterise all of the learnable, linear, group equivariant layer functions between tensor power spaces in the standard basis of \(\mathbb{R}^{n}\) for the following groups: the symmetric group \(S_{n}\); the orthogonal group \(O(n)\); the symplectic group \(Sp(n)\); and the special orthogonal group \(SO(n)\). We will show that in the case of the alternating group \(A_{n}\), the layer functions can also be characterised by specific sets of set partition diagrams. The main contributions of this paper are as follows: 1. We are the first to show how the combinatorics underlying set partition diagrams, together with some jellyfish, serves as the theoretical foundation for constructing neural networks that are equivariant to the alternating group when the layers are some tensor power of \(\mathbb{R}^{n}\). 2. Specifically, we find a basis for the learnable, linear, \(A_{n}\)-equivariant layer functions between such tensor power spaces in the standard basis of \(\mathbb{R}^{n}\). 3. We extend our approach to show how to construct neural networks that are equivariant to local symmetries. ## 2 Preliminaries We choose our field of scalars to be \(\mathbb{R}\) throughout. Tensor products are also taken over \(\mathbb{R}\), unless otherwise stated. Also, we let \([n]\) represent the set \(\{1,\ldots,n\}\). Recall that a representation of a group \(G\) is a choice of vector space \(V\) over \(\mathbb{R}\) and a group homomorphism \[\rho:G\to GL(V) \tag{1}\] We choose to focus on finite-dimensional vector spaces \(V\) that are some tensor power of \(\mathbb{R}^{n}\) in this paper. We often abuse our terminology by calling \(V\) a representation of \(G\), even though the representation is technically the homomorphism \(\rho\). When the homomorphism \(\rho\) needs to be emphasised alongside its vector space \(V\), we will use the notation \((V,\rho)\). ## 3 \((\mathbb{R}^{n})^{\otimes k}\), a representation of both \(S_{n}\) and \(A_{n}\) Recall that \(S_{n}\) is the group of all permutations on \([n]\), and that \(A_{n}\) is the subgroup of \(S_{n}\) consisting of all permutations on \([n]\) whose image under the function \[\operatorname{sgn}:S_{n}\to\{\pm 1\} \tag{2}\] is \(+1\), where \(\operatorname{sgn}\) is defined, for all \(\sigma\in S_{n}\), as \[\operatorname{sgn}(\sigma)\coloneqq\begin{cases}+1&\text{if $\sigma$ is an even permutation in $S_{n}$}\\ -1&\text{if $\sigma$ is an odd permutation in $S_{n}$}\end{cases} \tag{3}\] We have that \(\mathbb{R}^{n}\) is a representation of \(S_{n}\) via its (left) action on the basis \(\{e_{a}\mid a\in[n]\}\) which is extended linearly, where, specifically, the action is given by \[\sigma\cdot e_{a}=e_{\sigma(a)}\text{ for all $\sigma\in S_{n}$ and $a\in[n]$} \tag{4}\] Restricting this action to \(A_{n}\) and extending linearly shows that \(\mathbb{R}^{n}\) is also a representation of \(A_{n}\). We also have that any \(k\)-tensor power of \(\mathbb{R}^{n}\), \((\mathbb{R}^{n})^{\otimes k}\), for any \(k\in\mathbb{Z}_{\geq 0}\), is a representation of \(S_{n}\), since the elements \[e_{I}\coloneqq e_{i_{1}}\otimes e_{i_{2}}\otimes\cdots\otimes e_{i_{k}} \tag{5}\] for all \(I\coloneqq(i_{1},i_{2},\ldots,i_{k})\in[n]^{k}\) form a basis of \((\mathbb{R}^{n})^{\otimes k}\), and the action of \(S_{n}\) that maps a basis element of \((\mathbb{R}^{n})^{\otimes k}\) of the form (5) to \[e_{\sigma(I)}\coloneqq e_{\sigma(i_{1})}\otimes e_{\sigma(i_{2})}\otimes \cdots\otimes e_{\sigma(i_{k})} \tag{6}\] can be extended linearly. Again, restricting this action to \(A_{n}\) and extending linearly shows that \((\mathbb{R}^{n})^{\otimes k}\) is also a representation of \(A_{n}\). We denote the representation of \(S_{n}\) by \(\rho_{k}\). We will use the same notation for the restriction of this representation to \(A_{n}\), with the context making clear that it is the restriction of the \(S_{n}\) representation. ## 4 Group Equivariant Neural Networks Group equivariant neural networks are constructed by alternately composing linear and non-linear \(G\)-equivariant maps between representations of a group \(G\). We define _\(G\)-equivariance_ below: **Definition 4.1**.: Suppose that \((V,\rho_{V})\) and \((W,\rho_{W})\) are two representations of a group \(G\). A map \(\phi:V\to W\) is said to be \(G\)-equivariant if, for all \(g\in G\) and \(v\in V\), \[\phi(\rho_{V}(g)[v])=\rho_{W}(g)[\phi(v)] \tag{7}\] The set of all _linear_\(G\)-equivariant maps between \(V\) and \(W\) is denoted by \(\operatorname{Hom}_{G}(V,W)\). When \(V=W\), we write this set as \(\operatorname{End}_{G}(V)\). It can be shown that \(\operatorname{Hom}_{G}(V,W)\) is a vector space over \(\mathbb{R}\), and that \(\operatorname{End}_{G}(V)\) is an algebra over \(\mathbb{R}\). See (Segal, 2014) for more details. A special case of \(G\)-equivariance is _\(G\)-invariance_: **Definition 4.2**.: The map \(\phi\) given in Definition 4.1 is said to be \(G\)-invariant if \(\rho_{W}\) is defined to be the \(1\)-dimensional trivial representation of \(G\). As a result, \(W=\mathbb{R}\). We can now define the type of neural network that is the focus of this paper: **Definition 4.3**.: An \(L\)-layer \(G\)-equivariant neural network \(f_{\textit{NN}}\) is a composition of _layer functions_ \[f_{\textit{NN}}\coloneqq f_{L}\circ\ldots\circ f_{l}\circ\ldots\circ f_{1} \tag{8}\] such that the \(l^{\text{th}}\) layer function is a map of representations of \(G\) \[f_{l}:(V_{l-1},\rho_{l-1})\to(V_{l},\rho_{l}) \tag{9}\] that is itself a composition \[f_{l}\coloneqq\sigma_{l}\circ\phi_{l} \tag{10}\] of a learnable, linear, \(G\)-equivariant function \(\phi_{l}:(V_{l-1},\rho_{l-1})\to(V_{l},\rho_{l})\) together with a fixed, non-linear activation function \(\sigma_{l}:(V_{l},\rho_{l})\to(V_{l},\rho_{l})\) such that 1. \(\sigma_{l}\) is a \(G\)-equivariant map, as in (7), and 2. \(\sigma_{l}\) acts pointwise (after a basis has been chosen for each copy of \(V_{l}\) in \(\sigma_{l}\).) We focus on the learnable, linear, \(G\)-equivariant functions in this paper, since the non-linear functions are fixed. _Remark 4.4_.: The entire neural network \(f_{\textit{NN}}\) is itself a \(G\)-equivariant function because it can be shown that the composition of any number of \(G\)-equivariant functions is itself \(G\)-equivariant. _Remark 4.5_.: One way of making a neural network of the form given in Definition 4.3\(G\)-invariant is by choosing the representation in the final layer to be the \(1\)-dimensional trivial representation of \(G\). ## 5 Symmetric Group In this section, we recall the technique of using set partitions to find a basis of \(\mathrm{Hom}_{S_{n}}((\mathbb{R}^{n})^{\otimes k},(\mathbb{R}^{n})^{\otimes l})\) in the standard basis of \(\mathbb{R}^{n}\) since it will feature heavily in what follows for the alternating group. For more details, see (Pearce-Crump, 2022). ### Set Partitions For \(l,k\in\mathbb{Z}_{\geq 0}\), consider the set \([l+k]\) having \(l+k\) elements. We can create a set partition of \([l+k]\) by partitioning it into a number of subsets. We call the subsets of a set partition _blocks_. Define \(\Pi_{l+k}\) to be the set of all set partitions of \([l+k]\). Let \(\Pi_{l+k,n}\) be the subset of \(\Pi_{l+k}\) consisting of all set partitions of \([l+k]\) having at most \(n\) blocks. As the number of set partitions in \(\Pi_{l+k}\) having exactly \(t\) blocks is the Stirling number \(\left\{\begin{smallmatrix}l+k\\ t\end{smallmatrix}\right\}\) of the second kind, we see that the number of elements in \(\Pi_{l+k}\) is equal to \(\mathrm{B}(l+k)\), the \((l+k)^{\text{th}}\) Bell number, and that the number of elements in \(\Pi_{l+k,n}\) is therefore equal to \[\sum_{t=1}^{n}\left\{\begin{smallmatrix}l+k\\ t\end{smallmatrix}\right\}\coloneqq\mathrm{B}(l+k,n) \tag{11}\] the \(n\)-restricted \((l+k)^{\text{th}}\) Bell number. For each set partition \(\pi\) in \(\Pi_{l+k}\), we can define a diagram \(d_{\pi}\) that has two rows of vertices and edges between vertices such that there are 1. \(l\) vertices on the top row, labelled by \(1,\ldots,l\) 2. \(k\) vertices on the bottom row, labelled by \(l+1,\ldots,l+k\), and 3. the edges between the vertices correspond to the connected components of the set partition that indexes the diagram. As a result, \(d_{\pi}\) represents the equivalence class of all diagrams with connected components equal to the blocks of \(\pi\). For example, if \(l=3\) and \(k=5\), the diagram corresponding to the set partition \[\pi\coloneqq\{1,5\mid 2,4\mid 3,6,8\mid 7\} \tag{12}\] in \(\Pi_{8}\) consisting of \(4\) blocks is given in Figure 1. We can define another diagram related to each set partition \(\pi\) in \(\Pi_{l+k}\): it is the flattened version of \(d_{\pi}\), where we pull the top row of \(l\) vertices down and to the left of the bottom row of \(k\) vertices, maintaining the order of the labels. For example, the flattened diagram corresponding to the set partition (12) is given in Figure 2. ### A Basis of \(\mathrm{Hom}_{S_{n}}((\mathbb{R}^{n})^{\otimes k},(\mathbb{R}^{n})^{\otimes l})\) We begin by noting that \(\mathrm{Hom}((\mathbb{R}^{n})^{\otimes k},(\mathbb{R}^{n})^{\otimes l})\) has a standard basis of matrix units \[\{E_{I,J}\}_{I\in[n]^{l},J\in[n]^{k}} \tag{13}\] where \(E_{I,J}\) has a \(1\) in the \((I,J)\) position and is \(0\) elsewhere. Hence, expressing \(f\in\mathrm{Hom}((\mathbb{R}^{n})^{\otimes k},(\mathbb{R}^{n})^{\otimes l})\) in this basis as \[f=\sum_{I\in[n]^{l}}\sum_{J\in[n]^{k}}f_{I,J}E_{I,J} \tag{14}\] it can be shown that \(f\in\mathrm{Hom}_{S_{n}}((\mathbb{R}^{n})^{\otimes k},(\mathbb{R}^{n})^{ \otimes l})\) if and only if \[f_{\sigma(I),\sigma(J)}=f_{I,J} \tag{15}\] for all \(\sigma\in S_{n}\) and \(I\in[n]^{l},J\in[n]^{k}\). Concatenating each \(I\in[n]^{l},J\in[n]^{k}\) into a single element \((I,J)\in[n]^{l+k}\), we see from (15) that the basis elements of \(\mathrm{Hom}_{S_{n}}((\mathbb{R}^{n})^{\otimes k},(\mathbb{R}^{n})^{\otimes l})\) are in bijective correspondence with the orbits coming from the action of \(S_{n}\) on \([n]^{l+k}\), where \(\sigma\in S_{n}\) acts on the pair \((I,J)\) by \[\sigma(I,J)\coloneqq(\sigma(I),\sigma(J)) \tag{16}\] As \(S_{n}\) acts on \([n]\) transitively, it acts on \([n]^{l+k}\) transitively, meaning that the orbits under this action actually partition the set \([n]^{l+k}\) into equivalence classes. Furthermore, we can define a bijection between the orbits coming from the action of \(S_{n}\) on \([n]^{l+k}\) and the set partitions \(\pi\) in \(\Pi_{l+k}\) having at most \(n\) blocks. Indeed, if \((I,J)\) is a class representative of an orbit, then, replacing momentarily the elements of \(J\) by \(i_{l+m}\coloneqq j_{m}\) for all \(m\in[k]\), so that \[(I,J) =(i_{1},i_{2},\ldots,i_{l},j_{1},j_{2},\ldots,j_{k})\] \[=(i_{1},i_{2},\ldots,i_{l},i_{l+1},i_{l+2},\ldots i_{l+k}) \tag{17}\] Figure 2: The flattened diagram corresponding to the set partition \(\pi\) given in (12). Figure 1: The diagram \(d_{\pi}\) corresponding to the set partition \(\pi\) given in (12) with \(l=3\) and \(k=5\). we define the bijection by \[i_{x}=i_{y}\iff x,y\text{ are in the same block of }\pi \tag{18}\] for all \(x\), \(y\in[l+k]\). The bijection (18) is independent of the choice of class representative since \[i_{x}=i_{y}\iff\sigma(i_{x})=\sigma(i_{y})\text{ for all }\sigma\in S_{n} \tag{19}\] Notice that the LHS of (18) is checking for an equality on the elements of \([n]\), whereas the RHS is separating the elements of \([l+k]\) into blocks; hence \(\pi\) must have at most \(n\) blocks. As a result, we have shown the following. **Theorem 5.1**.: _The basis elements of \(\operatorname{Hom}_{S_{n}}((\mathbb{R}^{n})^{\otimes k},(\mathbb{R}^{n})^{ \otimes l})\), in the standard basis of \(\mathbb{R}^{n}\), correspond bijectively with all set partitions \(\pi\) in \(\Pi_{l+k}\) having at most \(n\) blocks, which correspond bijectively with the orbits coming from the action of \(S_{n}\) on \([n]^{l+k}\)._ We can obtain the basis elements themselves, as follows: Taking a set partition \(\pi\) in \(\Pi_{l+k,n}\), and denoting the number of blocks in \(\pi\) by \(t\), we obtain a labelling of the blocks by letting \(B_{1}\) be the block that contains the number \(1\in[l+k]\), and iteratively letting \(B_{j}\), for \(1<j\leq t\), be the block that contains the smallest number in \([l+k]\) that is not in \(B_{1}\cup B_{2}\cup\cdots\cup B_{j-1}\). Using this labelling of the blocks, we can create an element of \([n]^{l+k}\) by letting the \(i^{\text{th}}\) position, \(i\in[l+k]\), be the label of the block containing the number \(i\). This is called the _block labelling_ of \(\pi\). Denote it by the pair \((I_{\pi},J_{\pi})\), where clearly \(I_{\pi}\in[n]^{l},J_{\pi}\in[n]^{k}\). In doing so, we have created a representative of the orbit for the \(S_{n}\) action on \([n]^{l+k}\) corresponding to the set partition \(\pi\in\Pi_{l+k,n}\) under the bijection given in (18). Denote this orbit by \(O_{S_{n}}((I_{\pi},J_{\pi}))\). We form a basis element of \(\operatorname{Hom}_{S_{n}}((\mathbb{R}^{n})^{\otimes k},(\mathbb{R}^{n})^{ \otimes l})\), denoted by \(X_{\pi}\), by adding together all matrix units whose indexing pair \((I,J)\) appears in the orbit \(O_{S_{n}}((I_{\pi},J_{\pi}))\); that is, \[X_{\pi}\coloneqq\sum_{(I,J)\in O_{S_{n}}((I_{\pi},J_{\pi}))}E_{I,J} \tag{20}\] We see that \(X_{\pi}\) is a basis element of \(\operatorname{Hom}_{S_{n}}((\mathbb{R}^{n})^{\otimes k},(\mathbb{R}^{n})^{ \otimes l})\) by (15). Doing this for each set partition \(\pi\) in \(\Pi_{l+k,n}\), or, equivalently, for all of the orbits coming from the action of \(S_{n}\) on \([n]^{l+k}\), gives: **Theorem 5.2** ([10]).: _For \(l,k\in\mathbb{Z}_{\geq 0},n\in\mathbb{Z}_{\geq 1}\), we have that_ \[\{X_{\pi}\mid\pi\in\Pi_{l+k,n}\} \tag{21}\] _is a basis of \(\operatorname{Hom}_{S_{n}}((\mathbb{R}^{n})^{\otimes k},(\mathbb{R}^{n})^{ \otimes l})\), and so_ \[\dim\operatorname{Hom}_{S_{n}}((\mathbb{R}^{n})^{\otimes k},(\mathbb{R}^{n}) ^{\otimes l})=\operatorname{B}(l+k,n) \tag{22}\] ## 6 Alternating Group In exactly the same way as for the symmetric group, we can show that the basis elements of \(\operatorname{Hom}_{A_{n}}((\mathbb{R}^{n})^{\otimes k},(\mathbb{R}^{n})^{ \otimes l})\) are in bijective correspondence with the orbits coming from the action of \(A_{n}\) on \([n]^{l+k}\). However, the major difference between the symmetric group and the alternating group is that the \(A_{n}\) orbits on \([n]^{l+k}\), and consequently the basis elements of \(\operatorname{Hom}_{A_{n}}((\mathbb{R}^{n})^{\otimes k},(\mathbb{R}^{n})^{ \otimes l})\), are not necessarily in bijective correspondence with the set partitions of \([l+k]\) having at most \(n\) blocks. This is because some of the \(S_{n}\) orbits on \([n]^{l+k}\) become the disjoint union of more than one \(A_{n}\) orbit on \([n]^{l+k}\). We say that an \(S_{n}\) orbit on \([n]^{l+k}\)_splits_ if it is the disjoint union of more than one \(A_{n}\) orbit on \([n]^{l+k}\). Our first task is to identify which \(S_{n}\) orbits on \([n]^{l+k}\) split and which do not. Let \(\pi\) be a set partition in \(\Pi_{l+k,n}\) having some \(t\) blocks. Its corresponding \(S_{n}\) orbit on \([n]^{l+k}\) is \(O_{S_{n}}((I_{\pi},J_{\pi}))\). Choose some arbitrary element \((I_{\alpha},J_{\alpha})\in O_{S_{n}}((I_{\pi},J_{\pi}))\), and consider its \(A_{n}\) orbit on \([n]^{l+k}\). We shall denote it by \(O_{A_{n}}((I_{\alpha},J_{\alpha}))\). Clearly, \(O_{A_{n}}((I_{\alpha},J_{\alpha}))\subseteq O_{S_{n}}((I_{\pi},J_{\pi}))\), since \(A_{n}\) is a subgroup of \(S_{n}\). Denote the stabilizer of \((I_{\pi},J_{\pi})\) under the action of \(S_{n}\) by \(\operatorname{Stab}_{S_{n}}((I_{\pi},J_{\pi}))\), and the stabilizer of \((I_{\alpha},J_{\alpha})\) under the action of \(A_{n}\) by \(\operatorname{Stab}_{A_{n}}((I_{\alpha},J_{\alpha}))\). Then, by the Orbit-Stabilizer Theorem, we have that \[|O_{S_{n}}((I_{\pi},J_{\pi}))|=\frac{|S_{n}|}{|\operatorname{Stab}_{S_{n}}((I_{ \pi},J_{\pi}))|}=\frac{n!}{(n-t)!} \tag{23}\] as \(\operatorname{Stab}_{S_{n}}((I_{\pi},J_{\pi}))\cong S_{n-t}\), and \[|O_{A_{n}}((I_{\alpha},J_{\alpha}))| =\frac{|A_{n}|}{|\operatorname{Stab}_{A_{n}}((I_{\alpha},J_{\alpha }))|}\] \[=\frac{n!}{2|\operatorname{Stab}_{A_{n}}((I_{\alpha},J_{\alpha}))|} \tag{24}\] Since each \(S_{n}\) orbit will either be an \(A_{n}\) orbit or a disjoint union of \(A_{n}\) orbits, by studying \(\operatorname{Stab}_{A_{n}}((I_{\alpha},J_{\alpha}))\), we shall see under what conditions the \(S_{n}\) orbits split. Indeed, these conditions are given in the following theorem: **Theorem 6.1** (\(S_{n}\) orbits split).: _Let \(\pi\) be a set partition in \(\Pi_{l+k,n}\) having some \(t\) blocks, and consider its corresponding \(S_{n}\) orbit on \([n]^{l+k}\), \(O_{S_{n}}((I_{\pi},J_{\pi}))\)._ _If \(t\leq n-2\), then \(O_{S_{n}}((I_{\pi},J_{\pi}))\) does not split._ _If \(t=n-1\) or \(n\), then \(O_{S_{n}}((I_{\pi},J_{\pi}))\) splits into a disjoint union of exactly two \(A_{n}\) orbits._ Proof.: Consider the case where \(\pi\) has \(t=n\) blocks. We look at \(\operatorname{Stab}_{A_{n}}((I_{\alpha},J_{\alpha}))\). As all of the elements in \([n]\) appear in the tuple \((I_{\alpha},J_{\alpha})\), the only element of \(A_{n}\) that fixes the entries of \((I_{\alpha},J_{\alpha})\) is the identity element; that is, \(\operatorname{Stab}_{A_{n}}((I_{\alpha},J_{\alpha}))=\{e_{A_{n}}\}\). Hence, by (24), we have that \(|O_{A_{n}}((I_{\alpha},J_{\alpha}))|=\frac{n!}{2}\). Since \(|O_{S_{n}}((I_{\pi},J_{\pi}))|=n!\) in this case, by (23), and because \((I_{\alpha},J_{\alpha})\) was an arbitrary element of \(O_{S_{n}}((I_{\pi},J_{\pi}))\), we have that \(O_{S_{n}}((I_{\pi},J_{\pi}))\) splits into a disjoint union of two \(A_{n}\) orbits. Similarly, for the case where \(\pi\) has \(t=n-1\) blocks, we see that \(\operatorname{Stab}_{A_{n}}((I_{\alpha},J_{\alpha}))=\{e_{A_{n}}\}\), and so, by the same argument, we have that \(O_{S_{n}}((I_{\pi},J_{\pi}))\) splits into a disjoint union of two \(A_{n}\) orbits. Finally, for \(t\leq n-2\), we have that \(\operatorname{Stab}_{A_{n}}((I_{\alpha},J_{\alpha}))\cong A_{n-t}\), and so, by (23) and (24), we see that \(|O_{A_{n}}((I_{\alpha},J_{\alpha}))|=|O_{S_{n}}((I_{\pi},J_{\pi}))|\). Consequently, the \(S_{n}\) orbit \(O_{S_{n}}((I_{\pi},J_{\pi}))\) does not split. As a result, we immediately obtain the following two theorems: **Theorem 6.2**.: _Let \(k,l\in\mathbb{Z}_{\geq 0}\) and \(n\in\mathbb{Z}_{\geq 1}\)._ _If \(\pi\) is a set partition in \(\Pi_{l+k,n}\) having \(n-2\) blocks or fewer, then \(\pi\) corresponds bijectively to a basis element of \(\operatorname{Hom}_{A_{n}}((\mathbb{R}^{n})^{\otimes k},(\mathbb{R}^{n})^{ \otimes l})\),_ _Otherwise, \(\pi\) corresponds to two basis elements of \(\operatorname{Hom}_{A_{n}}((\mathbb{R}^{n})^{\otimes k},(\mathbb{R}^{n})^{ \otimes l})\)._ **Theorem 6.3**.: _For \(k,l\in\mathbb{Z}_{\geq 0},n\in\mathbb{Z}_{\geq 1}\), the dimension of \(\operatorname{Hom}_{A_{n}}((\mathbb{R}^{n})^{\otimes k},(\mathbb{R}^{n})^{ \otimes l})\) is equal to_ \[\sum_{t=1}^{n-2}\genfrac{\{}{\}}{0.0pt}{}{l+k}{t}+2\genfrac{\{}{\}}{0.0pt}{}{ l+k}{n-1}+2\genfrac{\{}{\}}{0.0pt}{}{l+k}{n} \tag{25}\] In other words, Theorem 6.2 tells us that finding a basis of \(\operatorname{Hom}_{A_{n}}((\mathbb{R}^{n})^{\otimes k},(\mathbb{R}^{n})^{ \otimes l})\) in the standard basis of \(\mathbb{R}^{n}\) is very similar to finding a basis of \(\operatorname{Hom}_{S_{n}}((\mathbb{R}^{n})^{\otimes k},(\mathbb{R}^{n})^{ \otimes l})\) in the standard basis of \(\mathbb{R}^{n}\), since finding the basis amounts once again to considering all of the set partitions of \([l+k]\) having at most \(n\) blocks. Indeed, if a set partition \(\pi\) in \(\Pi_{l+k,n}\) has at most \(n-2\) blocks, then we see that \(X_{\pi}\) given in (20) is a basis element of \(\operatorname{Hom}_{A_{n}}((\mathbb{R}^{n})^{\otimes k},(\mathbb{R}^{n})^{ \otimes l})\) since, in this case, \(O_{S_{n}}((I_{\pi},J_{\pi}))=O_{A_{n}}((I_{\pi},J_{\pi}))\), by Theorem 6.1. The question remains as to how to take a set partition \(\pi\) in \(\Pi_{l+k,n}\) having either \(n-1\) or \(n\) blocks and use it to obtain the two basis elements of \(\operatorname{Hom}_{A_{n}}((\mathbb{R}^{n})^{\otimes k},(\mathbb{R}^{n})^{ \otimes l})\) that it corresponds to. Said differently, we would like to take such a set partition \(\pi\) and identify the two \(A_{n}\) orbits that its corresponding \(S_{n}\) orbit on \([n]^{l+k}\), \(O_{S_{n}}((I_{\pi},J_{\pi}))\), splits into. ### Enter: the Jellyfish Comes (2020) originally came up with the idea of using _jellyfish_ to identify the two \(A_{n}\) orbits; here, however, our choice of exposition is rather different and our proofs are simpler than those given in their paper. We begin by defining the following map. **Definition 6.4**.: For \(n\in\mathbb{Z}_{\geq 1}\), we define the determinant map \[\det:(\mathbb{R}^{n})^{\otimes n}\to\mathbb{R} \tag{26}\] on the standard basis of \((\mathbb{R}^{n})^{\otimes n}\) by \[e_{I}=e_{i_{1}}\otimes\cdots\otimes e_{i_{n}}\mapsto\left|e_{i_{1}}\quad \ldots\quad e_{i_{n}}\right| \tag{27}\] and extend linearly, where the RHS of (27) is the determinant of an \(n\times n\) matrix. **Lemma 6.5**.: _The determinant map is an element of \(\operatorname{Hom}_{A_{n}}((\mathbb{R}^{n})^{\otimes n},(\mathbb{R}^{n})^{ \otimes 0})\), but it is not an element of \(\operatorname{Hom}_{S_{n}}((\mathbb{R}^{n})^{\otimes n},(\mathbb{R}^{n})^{ \otimes 0})\)._ Proof.: It is clear that the determinant map is a linear map. Then, for any \(\sigma\in S_{n}\), we have that \[\det(\rho_{n}(\sigma)[e_{I}])=(-1)^{\operatorname{sgn}(\sigma)}\det(e_{I}) \tag{28}\] since a transposition in \(S_{n}\) corresponds to swapping two columns of the \(n\times n\) matrix. As \(\operatorname{sgn}(\sigma)=1\) for all \(\sigma\in A_{n}\), (28) shows that \(\det\) is an element of \(\operatorname{Hom}_{A_{n}}((\mathbb{R}^{n})^{\otimes n},(\mathbb{R}^{n})^{ \otimes 0})\). It is enough to see that for any odd permutation in \(S_{n}\), (28) implies that \(\det\) is not an element of \(\operatorname{Hom}_{S_{n}}((\mathbb{R}^{n})^{\otimes n},(\mathbb{R}^{n})^{ \otimes 0})\). For each \(n\in\mathbb{Z}_{\geq 1}\), we represent the determinant map by a diagram that has a single row of \(n\) vertices, each of which is attached to a blue head. We will call this diagram a _jellyfish_, for obvious reasons. For example, if \(n=3\), the jellyfish has the form _Remark 6.6_.: It is important to highlight that the determinant map (26) is different from the determinant operator on an \(n\times n\) matrix. In particular, the determinant map is a linear map on \((\mathbb{R}^{n})^{\otimes n}\) whereas the determinant operator on \(n\times n\) matrices is not linear. We introduce the following useful lemma. **Lemma 6.7**.: _The determinant map applied to a standard basis vector of \((\mathbb{R}^{n})^{\otimes n}\) gives either \(-1,0\) or \(+1\)._ Proof.: Let \(e_{I}=e_{i_{1}}\otimes\cdots\otimes e_{i_{n}}\) be a standard basis vector of \((\mathbb{R}^{n})^{\otimes n}\). If \(i_{x}=i_{y}\) for some \(1\leq x\neq y\leq n\), then \(\det(e_{I})=0\) since two columns in the \(n\times n\) matrix will be the same. Otherwise, \(\{i_{1},\ldots,i_{n}\}\) is some permutation of \([n]\). Defining \(e_{[n]}\coloneqq e_{1}\otimes\cdots\otimes e_{n}\), we know that \(\det(e_{[n]})=+1\). Since, in this case, \(e_{I}=\rho_{n}(\sigma)e_{[n]}\) for some \(\sigma\in S_{n}\), we can use (28) to calculate \(\det(e_{I})\), giving a result of \(\pm 1\). _Remark 6.8_.: We can view Lemma 6.7 in another way; namely, that the determinant map splits basis vectors of \((\mathbb{R}^{n})^{\otimes n}\) into disjoint classes. Let us call these classes \(-1,0\) and \(+1\). Consequently, Remark 6.8 suggests that the determinant map is a possible candidate function for identifying the \(A_{n}\) orbits that the \(S_{n}\) orbit \(O_{S_{n}}((I_{\pi},J_{\pi}))\) splits into, where \(\pi\) is a set partition in \(\Pi_{l+k,n}\) having either \(n-1\) or \(n\) blocks. However, since the determinant map is a map \((\mathbb{R}^{n})^{\otimes n}\to\mathbb{R}\), and the elements of \(O_{S_{n}}((I_{\pi},J_{\pi}))\) are elements of \([n]^{l+k}\), to use the determinant map to try to identify the \(A_{n}\) orbits in \(O_{S_{n}}((I_{\pi},J_{\pi}))\), it would be useful to create a map \(g_{\pi}:(\mathbb{R}^{n})^{\otimes l+k}\to(\mathbb{R}^{n})^{\otimes n}\) that corresponds bijectively with the set partition \(\pi\), since such a map would project standard basis elements of \((\mathbb{R}^{n})^{\otimes l+k}\) onto, at the very least, a linear combination of basis elements of \((\mathbb{R}^{n})^{\otimes n}\). We could then use the splitting property of the determinant map on such linear combinations to try to split the elements of \(O_{S_{n}}((I_{\pi},J_{\pi}))\) into different classes. However, in order to use the three classes given in Remark 6.8, we cannot choose any map \((\mathbb{R}^{n})^{\otimes l+k}\to(\mathbb{R}^{n})^{\otimes n}\). We will see that with a clever choice of \(g_{\pi}\), the determinant map then splits the elements of \(O_{S_{n}}((I_{\pi},J_{\pi}))\) into the \(\pm 1\) classes and sends all other elements of \([n]^{l+k}\) to the \(0\) class. We create \(g_{\pi}\) as follows. Flatten the diagram \(d_{\pi}\) that corresponds to \(\pi\). Add a new top row of \(n\) nodes above the row of \(l+k\) vertices. From the bottom row, take the lowest numbered vertex in block \(i\) of \(\pi\), \(1\leq i\leq t\), where \(t=n-1\) or \(n\), and connect that vertex to vertex \(i\) in the top row. Call this new diagram \(b_{\pi}\). We claim the following: **Proposition 6.9**.: _The diagram \(b_{\pi}\) corresponds bijectively with a basis element of \(\operatorname{Hom}_{S_{n}}((\mathbb{R}^{n})^{\otimes l+k},(\mathbb{R}^{n})^{ \otimes n})\). Consequently, we define \(g_{\pi}\) to be this basis element._ Proof.: It is clear that the diagram \(b_{\pi}\) corresponds to a set partition of \([n+l+k]\) having exactly \(n\) blocks. Hence this set partition is an element of \(\Pi_{n+l+k,n}\). Since each set partition in \(\Pi_{n+l+k,n}\) corresponds bijectively with a basis element of \(\operatorname{Hom}_{S_{n}}((\mathbb{R}^{n})^{\otimes l+k},(\mathbb{R}^{n})^{ \otimes n})\), by Theorem 5.2, we obtain the result. The following result is immediate from the construction of the diagram \(b_{\pi}\). **Proposition 6.10**.: _In the standard basis of matrix units of \(\operatorname{Hom}((\mathbb{R}^{n})^{\otimes l+k},(\mathbb{R}^{n})^{\otimes n})\), \(g_{\pi}\) is given by_ \[g_{\pi}\coloneqq\sum_{(K,I,J)\in O_{S_{n}}((K_{\pi},I_{\pi},J_{\pi}))}E_{K,(I,J)} \tag{29}\] _where_ \[K_{\pi}\coloneqq(1,2,\ldots,n) \tag{30}\] _and \(O_{S_{n}}((K_{\pi},I_{\pi},J_{\pi}))\) is defined to be_ \[\left\{(K,I,J)\left.\begin{array}{l}(I,J)\in O_{S_{n}}((I_{\pi},J_{\pi}))\\ \text{and if }(I,J)=\sigma(I_{\pi},J_{\pi}),\\ \text{then }K\coloneqq\sigma(K_{\pi})\end{array}\right\} \tag{31}\] In order to see that \(g_{\pi}\) has the properties that we need, we first define the following map. **Definition 6.11**.: Let \(\pi\) be a set partition in \(\Pi_{l+k,n}\) having either \(n-1\) or \(n\) blocks. Then we define \(f_{\pi}\coloneqq\det\circ g_{\pi}:(\mathbb{R}^{n})^{\otimes l+k}\to\mathbb{R}\). Clearly, \(f_{\pi}\) corresponds bijectively with the set partition \(\pi\). We can associate to \(f_{\pi}\) a diagram that is built from the composition of \(b_{\pi}\) (which corresponds to the map \(g_{\pi}\)) and a jellyfish (which corresponds to the determinant map). For example, the diagram that is associated to \(f_{\pi}\) for the set partition \(\pi\) whose diagram \(d_{\pi}\) is given in Figure 1, where we choose \(l=3\), \(k=5\) and \(n=5\), is **Proposition 6.12**.: _The map \(f_{\pi}\) is an element of \(\operatorname{Hom}_{A_{n}}((\mathbb{R}^{n})^{\otimes l+k},(\mathbb{R}^{n})^{ \otimes 0})\)._ Proof.: Let \(e_{(I,J)}\) be any standard basis vector in \((\mathbb{R}^{n})^{\otimes l+k}\), where \(I\in[n]^{l},J\in[n]^{k}\). Then, for all \(\sigma\in A_{n}\), we have that \[f_{\pi}(\rho_{l+k}(\sigma)[e_{(I,J)}]) =\det\circ g_{\pi}(\rho_{l+k}(\sigma)[e_{(I,J)}]) \tag{32}\] \[=\det(\rho_{n}(\sigma)[g_{\pi}(e_{(I,J)})])\] (33) \[=\det(g_{\pi}(e_{(I,J)}))\] (34) \[=f_{\pi}(e_{(I,J)}) \tag{35}\] where, in (33), we have used Proposition 6.9 and in (34), we have used (28). We come to the crucial result for our purposes. **Theorem 6.13**.: _Let \(e_{(I,J)}\) be any standard basis vector in \((\mathbb{R}^{n})^{\otimes l+k}\), where \(I\in[n]^{l},J\in[n]^{k}\)._ _Then_ \[f_{\pi}:e_{(I,J)}\to\begin{cases}\pm 1&\text{if }(I,J)\in O_{S_{n}}((I_{\pi},J_{ \pi}))\\ 0&\text{otherwise}\end{cases} \tag{36}\] Proof.: For any standard basis vector \(e_{(I,J)}\) in \((\mathbb{R}^{n})^{\otimes l+k}\), we have, on a matrix unit of \(\operatorname{Hom}((\mathbb{R}^{n})^{\otimes l+k},(\mathbb{R}^{n})^{\otimes n})\), that \[E_{K,(L,M)}e_{(I,J)}=\delta_{((L,M),(I,J))}e_{K} \tag{37}\] where \(e_{K}\) is a standard basis vector in \((\mathbb{R}^{n})^{\otimes n}\). Hence, by (29), we see that, for the otherwise case, \(g_{\pi}(e_{(I,J)})=0\), and so \(f_{\pi}(e_{(I,J)})=0\). If \((I,J)\in O_{S_{n}}((I_{\pi},J_{\pi}))\), then we have that \((I,J)=\sigma(I_{\pi},J_{\pi})\) for some \(\sigma\in S_{n}\). Hence, by (29), (37) and the definition of \(O_{S_{n}}((K_{\pi},I_{\pi},J_{\pi}))\) given in (31), we see that \(g_{\pi}(e_{(I,J)})=e_{K}\), where \(K=\sigma(K_{\pi})\). Since \(K\) is a permutation of \([n]\), we can apply Lemma 6.7 to get that \(f_{\pi}(e_{(I,J)})=\det(e_{K})=\pm 1\). Consequently, we can define the following two sets: \[O_{\pi}^{+}\coloneqq\{(I,J)\in O_{S_{n}}((I_{\pi},J_{\pi}))\mid f_{\pi}(e_{(I,J)})=+1\} \tag{38}\] and \[O_{\pi}^{-}\coloneqq\{(I,J)\in O_{S_{n}}((I_{\pi},J_{\pi}))\mid f_{\pi}(e_{(I,J)})=-1\} \tag{39}\] We claim the following result. **Theorem 6.14**.: \(O_{\pi}^{+}\) _and \(O_{\pi}^{-}\) are the two \(A_{n}\) orbits that \(O_{S_{n}}((I_{\pi},J_{\pi}))\) splits into._ Proof.: It is enough to show that if \((I,J)\in O_{\pi}^{+}\), then \(\sigma(I,J)\in O_{\pi}^{+}\) for all \(\sigma\in A_{n}\), and if \((I,J)\in O_{\pi}^{-}\), then \(\sigma(I,J)\in O_{\pi}^{-}\) for all \(\sigma\in A_{n}\), where the action of \(\sigma\) on the pair \((I,J)\) is given in (16). Indeed, by Proposition 6.12, we have that \[f_{\pi}(e_{\sigma(I,J)})=f_{\pi}(\rho_{l+k}(\sigma)[e_{(I,J)}])=f_{\pi}(e_{(I,J)}) \tag{40}\] Applying Theorem 6.13 gives the result. Relabelling \(O_{\pi}^{+}\) as \(O_{A_{n}}((I_{\pi}^{+},J_{\pi}^{+}))\), and \(O_{\pi}^{-}\) as \(O_{A_{n}}((I_{\pi}^{-},J_{\pi}^{-}))\), we obtain the two basis elements of \(\operatorname{Hom}_{A_{n}}((\mathbb{R}^{n})^{\otimes k},(\mathbb{R}^{n})^{ \otimes l})\) from the one set partition \(\pi\in\Pi_{l+k,n}\) that has either \(n-1\) or \(n\) blocks, namely \[X_{\pi}^{+}\coloneqq\sum_{(I,J)\in O_{A_{n}}((I_{\pi}^{+},J_{\pi}^{+}))}E_{I,J} \tag{41}\] and \[X_{\pi}^{-}\coloneqq\sum_{(I,J)\in O_{A_{n}}((I_{\pi}^{-},J_{\pi}^{-}))}E_{I,J} \tag{42}\] We summarise the above results into the following theorem. **Theorem 6.15**.: _For \(l,k\in\mathbb{Z}_{\geq 0},n\in\mathbb{Z}_{\geq 1}\), the union of the two sets_ \[\{X_{\pi}\mid\pi\in\Pi_{l+k,n-2}\} \tag{43}\] \[\{X_{\pi}^{+},X_{\pi}^{-}\mid\pi\in\Pi_{l+k,n}\setminus\Pi_{l+k,n-2}\} \tag{44}\] _forms a basis of \(\operatorname{Hom}_{A_{n}}((\mathbb{R}^{n})^{\otimes k},(\mathbb{R}^{n})^{ \otimes l})\). Its dimension is given in Theorem 6.3._ ## 7 Adding Features and Biases ### Features We have assumed throughout that the feature dimension for all of the layers appearing in the neural network is one. We can adapt all of the results that have been shown for the case where the feature dimension of the layers is greater than one. Suppose that an \(r\)-order tensor has a feature space of dimension \(d_{r}\). We now wish to find a basis for \[\operatorname{Hom}_{A_{n}}((\mathbb{R}^{n})^{\otimes k}\otimes\mathbb{R}^{d_{k} },(\mathbb{R}^{n})^{\otimes l}\otimes\mathbb{R}^{d_{l}}) \tag{45}\] in the standard basis of \(\mathbb{R}^{n}\). Such a basis can be found by making the following substitutions, where now \(i\in[d_{l}],j\in[d_{k}]\): * replace \(E_{I,J}\) by \(E_{I,i,J,j}\) in (20), (41), and (42) * relabel \(X_{\pi}\) by \(X_{\pi,i,j}\), \(X_{\pi}^{+}\) by \(X_{\pi,i,j}^{+}\), and \(X_{\pi}^{-}\) by \(X_{\pi,i,j}^{-}\). Consequently, a basis for (45) in the standard basis of \(\mathbb{R}^{n}\) is given by the union of the two sets \[\{X_{\pi,i,j}\mid\pi\in\Pi_{l+k,n-2},i\in[d_{l}],j\in[d_{k}]\} \tag{46}\] \[\left\{X_{\pi,i,j}^{+},X_{\pi,i,j}^{-}\ \middle|\ \begin{array}{l}\pi\in\Pi_{l+k,n} \setminus\Pi_{l+k,n-2},\\ i\in[d_{l}],j\in[d_{k}]\end{array}\right.\right\} \tag{47}\] ### Biases Including bias terms in the layer functions of a \(A_{n}\)-equivariant neural network is harder, but it can be done. For the learnable linear layers of the form \(\operatorname{Hom}_{A_{n}}((\mathbb{R}^{n})^{\otimes k},(\mathbb{R}^{n})^{ \otimes l})\), Pearce-Crump (2022a) shows that the \(A_{n}\)-equivariance of the bias function, \(\beta:((\mathbb{R}^{n})^{\otimes k},\rho_{k})\to((\mathbb{R}^{n})^{\otimes l}, \rho_{l})\), needs to satisfy \[c=\rho_{l}(g)c \tag{48}\] for all \(g\in A_{n}\) and \(c\in(\mathbb{R}^{n})^{\otimes l}\). Since any \(c\in(\mathbb{R}^{n})^{\otimes l}\) satisfying (48) can be viewed as an element of \(\operatorname{Hom}_{A_{n}}(\mathbb{R},(\mathbb{R}^{n})^{\otimes l})\), to find the matrix form of \(c\), all we need to do is to find a basis for \(\operatorname{Hom}_{A_{n}}(\mathbb{R},(\mathbb{R}^{n})^{\otimes l})\). But this is simply a matter of applying Theorem 6.15, setting \(k=0\). ## 8 Equivariance to Local Symmetries We can extend our results to looking at linear layer functions that are equivariant to a direct product of alternating groups; that is, we can construct neural networks that are equivariant to local symmetries. Specifically, we wish to find a basis for \[\operatorname{Hom}_{A_{n_{1}}\times\cdots\times A_{n_{p}}}(V,W) \tag{49}\] where \[V\coloneqq(\mathbb{R}^{n_{1}})^{\otimes k_{1}}\boxtimes\cdots\boxtimes( \mathbb{R}^{n_{p}})^{\otimes k_{p}} \tag{50}\] \[W\coloneqq(\mathbb{R}^{n_{1}})^{\otimes l_{1}}\boxtimes\cdots\boxtimes( \mathbb{R}^{n_{p}})^{\otimes l_{p}} \tag{51}\] and \(\boxtimes\) is the external tensor product. The \(\operatorname{Hom}\)-space given in (49) is isomorphic to \[\bigotimes_{r=1}^{p}\operatorname{Hom}_{A_{n_{r}}}((\mathbb{R}^{n_{r}})^{ \otimes k_{r}},(\mathbb{R}^{n_{r}})^{\otimes l_{r}}) \tag{52}\] As Theorem 6.15 gives a basis for each individual \(\operatorname{Hom}\)-space in (52), we can obtain a basis for the overall \(\operatorname{Hom}\)-space (49) by forming all possible \(p\)-length Kronecker products of basis elements in the standard way for tensor product spaces. ## 9 Related Work The theory for the alternating group has its roots in the theory for the symmetric group and its links to the partition algebra. Jones (1994) constructed a surjective algebra homomorphism between the partition algebra \(P_{k}(n)\) and the centraliser algebra of the symmetric group, \(\operatorname{End}_{S_{n}}((\mathbb{R}^{n})^{\otimes k})\). Most notably, Benkart and Halverson went on to develop much of the theory for the duality between the symmetric group and the partition algebra in a number of important papers (2017, 2019a, 2019b). Bloss (2005) used the result of Jones (1994) to study the centralizer algebra of the alternating group, \(\operatorname{End}_{A_{n}}((\mathbb{R}^{n})^{\otimes k})\). He showed that the partition algebra \(P_{k}(n)\), which has a basis consisting of set partition diagrams having two rows of \(k\) vertices, is isomorphic to the centralizer algebra when \(n\geq 2k+2\). He also highlighted the difficulty of finding a diagrammatic approach for characterising \(\operatorname{End}_{A_{n}}((\mathbb{R}^{n})^{\otimes k})\) in the remaining cases since he recognised that the \(S_{n}\) orbits that correspond bijectively with the set partition diagrams split in these cases. Comes (2020) solved this problem and extended it to all \(\operatorname{Hom}\)-spaces \(\operatorname{Hom}_{A_{n}}((\mathbb{R}^{n})^{\otimes k},(\mathbb{R}^{n})^{ \otimes l})\), developing much of the theory in the process. In particular, he came up with the idea of using the determinant map to show how the \(S_{n}\) orbits split, and introduced jellyfish to represent this map in its diagrammatic form. Finding the form of neural networks that are equivariant to a particular group has become an important area of research. Zaheer et al. (2017) introduced the first permutation equivariant neural network, called Deep Sets, for learning from sets in a permutation equivariant manner. Maron et al. (2019) were the first to study the problem of classifying all of the linear permutation equivariant and invariant neural network layers, with their motivation coming from learning relations between the nodes of graphs. They characterised all of the learnable, linear, permutation equivariant layer functions in \(\operatorname{Hom}_{S_{n}}((\mathbb{R}^{n})^{\otimes k},(\mathbb{R}^{n})^{ \otimes l})\) in the practical cases (specifically, when \(n\geq k+l\)). They used some equalities involving Kronecker products to find a number of fixed point equations which they solved to find a basis, in tensor form, for the layer functions under consideration. As discussed in the Introduction, the approach taken in this paper to characterise all of the learnable, linear, equivariant layer functions in \(\operatorname{Hom}_{A_{n}}((\mathbb{R}^{n})^{\otimes k},(\mathbb{R}^{n})^{ \otimes l})\) is similar to the one seen in the papers written by Pearce-Crump (2022a, 2022b). They used various sets of set partition diagrams to characterise all of the learnable, linear, equivariant layer functions in \(\operatorname{Hom}_{G}((\mathbb{R}^{n})^{\otimes k},(\mathbb{R}^{n})^{ \otimes l})\) when \(G\) is any of the following groups: the symmetric group \(S_{n}\), the orthogonal group \(O(n)\), the symplectic group \(Sp(n)\), and the special orthogonal group \(SO(n)\). ## 10 Conclusion We are the first to show how the combinatorics underlying set partition diagrams, together with some jellyfish representing the determinant map, provides the theoretical background for constructing neural networks that are equivariant to the alternating group when the layers are some tensor power of \(\mathbb{R}^{n}\). We looked at the problem of calculating the form of the learnable, linear, \(A_{n}\)-equivariant layer functions between such tensor power spaces in the standard basis of \(\mathbb{R}^{n}\). We achieved this by finding a basis for the \(\operatorname{Hom}\)-spaces in which these layer functions live. In particular, we showed how set partition diagrams correspond to a number of basis elements, and we used jellyfish to identify the individual basis elements when a set partition diagram corresponded to more than one basis element. In doing so, we calculated the number of weights that appear in these layer functions. We also generalised our approach to show how to construct neural networks that are equivariant to local symmetries. ## Acknowledgements The author would like to thank his PhD supervisor Professor William J. Knottenbelt for being generous with his time throughout the author's period of research prior to the publication of this paper. This work was funded by the Doctoral Scholarship for Applied Research which was awarded to the author under Imperial College London's Department of Computing Applied Research scheme. This work will form part of the author's PhD thesis at Imperial College London.
2304.03096
Spectral Gap Regularization of Neural Networks
We introduce Fiedler regularization, a novel approach for regularizing neural networks that utilizes spectral/graphical information. Existing regularization methods often focus on penalizing weights in a global/uniform manner that ignores the connectivity structure of the neural network. We propose to use the Fiedler value of the neural network's underlying graph as a tool for regularization. We provide theoretical motivation for this approach via spectral graph theory. We demonstrate several useful properties of the Fiedler value that make it useful as a regularization tool. We provide an approximate, variational approach for faster computation during training. We provide an alternative formulation of this framework in the form of a structurally weighted $\text{L}_1$ penalty, thus linking our approach to sparsity induction. We provide uniform generalization error bounds for Fiedler regularization via a Rademacher complexity analysis. We performed experiments on datasets that compare Fiedler regularization with classical regularization methods such as dropout and weight decay. Results demonstrate the efficacy of Fiedler regularization. This is a journal extension of the conference paper by Tam and Dunson (2020).
Edric Tam, David Dunson
2023-04-06T14:23:40Z
http://arxiv.org/abs/2304.03096v1
# Spectral Gap Regularization of Neural Networks ###### Abstract We introduce Fiedler regularization, a novel approach for regularizing neural networks that utilizes spectral/graphical information. Existing regularization methods often focus on penalizing weights in a global/uniform manner that ignores the connectivity structure of the neural network. We propose to use the Fiedler value of the neural network's underlying graph as a tool for regularization. We provide theoretical motivation for this approach via spectral graph theory. We demonstrate several useful properties of the Fiedler value that make it useful as a regularization tool. We provide an approximate, variational approach for faster computation during training. We provide an alternative formulation of this framework in the form of a structurally weighted L\({}_{1}\) penalty, thus linking our approach to sparsity induction. We provide uniform generalization error bounds for Fiedler regularization via a Rademacher complexity analysis. We performed experiments on datasets that compare Fiedler regularization with classical regularization methods such as dropout and weight decay. Results demonstrate the efficacy of Fiedler regularization. This is a journal extension of the conference paper by Tam and Dunson (2020). Spectral Gap Regularization of Neural Networks Spectral Gap Regularization of Neural Networks ## 1 Introduction Neural networks (NNs) are important tools with many applications in various machine learning domains such as computer vision, natural language processing and reinforcement learning. NNs have been very effective in settings where large labeled datasets are available. Empirical and theoretical evidence has pointed to the ever-increasing capacity of recent NN models, both in depth and width, as an important contributor to their modeling flexibility and success. To ameliorate any potential overfitting that comes with these flexible models, a wide range of techniques for regularizing NNs have been developed. These techniques often regularize the network from a global/uniform perspective, e.g. weight decay (Krogh and Hertz, 1992), L\({}_{1}\)/L\({}_{1}\) penalization of weights, dropping nodes/weights in a Bernoulli manner with uniform probability across units/layers (Hinton et al., 2012; Srivastava et al., 2014; Wan et al., 2013), or stopping training early. These commonly used approaches ignore the NN's underlying graphical structure, which can provide valuable connectivity information for regularization. Existing feedforward NN architectures, e.g. multi-layer perceptrons, frequently employ fully connected layers that lead to many redundant paths between nodes of the network. These redundant connections can contribute to over-fitting through the phenomenon of co-adaptation, where weights become dependent on one another, leading to highly correlated behavior amongst different hidden units (Hinton et al., 2012). Empirical work has shown that dropping weights and nodes randomly during training can significantly improve test performance by reducing co-adaptation (Hinton et al., 2012; Srivastava et al., 2014; Wan et al., 2013). One natural alternative to these approaches is to take the graph structure of the NN into consideration during regularization. In this work, we would like to regularize the NN through reducing co-adaptation and penalizing extraneous connections in a way that respects the NN's graphical/connectivity structure. We introduce Fiedler regularization, borrowing from advances in spectral graph theory (Godsil and Royle, 2013; Chung, 1997; Spielman, 2019). The Fiedler value of a connected graph, denoted \(\lambda_{2}\), also known as the algebraic connectivity, is the second smallest eigenvalue of the graph's Laplacian matrix. The magnitude of \(\lambda_{2}\) characterizes how well connected a graph is: if the Fiedler value is small, then the graph is close to disconnected. By adding the Fiedler value as a penalty term to the loss function during training, we can penalize the connectedness of the NN and reduce co-adaptation while taking into account the graph's connectivity structure. We also exploit several useful characteristics of the Fiedler value. We show that the Fiedler value is a concave function on the sizes of the NN's weights. This allows us to draw connections to the literature on folded-concave penalties in variable selection, which are widely adopted in statistics to reduce bias in the penalized regression setting. We additionally show that the Fiedler value's gradient with respect to the network's weights admits a closed form expression, which gives insight into the behavior of Fiedler regularization. In practice, for larger networks, to speed up computation, we propose a variational approach, which replaces the original Fiedler value penalty term by a quadratic form of the graph Laplacian. When used together with the so called Laplacian test vectors, such a Laplacian quadratic form provides a sharp upper bound of the Fiedler value. This variational approximation allows for substantial speedups during training. We give an alternative but equivalent formulation of the variational penalty in terms of a structurally weighted L\({}_{1}\) penalization, where the weights depend on the (approximate) second eigenvector of the graph Laplacian. This L\({}_{1}\) formulation allows us to link Fiedler regularization to sparsity induction, similar to the parallel literature in statistics (Tibshirani, 1996; Zou, 2006). To provide theoretical guarantees of such an approach, we characterize how Fiedler regularization reduces the Rademacher complexity of neural networks. This leads to uniform risk upper bounds for our approach, which sheds light on generalization performance. There has been prior work on using the Laplacian structure of the input data to regularize NNs (Kipf and Welling, 2016; Jiang and Lin, 2018; Zeng et al., 2019). There has also been recent work on understanding regularization on NNs in Bayesian settings (Vladimirova et al., 2018; Polson and Rockova, 2018). These approaches do not consider the graphical connectivity structure of the underlying NN. One of the main conceptual contribution of this work is to use the graphical/connectivity structure of a model to regularize itself. Af ter the publication of the conference version of this article, several related directions of research have been pursued. (Carmichael, 2021) adopted a similar folded concave Laplacian spectral (FCLS) penalty in the block sparsity estimation setting in statistics. (Arbel et al., 2021) adopted a related Fiedler prior in the Bayesian block-diagonal graphical models setting. In related Laplacian regularization problems considered in (Tuck et al., 2019) and (Carmichael, 2021), majorization-minimization procedures are proposed to optimize the Laplacian regularization term. However, in the context of neural networks, majorization-minimization is not a computationally feasible method for optimization, in part due to the deep and high-dimensional nature of the model as well as the highly non-convex nature of the loss function. The main contributions of this work include: (1) to the authors' best knowledge, this is the first application of spectral graph theory and Fiedler values in regularization of NNs via their own underlying graphical/connectivity structures. (2) We give practical and fast approaches for Fiedler regularization, along with strong theoretical guarantees and experimental performances. This is a journal extension of the conference paper (Tam and Dunson, 2020). The journal version extends the conference paper by providing new generalization error guarantees via a Rademacher complexity analysis as well as a new connection to the variable selection literature via the folded-concave penalty interpretation. ## 2 Spectral Graph Theory ### Setup and Background Let \(W\) denote the set of weights of a feedforward NN \(\mathbf{f}\). We denote \(\mathbf{f}\)'s underlying graph structure as \(G\). We would like to use structural information from \(G\) to regularize \(\mathbf{f}\) during training. Feedforward NNs do not allow for self-loops or recurrent connections, hence it suffices that \(G\) be a finite, connected, simple, weighted and undirected graph in this setting. Such a graph \(G\) can be fully specified by a triplet \((V,E,|W|)\). Here the vertex set \(V\) of \(G\) corresponds to all the units (including units in the input and output layers) in the NN \(\mathbf{f}\), while the edge set \(E\) of \(G\) corresponds to all the edges in \(\mathbf{f}\). For our purposes of regularization, \(G\) is restricted to have non-negative weights \(|W|\), which are taken to be the absolute value of the corresponding weights \(W\) in the NN \(\mathbf{f}\). Throughout the paper we use \(n\) to denote the number of vertices in \(G\). \(|W|\) and \(E\) can be jointly represented by an \(n\times n\) weighted adjacency matrix \(|\mathbf{W}|\), where \(|\mathbf{W}|_{ij}\) is the weight on the edge \((i,j)\) if vertices \(i\) and \(j\) are connected, and \(0\) otherwise. The degree matrix \(\mathbf{D}\) of the graph is a \(n\times n\) diagonal matrix, where \(\mathbf{D}_{ii}=\sum_{j=1}^{n}|\mathbf{W}|_{ij}\). The Laplacian matrix \(\mathbf{L}\), which is a central object of study in spectral graph theory, is defined as the difference between the degree and the adjacency matrix, i.e. \(\mathbf{L}=\mathbf{D}-|\mathbf{W}|\). In certain contexts where we would like to emphasize the dependency of \(\mathbf{L}\) on the particular graph \(G\) or the weights \(|\mathbf{W}|\), we adopt the notation \(\mathbf{L}_{G}\) or \(\mathbf{L}_{|\mathbf{W}|}\). We use \([M]\) to denote the set \(\{1,2,\cdots,M\}\) for positive integer \(M\). Throughout the paper, eigenvalues are real-valued since the matrices under consideration are symmetric. We adopt the convention where all eigenvectors are taken to be unit vectors. We order the eigenvalues in ascending order, so \(\lambda_{i}\leq\lambda_{j}\) for \(i<j\). When we want to emphasize \(\lambda_{i}\) as a function of the weights, we use \(\lambda_{i}(|\mathbf{W}|)\). We use \(\mathbf{v}_{i}\) to denote the corresponding eigenvector for \(\lambda_{i}\). We use \(n(S)\) to denote the cardinality of a given set \(S\). ### Graph Laplacian The Laplacian matrix encodes much information about the structure of a graph. Laplacian eigenvalues and eigenvectors are widely used in tasks such as spectral clustering Von Luxburg (2007); Ng et al. (2001) and manifold learning Belkin and Niyogi (2003), precisely because they capture valuable graph connectivity information. One particularly useful characterization of the graph Laplacian that we use heavily is the so called Laplacian quadratic form (Batson et al., 2012; Spielman, 2019; Chung, 1997), defined below. [Laplacian quadratic form] Given a graph \(G=(V,E,|W|)\) with Laplacian matrix \(\mathbf{L}_{G}\), define its Laplacian quadratic form \(Q_{G}:\mathbb{R}^{|V|}\rightarrow\mathbb{R}^{+}\) as \[Q_{G}(\boldsymbol{z}):=\boldsymbol{z}^{T}\mathbf{L}_{G}\boldsymbol{z}=\sum_{ (i,j)\in E}|\mathbf{W}|_{ij}(\boldsymbol{z}(i)-\boldsymbol{z}(j))^{2},\] where \(\boldsymbol{z}(k)\) denotes the \(k^{\text{th}}\) entry of the vector \(\boldsymbol{z}\in\mathbb{R}^{|V|}\). The Laplacian quadratic form demonstrates how a graph's boundary information can be recovered from its Laplacian matrix. One can think of \(\mathbf{z}\) as a mapping that assigns to each vertex a value. If we denote the characteristic vector of a subset of vertices \(S\subset V\) as \(\mathbf{1}_{S}\), i.e. \(\mathbf{1}_{S}(i)=1\) if \(i\in S\) and \(\mathbf{1}_{S}(i)=0\) otherwise, and apply it to the Laplacian quadratic form, we obtain \(\mathbf{1}_{S}^{T}\mathbf{L}_{G}\mathbf{1}_{S}=\sum_{(i,j)\in E,i\in S,j \not\in S}|\mathbf{W}|_{ij}\). This expression characterizes the size of the graph cut \((S,V-S)\), which is the sum of the weights of edges crossing the boundary between \(S\) and \(V-S\). The size of any graph cut can therefore be obtained by application of the corresponding characteristic vector on the Laplacian quadratic form. ### Edge Expansion and Cheeger's Inequality The above discussion on the sizes of graph cuts is highly related to our study of regularizing a NN. Reducing the sizes of graph cuts in a NN would imply reducing the NN's connectivity and potential co-adaptation. A related but more convenient construct that captures this notion of boundary sizes in a graph is the graph's edge expansion (also known as the Cheeger constant or the isoperimetric constant), which can be informally thought of as the smallest "surface-area-to-volume ratio" achieved by a subset of vertices not exceeding half of the graph. [Edge expansion of a graph] The edge expansion \(\phi_{G}\) of a graph \(G=(V,E,|W|)\) is defined as \[\phi_{G}=\min_{S\subset V,n(S)\leq\frac{n(V)}{2}}\frac{\sum_{i\in S,j\not\in S }|\mathbf{W}|_{ij}}{n(S)},\] where \(n(S)\) denotes the number of vertices in \(S\). Observe that the term in the numerator characterizes the size of the graph cut \((S,V-S)\), while the denominator normalizes the expression by the number of vertices in \(S\). The edge expansion is then taken to be the smallest such ratio achieved by a set of vertices \(S\) that has cardinality at most half that of \(V\). One can think of the edge expansion of a graph as characterizing the connectivity bottleneck of a graph. It is highly related to how sparse the graph is and whether there exist nice planar embeddings of the graph (Hall, 1970). We would like to control the edge expansion of the NN's underlying graph for regularization. It is well known that direct computation of the edge expansion is a hard problem Garey et al. (1974) due to the combinatorial structure. Instead, we control the edge expansion indirectly through the Fiedler value \(\lambda_{2}\), the second smallest eigenvalue of the graph's Laplacian \(\mathbf{L}_{G}\). \(\lambda_{2}\) is related to the edge expansion of the graph through Cheeger's inequality (Spielman, 2019; Chung, 1997; Godsil and Royle, 2013). **Proposition 2.3.2** (Cheeger's inequality): _Given a graph \(G=(V,E,|W|)\), the edge expansion \(\phi_{G}\) is upper and lower bounded as follows:_ \[\sqrt{2d_{\max}(G)\lambda_{2}}\geq\phi_{G}\geq\frac{\lambda_{2}}{2},\] _where \(d_{\max}(G)\) is the maximum (weighted) degree of vertices in \(G\) and \(\lambda_{2}\), the Fiedler value, is the second smallest eigenvalue of \(G\)'s Laplacian matrix._ Cheeger's inequality originally arose from the study of Riemannian manifolds and was later extended to graphs. There are many versions of Cheeger's inequality depending on the types of graphs and normalizations used. The proofs can be found in many references, including Spielman (2019); Chung (1997); Godsil and Royle (2013). These types of Cheeger's inequalities are generally tight asymptotically up to constant factors. The Fiedler value is also known as the algebraic connectivity because it encodes considerable information about the connectedness of a graph. Cheeger's inequality allows sharp control over the edge expansion of \(G\) via the Fiedler value. By making the Fiedler value small, we can force the edge expansion of the graph to be small, thus reducing the con Figure 1: Graphical illustration of graph cut \((S,S^{C})\) on neural networks. A subset of vertices \(S\) are circled in red, and the size of the graph cut \((S,S^{C})\) is the sum of the sizes of the weights of all the edges that intersect the red boundary. Weights are colored by their signs (orange for positive, blue for negative) and their opacity determined by the absolute values. nectedness of the graph and potentially alleviating co-adaptation in the NN setting. On the other hand, a large Fiedler value necessarily implies a large edge expansion. This implies that penalization of the Fiedler value during NN training is a promising regularization strategy to reduce connectivity and thus co-adaptation. ## 3 Fiedler Regularization In this section we introduce Fiedler Regularization of neural networks. We characterize this in a supervised classification setting to illustrate the main ideas, even though the general framework is easily extendable to other settings such as regression and autoencoding. The relevant setup and background is introduced below. ### Supervised Learning: Classification Setup We are given training data \(\{(\mathbf{x}_{i},y_{i})\}_{i=1}^{N}\) assumed to be drawn independently from some joint distribution \(\mathcal{P}\). Here \(i\) indexes the \(N\) data points, \(\mathbf{x}\in\mathbb{R}^{d}\) denotes the \(d\)-dimensional feature vectors, and \(y\) denotes the outcomes, which for simplicity of presentation we assume to take values in a binary space \(\{0,1\}\) (i.e. binary classification). Many of our results can be easily generalized to settings such as multi-class classification and regression with straightforward modifications. We aim to find a mapping \(\mathbf{f}\) that predicts \(y\) through \(\mathbf{f}(\mathbf{x})\) so that the expectation of some pre-specified loss \(\mathbb{E}_{\mathcal{P}}\mathcal{L}(f(\mathbf{x}),y)\) is minimized. Typical choices of the loss function \(\mathcal{L}(\cdot,\cdot)\) for classification include the cross-entropy loss, hinge loss etc, whereas for regression problems the mean squared error is common. The empirical approximation \(\mathbb{E}_{\mathcal{P}_{N}}\mathcal{L}(f(\mathbf{x}),y):=\frac{1}{N}\sum_{i= 1}^{N}\mathcal{L}(f(\mathbf{x_{i}}),y_{i})\) is used as a proxy for the expected loss during training, where \(\mathcal{P}_{N}\) denotes the empirical measure. It is assumed that new observations in the testing set are sampled independently from the same distribution \(\mathcal{P}\) as the training data. We denote the estimator of \(\mathbf{f}\) as \(\mathbf{\hat{f}}\). When we want to emphasize the estimator's dependence on the weights, we use \(\mathbf{\hat{f}_{W}}\). ### Neural Network Setup For Fiedler Regularization, we consider for now only feedforward NNs (see discussion for potential extensions). For feedforward NNs, \(\mathbf{\hat{f}}\) is characterized as a composition of nonlinear functions \(\{\mathbf{g}^{(l)}\}_{l=1}^{\Lambda}\), i.e. \(\mathbf{\hat{f}}=\mathbf{g}^{(\Lambda)}\circ\mathbf{g}^{(\Lambda-1)}\circ \cdots\circ\mathbf{g}^{(1)}(\mathbf{x})\), where \(\Lambda\) is the number of layers in the network. The outputs of the \(l^{\text{th}}\) layer have the form \(\mathbf{h}^{(l)}:=\mathbf{g}^{(l)}(\mathbf{h}^{(l-1)}):=\sigma^{(l)}(\mathbf{W }^{(l)}\mathbf{h}^{(l-1)}+\mathbf{b}^{(l)})\), where \(\sigma^{(l)}\), \(\mathbf{W}^{(l)}\) and \(\mathbf{b}^{(l)}\) are the activation function, weight matrix and bias of the \(l^{\text{th}}\) layer of the NN, respectively. Note that we use \(\mathbf{W}\) to denote the weighted adjacency matrix of the entire neural network encoded as a graph, and \(\mathbf{W}^{(l)}\) to denote the matrix encoding the linear transformation applied at the \(l^{\text{th}}\) layer. In essence, each hidden layer first performs an affine transformation on the previous layer's outputs, followed by an element-wise activation that is generally nonlinear. For additional details, see the excellent review by Fan et al. (2019). ### Penalizing with Fiedler Value Given the motivations from section 2, we would like to penalize the graph connectivity of the NN during training. In the Fiedler regularization approach, we add \(\lambda_{2}\) as a penalty term to the objective. **Definition 3.2.1** (Fiedler Regularization): _During training of the neural network, we optimize the following objective:_ \[\min_{\mathbf{W}}\mathbb{E}_{\mathcal{P}_{N}}\mathcal{L}_{\mathbf{W}}+\delta \lambda_{2}(|\mathbf{W}|),\] _where \(\lambda_{2}(|\mathbf{W}|)\) is the Fiedler value of the NN's underlying graph, \(\mathbf{W}\) is the weight matrix of the NN, \(\delta\) is a tuning parameter, and \(Y\) and \(X\) denote the training labels and training features, respectively._ We remark that the actual NN \(\mathbf{\hat{f}_{W}}\) has weights that can be negative, but the regularization term \(\lambda_{2}(|\mathbf{W}|)\) only depends on the sizes of such weights, which can be thought of as edge capacities of the underlying graph \(G\). Note that one can generalize the penalty by applying a differentiable function \(Q\) to \(\lambda_{2}\). For our discussion below, we focus on the case where no \(Q\) is applied in order to focus the analysis on the Fiedler value. However, incorporating \(Q\) is straightforward, and desirable properties such as having a closed-form gradient can generally be retained. We also note that, without loss of generality, one can consider the biases of the units in the NN as additional weights with constant inputs, so it is straightforward to include consideration of both biases and weights in Fiedler regularization. For our purposes, we consider the main parameters of interest to be the weights of the NN. The choice of the activation function(s), architecture, and hyperparameters such as the learning rate or the tuning factor are all considered to be pre-specified in our study. There is a separate and rich literature devoted to methods for selecting activation functions/architectures/hyperparameters that we do not consider here. It is worth noting that the Fiedler Regularization defined in this section is meant to illustrate the core ideas and motivations in a theoretical and idealized way. In practice, it is computationally intensive to penalize the Fiedler value directly, and for implementation, we refer to the approximate variational approach described in the subsequent section. ### Properties of the Fiedler Value It is instructive to examine some properties of the Fiedler value in order to understand why it is an appropriate tool for regularization. First, one concern is whether using the Fiedler value as a penalty in the objective would complicate the optimization process. The Fiedler value can be viewed as a root of the Laplacian matrix's characteristic polynomial, which in higher dimensions has no closed-form solution and can depend on the network's weights in a convoluted manner. To address this concern, the following proposition shows that the Fiedler penalty is a concave function of the sizes of the NN's weights. This shows that when we add the Fiedler penalty to deep learning objectives, which are typically highly non-convex, we are not adding substantially to the optimization problem's difficulty. **Proposition 3.3.1** (Concavity of Fiedler Value): _The function \(\lambda_{2}(|W|)\) is a concave function of the sizes of the NN's weights \(|W|\)._ _Proof:_ Since the Fiedler value \(\lambda_{2}\) is just the second smallest eigenvalue of the Laplacian, and we know that the first eigenvector of the Laplacian must be constant, we can consider \(\lambda_{2}\)'s Rayleigh-Ritz variational characterization as follows: \[\lambda_{2}(|\mathbf{W}|)=\inf_{||\mathbf{u}||=1,\mathbf{u}^{T}\mathbf{1}=0} \mathbf{u}^{T}\mathbf{Lu}\] \[=\inf_{||\mathbf{u}||=1,\mathbf{u}^{T}\mathbf{1}=0}\sum_{(i,j)\in E}|\mathbf{ W}|_{ij}(\mathbf{u}(i)-\mathbf{u}(j))^{2}\] Note that this is a pointwise infimum of a linear function of \(|\mathbf{W}|_{ij}\). Since linear functions are concave (and convex), and the pointwise infimum preserves concavity, we have that \(\lambda_{2}\) is a concave function of the sizes of the weights. \(\blacksquare\) This is related to Laplacian eigenvalue optimization problems and we refer to Boyd (2006) and Sun et al. (2006) for a more general treatment. An immediate corollary of Proposition 3.3.1 is that the Fiedler value is a folded-concave penalty with respect to the weights \(W\) of the neural network. Typical sparsity-inducing methods with \(\mathrm{L}_{1}\) penalties, such as the least absolute shrinkage and selection operator (LASSO) in statistics (Tibshirani, 1996), can suffer from large biases. Methods with folded-concave penalties, such as the Smoothly Clipped Absolute Deviation (SCAD) (Fan and Li, 2001) penalty and the minimax concave penalty (MCP) (Zhang, 2010), have been shown to reduce the biases of \(\mathrm{L}_{1}\)-based sparsity-inducing methods. This shape of folded-concave penalty functions leads to the property that smaller weights are going to be penalized relatively more than the larger weights. In the case of Fiedler regularization, the weights of neural network that have "low connectivity" are penalized more. We can further understand this phenomenon via analyzing the gradient of the Fiedler value with respect to the neural network's weights. ### Closed-form Expression of Gradient In all except the most simple of cases, optimizing the loss function \(\min_{\mathbf{W}}\mathcal{L}(Y,\mathbf{f}_{\mathbf{W}}(X))\) is a non-convex problem. There are a variety of scalable, stochastic algorithms for practical optimization on such objectives. Virtually all of the widely used methods, such as stochastic gradient descent (SGD) (Ruder, 2016), Adam (Kingma and Ba, 2014), Adagrad (Duchi et al., 2011), RMSProp (Graves, 2013) etc, require computation of the gradient of the objective with respect to the parameters. We provide a closed-form analytical expression of the gradients of a general Laplacian eigenvalue with respect to the entries of the Laplacian matrix. From that, as a straightforward corollary, a closed-form analytical expression of the Fiedler value's gradient is obtained. **Proposition 3.4.1** (Gradient of Laplacian Eigenvalue): _Assuming that the eigenvalues of the Laplacian \(\mathbf{L}\) are not repeated, the gradient of the \(k^{\text{th}}\) smallest eigenvalue \(\lambda_{k}\) with respect to \(\mathbf{L}\)'s \((ij)^{\text{th}}\) entry \(\mathbf{L}_{ij}\) can be analytically expressed as_ \[\frac{d\lambda_{k}}{d\mathbf{L}_{ij}}=\textbf{v}_{k}(i)\times\textbf{v}_{k}(j),\] _where \(\textbf{v}_{k}(i)\) denotes the \(i^{\text{th}}\) entry of the \(k^{\text{th}}\) eigenvector of the Laplacian. We adopt the convention in which all eigenvectors under consideration are unit vectors._ _Proof:_ To compute \(\frac{d\lambda_{k}}{d\textbf{L}_{ij}}\), note that since the Laplacian matrix is symmetric, all eigenvalues are real. By assumption, the eigenvalues are not repeated. Under this situation, there is an existing closed-form formulae (see (Petersen et al., 2008)): \(\textbf{v}_{k}^{T}(\partial\textbf{L})\textbf{v}_{k}=d\lambda_{k}\). Specializing to individual entries, we get \(\frac{d\lambda_{k}}{d\textbf{L}_{ij}}=\textbf{v}_{k}(i)\times\textbf{v}_{k}(j)\). From the above, we can easily obtain an analytical expression for the gradient of the Fiedler value with respect to the weights of the neural network. **Corollary 3.4.2** (Gradient of Fiedler value with respect to weights): _Under the same assumptions of Proposition 3.4.1, as an immediate special case, the gradient of the Fiedler value \(\lambda_{2}\) can be expressed as:_ \[\frac{d\lambda_{2}}{d\textbf{L}_{ij}}=\textbf{v}_{2}(i)\times\textbf{v}_{2}(j)\] _Since \(\textbf{L}_{ij}=-\abs{\textbf{W}}_{ij}\) for \(i\neq j\), this yields the following:_ \[\frac{d\lambda_{2}}{d\abs{\textbf{W}}_{ij}}=-\textbf{v}_{2}(i)\times\textbf{ v}_{2}(j)\] Under the additional assumption that the weights under consideration are non-zero, one can remove the absolute value mapping in the gradient by a simple application of the chain rule. Our assumption that the eigenvalues are not repeated generally holds in the context of NNs. The weights in a NN are usually initialized as independent draws from certain continuous distributions, such as the uniform or the Gaussian. Repeated Laplacian eigenvalues often occur when there are strong symmetries in the graph. Such symmetries are typically broken in the context of NNs since the probability of different weights taking the same non-zero value at initialization or during training is negligible. The reason we develop the above analytical form for the gradient of the Fiedler value is not for direct optimization of real life neural networks: recomputing the second Laplacian eigenvector at every iteration of optimization (e.g. in SGD) would be prohibitively expensive for all but the smallest neural networks. Rather, we use the analytical form of the gradient to shed light on what Fiedler Regularization achieves theoretically. For actual computation, we propose a tight variational approximation in the next section which works well in practice. There is a large literature on spectral clustering that analyzes the interpretation of the entries of the second Laplacian eigenvector. In particular, if vertices \(i\) and \(j\) are poorly connected to each other (i.e. they belong to different "clusters"), then \(\textbf{v}_{2}(i)\times\textbf{v}_{2}(j)\) would be a very small/negative real number. This indicates that the derivative \(\frac{d\lambda_{2}}{d\abs{\textbf{W}}_{ij}}=-\textbf{v}_{2}(i)\times\textbf{v} _{2}(j)\) is larger for vertices \(i\) and \(j\) that are less well connected, which in turn implies that edges/weights between poorly connected vertices gets penalized most under Fiedler regularization. ## 4 Variational, Approximate Approach for Computational Speedup We have given theoretical motivation and outlined the use of the Fiedler value as a tool for NN regularization. However, typical matrix computations for eigenvalues and eigenvectors are of order \(O(n^{3})\), where \(n=|V|\). This can be computationally prohibitive for moderate to large networks. Even though there exist theoretically much more efficient algorithms to approximate eigenvalues/eigenvectors of graph-related matrices, in practice computing the Fiedler value in every iteration of training can prove costly. To circumvent this issue, we propose an approximate, variational approach to speed up the computation to \(O(|E|)\), where \(|E|\) is the number of edges in the graph. This proposed approach can be readily implemented in popular deep learning packages such as Tensorflow and PyTorch. We make the following observations. First, for the purpose of regularizing a NN, we do not need the exact Fiedler value of the Laplacian matrix. A good approximation suffices. Second, there is no need to update our approximate \(\lambda_{2}\) at every iteration during training. We can set a schedule to update our \(\lambda_{2}\) approximation periodically, say once every 100 iterations. Both of these observations allow for substantial speedups in practice. An outline of the pseudo-code for this approximate, variational approach is provided in Algorithm 1. To obtain an approximate Fiedler value, we use a special type of Laplacian quadratic form involving the so called test vectors. We additionally provide a perturbation bound that gives justification for periodically updating the Fiedler value. ### Rayleigh Quotient Characterization of Eigenvalues We can closely upper-bound the Fiedler value via the notion of test vectors (Spielman, 2019), which depends crucially upon the Rayleigh quotient characterization of eigenvalues. **Proposition 4.1.1** (Test Vector Bound): _For any unit vector \(\boldsymbol{u}\) that is perpendicular to the constant vector \(\boldsymbol{1}\), we have:_ \[\lambda_{2}\leq\boldsymbol{u}^{T}\mathbf{L}\boldsymbol{u}\] _Any such unit vector is called a test vector. Equality is achieved when \(\boldsymbol{u}=\boldsymbol{v}_{2}\)._ _Proof:_ The Laplacian matrix of a non-negatively weighted graph is symmetric and positive semidefinite. Thus all eigenvalues are real and non-negative. In particular, the smallest eigenvalue of the Laplacian is 0, with the constant vector being the first eigenvector. For a connected graph, the second smallest eigenvalue, which is the Fiedler value, can thus be variationally characterized via the Courant-Fischer theorem by \(\lambda_{2}=\min_{||\boldsymbol{u}||=1,\boldsymbol{u}^{T}\mathbf{L}=0} \boldsymbol{u}^{T}\mathbf{L}\boldsymbol{u}\). This gives us the desired upper bound. \(\blacksquare\) The above description implies that by appropriately choosing test vectors, we can effectively upper bound the Fiedler value. This in turn implies that during training, instead of penalizing by the exact Fiedler value, we can penalize by the quadratic form upper bound instead. In other words, we would perform the following optimization, \[\min_{\mathbf{W}}\mathcal{L}(Y,\mathbf{\hat{f}_{W}}(X))+\delta\mathbf{u}^{T} \mathbf{L}\boldsymbol{u}\] For a given \(\mathbf{u}\), this speeds up computation of the penalty term considerably to \(O(|E|)\) since \(\mathbf{u}^{T}\mathbf{Lu}=\sum_{(i,j)\in E}\left|\mathbf{W}\right|_{ij}(\mathbf{u }(i)-\mathbf{u}(j))^{2}\). The core question now becomes how to choose appropriate test vectors \(\mathbf{u}\) that are close to \(\mathbf{v}_{2}\). We propose to initialize training with the exact \(\mathbf{v}_{2}\) and recompute/update \(\mathbf{v}_{2}\) only periodically during training. For an iteration in between two exact \(\mathbf{v}_{2}\) updates, the \(\mathbf{v}_{2}\) from the previous update carries over and serves as the test vector for the current iteration. By proposition 4.1.1, this always upper-bounds the true \(\lambda_{2}\). During training, weights of the NN are updated at each iteration. This is equivalent to adding a symmetric matrix \(\mathbf{H}\) to the Laplacian matrix \(\mathbf{L}\), which is also symmetric, at every iteration. We can bound the effect of such a perturbation on the eigenvalues via Weyl's inequality (Horn and Johnson, 2012; Horn et al., 1998). **Proposition 4.1.2** (Weyl's Inequality): _Given a symmetric matrix \(\mathbf{L}\) and a symmetric perturbation matrix \(\mathbf{H}\), both with dimension \(n\times n\), for any \(1\leq i\leq n\), we have:_ \[|\lambda_{i}(\mathbf{L}+\mathbf{H})-\lambda_{i}(\mathbf{L})|\leq||\mathbf{H}|| _{op}\] _where \(||\cdot||_{op}\) denotes the operator norm._ Weyl's inequality is a classic result in matrix analysis, and its proof can be found in the excellent reference (Horn and Johnson, 2012) as a straightforward result of linearity and the Courant-Fischer theorem. As an immediate special case, \(|\lambda_{2}(\mathbf{L}+\mathbf{H})-\lambda_{2}(\mathbf{L})|\leq||\mathbf{H}|| _{op}\). Proposition 4.1.2 tells us that as long as the perturbation \(\mathbf{H}\) is small, the change in Fiedler value caused by the perturbation is also small. In fact, this shows that the map \(\mathbf{L}\rightarrow\lambda_{2}(\mathbf{L})\) is Lipschitz continuous on the space of symmetric matrices. In the context of training NNs, \(\mathbf{H}\) represents the updates to the weights of the network during training. This justifies updating \(\lambda_{2}\) only periodically for the purposes of regularization. It suggests that with a smaller learning rate, \(\mathbf{H}\) would be smaller, and therefore the change to \(\lambda_{2}\) would also be smaller, and updates of the test vectors can be more spaced apart. On the other hand, for larger learning rates we recommend updating test vectors more frequently. ## 5 Weighted-\(\mathbf{L}_{1}\) Formulation and Sparsity We now expand on an equivalent formulation of the variational Fiedler penalty as a weighted \(\mathbf{L}_{1}\) penalty. We note that the Laplacian quadratic form in the variational Fiedler penalty can be written as \(\mathbf{u}^{T}\mathbf{Lu}=\sum_{(i,j)\in E}\left|\mathbf{W}\right|_{ij}( \mathbf{u}(i)-\mathbf{u}(j))^{2}\). This yields the variational objective: \[\min_{\mathbf{W}}\mathcal{L}(Y,\mathbf{\hat{f}_{W}}(X))+\delta\sum_{(i,j)\in E }\left|\mathbf{W}\right|_{ij}(\mathbf{u}(i)-\mathbf{u}(j))^{2}\] We note that both \(\left|\mathbf{W}\right|_{ij}\) and \((\mathbf{u}(i)-\mathbf{u}(j))^{2}\) are non-negative. This is equivalent to performing \(L_{1}\) penalization on \(\mathbf{W}_{ij}\) with weights \((\mathbf{u}(i)-\mathbf{u}(j))^{2}\). There is an immense literature on modified \(L_{1}\) penalties in shallow models (Zou, 2006; Candes et al., 2008). It is well known that optimizing an objective under (weighted) \(L_{1}\) constraints often yields sparse solutions. This thus connects our Fiedler regularization approach with sparsity induction on the weights of the NN. From an optimization perspective, recall that \(\lambda_{2}(|\mathbf{W}|)\) is a concave function of \(|\mathbf{W}|\) and thus a folded concave function of \(\mathbf{W}\). One way to optimize this folded concave function is to substitute it with a majorizing surrogate function, in the spirit of majorization-minimization algorithms. It is easy to see from our test vector bound that the weighted \(\mathrm{L}_{1}\) formulation is indeed a majorizer of \(\lambda_{2}(|\mathbf{W}|)\), lending support to our variational approximation from a separate perspective. Similar ideas are explored in (Carmichael, 2021). In Fiedler regularization, the weights \(|\mathbf{W}|_{ij}\) are scaled by a factor of \((\mathbf{u}(i)-\mathbf{u}(j))^{2}\), where \(\mathbf{u}\) is a test vector that approximates \(\mathbf{v}_{2}\). From the spectral clustering literature (Hagen and Kahng, 1992; Donath and Hoffman, 1972), we understand that \(\mathbf{v}_{2}\) is very useful for approximating the minimum conductance cut of a graph. The usual heuristic is that one sorts entries of \(\mathbf{v}_{2}\) in ascending order, sets a threshold \(t\), and groups all vertices \(i\) having \(\mathbf{v}_{2}>t\) into one cluster and the rest into another cluster. If the threshold \(t\) is chosen optimally, this clustering will be a good approximation to the minimum conductance cut of a graph. As such, the farther apart \(\mathbf{v}_{2}(i)\) and \(\mathbf{v}_{2}(j)\) are (1) the edge between nodes \(i\) and \(j\) (if it exists) is likely "less important" for the connectivity structure of the graph, and (2) the more likely that nodes \(i\) and \(j\) belong to different clusters. This is also connected to spectral drawing of graphs (Spielman, 2019; Hall, 1970), where it can be shown that "nice" planar embeddings/drawings of the graph do not exist if is large. In this sense, Fiedler regularization is forcing the NN to be "more planar" while respecting its connectivity structure. Hence, with Fiedler regularization, the penalization on \(\left|\mathbf{W}\right|_{ij}\) is the strongest when this edge is "less important" for the graph's connectivity structure. This would in theory lead to greater sparsity in edges that have low weights and connect distant vertices belonging to different clusters. Thus, Fiedler regularization sparsifies the NN in a way that respects its connectivity structure. To this end, an alternative guarantee is the ordering property of Laplacian eigenvalues with respect to a sequence of graphs (Godsil and Royle, 2013). **Proposition 5.1** (Laplacian Eigenvalue Ordering): _Given the graph \(G\) with non-negative weights, if we remove an edge \((a,b)\) to obtain \(G\setminus(a,b)\), we have that \(\lambda_{2}(G\setminus(a,b))\leq\lambda_{2}(G)\)._ _Proof:_ The proof is a simple generalization of Godsil and Royle (2013). Pick \(\mathbf{q}_{2}\) and \(\mathbf{r}_{2}\) to be second eigenvectors of \(G\) and \(G\setminus(a,b)\) respectively. By the Laplacian quadratic form characterization of eigenvalues, we have \[\lambda_{2}(G)=\mathbf{q}_{2}^{T}\mathbf{L}_{G}\mathbf{q}_{2}=\sum_{(c,d)\in E }\left|\mathbf{W}\right|_{cd}(\mathbf{q}_{2}(c)-\mathbf{q}_{2}(d))^{2}\] \[\geq[\sum_{(c,d)\in E}\left|\mathbf{W}\right|_{cd}(\mathbf{q}_{2}(c)-\mathbf{ q}_{2}(d))^{2}]-\left|\mathbf{W}\right|_{ab}(\mathbf{q}_{2}(a)-\mathbf{q}_{2}(b))^{2}\] \[=\mathbf{q}_{2}^{T}\mathbf{L}_{G\setminus(a,b)}\mathbf{q}_{2}\geq\mathbf{r}_{ 2}^{T}\mathbf{L}_{G\setminus(a,b)}\mathbf{r}_{2}=\lambda_{2}(G\setminus(a,b))\] where the first inequality follows from the non-negativity of the weights under consideration and the second inequality follows from the Rayleigh-Ritz variational characterization of eigenvalues. \(\blacksquare\) Hence, by sparsifying edges and reducing edge weights, we are in effect reducing the Fiedler value of the NN. The above ordering property is a special case of the more general Laplacian eigenvalue interlacing property, where \(\lambda_{2}(G\setminus(a,b))\) also admits a corresponding lower bound. For a general treatment, see Godsil and Royle (2013). We remark that since Fiedler regularization encourages sparsity, during the training process the NN might become disconnected, rendering \(\lambda_{2}\) to become \(0\). This issue could be easily avoided in practice by dropping one of the disconnected components (e.g. the smaller one) from the Laplacian matrix during training, i.e. remove the Laplacian matrix's rows and columns that correspond to the vertices in the dropped component. ## 6 Error Generalization Bounds The guarantees that we have provided above focus on the approximation and variational aspects of Fiedler Regularization. In this section, we provide some theoretical guarantees on the generalization error of such an approach. In particular, we use the notion of Rademacher complexity (Bartlett and Mendelson, 2002) from statistical learning theory to provide finite-sample, uniform generalization error upper bounds for Fiedler regularization. This yields insights into how Fiedler regularization reduces the expressiveness of the learned NN, thus reducing overfitting and improving generalization performance. We focus on the case of supervised classification. We analyze the Laplacian quadratic form/weighted \(L_{1}\) penalization formulation, which includes the exact Fielder value penalization as a special case when the test vector used is exactly \(\mathbf{v}_{2}\). To the best of our knowledge, this is the first Rademacher complexity analysis for a weighted-\(L_{1}\) penalized neural network. The results here might be of independent interest. ### Rademacher Complexity and Error Bounds One key aspect of characterizing the generalization performance of a class of functions/classifiers is via understanding their expressiveness. The notion of empirical Rademacher complexity provides a useful approach for quantifying the expressiveness of a class of functions. **Definition 6.1** (Rademacher Complexity): _Given a sample of \(N\) points \(\mathbf{z}_{1},\cdots,\mathbf{z}_{N}\) drawn i.i.d. from some probability distribution \(\mathcal{P}\) on a set \(Z\subseteq\mathbb{R}^{d}\), as well as a function class \(\mathcal{H}\) consisting of functions that map from \(Z\) to \(\mathbb{R}\), we define the empirical Rademacher complexity of \(\mathcal{H}\), denoted \(\hat{R}_{N}(\mathcal{H})\), as:_ \[\hat{R}_{N}(\mathcal{H}):=\mathbb{E}_{\mathcal{R}}\bigg{[}\sup_{h\in\mathcal{ H}}\frac{1}{N}\sum_{i=1}^{N}\Omega_{i}h(\mathbf{z}_{i})\Big{|}\{\mathbf{z}_{i} \}_{i=1}^{N}\bigg{]}\] _where \(\Omega_{i}\) are independent and identically distributed random variables drawn from the Rademacher distribution \(\mathcal{R}\) (i.e. the uniform distribution on \(\{-1,1\}\)), and the expectation is taken over the Rademacher random variables \(\Omega_{i}\)._ \(\hat{R}_{N}(\mathcal{H})\) _is a random quantity since it conditions on the sample \(\mathbf{z}_{1},\cdots,\mathbf{z}_{N}\). The expectation of \(\hat{R}_{N}(\mathcal{H})\) under the product measure \(\mathcal{P}^{N}\) is known as the Rademacher complexity of \(\mathcal{H}\), denoted \(R_{N,\mathcal{P}}(\mathcal{H})\). In other words,_ \[R_{N,\mathcal{P}}(\mathcal{H}):=E_{\mathcal{P}^{N}}[\hat{R}_{N}(\mathcal{H})]\] On an intuitive level, the Rademacher complexity of the function class \(\mathcal{H}\) characterizes how "expressive" \(\mathcal{H}\) is, in terms of the ability of \(\mathcal{H}\) to match a random sign pattern (i.e. the Rademacher random variables). The larger the Rademacher complexity, the more expressive the function class, and this generally indicates poorer generalization performance due to overfitting. Note that the expectation in the definition of the Rademacher complexity depends on \(\mathcal{P}\), which in many problems is complicated, high-dimensional and/or unknown. The notion of empirical Rademacher complexity bypasses this issue by conditioning on the sample. The Rademacher complexity is a useful notion in part because it naturally occurs in many bounds of interest in empirical process theory and statistical learning theory. For the case of supervised classification where \(Z=(X,Y)\), one can choose \(\mathcal{H}:=\{(x,y)\mapsto\mathcal{L}(f(x),y):f\in\mathcal{F}\}\), where \(\mathcal{L}\) is a fixed loss function, and \(\mathcal{F}\) is the class of classifiers under consideration. In the case of classification, the function \(\mathcal{L}\) is commonly chosen to be a surrogate loss, such as the hinge loss or the logistic loss. These commonly used loss functions are Lipschitz continuous with Lipschitz constant \(1\). The following theorem is then useful. **Theorem 6.2** (Generalization Bounds via Rademacher Complexity): _Let \(\mathcal{H}:=\{(x,y)\mapsto\mathcal{L}(f(x),y):f\in\mathcal{F}\}\), where \(\mathcal{L}\) is a 1-Lipschitz continuous loss function. Then for any \(\delta\in(0,1)\), with probability at least \(1-\delta\) under the product measure \(\mathcal{P}^{N}\), the following inequality holds:_ \[\sup_{h\in\mathcal{H}}\bigg{[}\frac{1}{N}\sum_{i=1}^{N}h(\mathbf{z}_{i})- \mathbb{E}_{\mathcal{P}}(h(\mathbf{z}))\bigg{]}\leq 2\hat{R}_{N}(\mathcal{H})+O \bigg{(}\sqrt{\frac{\log(1/\delta)}{N}}\bigg{)},\] _where each \(\mathbf{z}_{i}\) is distributed according to \(\mathcal{P}\) independently._ The proof of the above theorem could be found in many sources and textbooks, including Bartlett and Mendelson (2002); Shalev-Shwartz and Ben-David (2014); Bousquet et al. (2003). The above probabilistic bound is uniform and finite-sample. When applied to the learning problem, the quantity \(\mathbb{E}_{\mathcal{P}}(h(\mathbf{z}))\) corresponds to the "true" error whereas the quantity \(\frac{1}{N}\sum_{i=1}^{N}h(\mathbf{z}_{i})\) corresponds to the error obtained on the training set. Thus theorem 6.2 provides a way to control the generalization error, in a uniform, finite-sample and distribution-agnostic way, which is particularly suited to analyzing modern machine learning models. The asymptotic notation \(O(\cdot)\) is used here to hide constant factors that are very small. Explicit forms of the inequality with the constant factors shown are described in the sources cited above. ### Rademacher Complexity Bounds for Neural Networks Armed with the above theorem, our focus turns to upper-bounding the empirical Rademacher complexity \(\hat{R}_{N}(\mathcal{H})\) for feedforward neural networks penalized by Fiedler regularization. This in turn shows us how Fiedler regularization affects generalization error bounds of neural networks. Our strategy is to first upper bound the Rademacher complexity \(\hat{R}_{N}(\mathcal{F})\) of the class of feedforward neural networks classifiers under consideration. We then use the results on \(\hat{R}_{N}(\mathcal{F})\) to derive upper bounds on \(\hat{R}_{N}(\mathcal{H})\) by applying the loss function. To gain intuition to our approach, recall that we operate in the following setting: fix the architecture of a neural network, setting \(\sigma\) to be the activation function and \(\Lambda\) to be the number of layers. Then the feedforward neural network under our consideration would have the following form: \[f(\mathbf{x}):=\mathbf{W}^{(\Lambda)}\sigma(\mathbf{W}^{(\Lambda-1)}(\sigma( \cdots\sigma(\mathbf{W}^{(1)}\mathbf{x})\cdots))) \tag{1}\] where the activation function \(\sigma\) is applied component-wise. Note that biases are absorbed into the inputs \(\mathbf{x}\) without loss of generality. Also note that \(\mathbf{W}^{(\Lambda)}\) denotes that matrix encoding the linear transformation that maps nodes from the \(l-1^{\text{th}}\) layer to nodes in the \(l^{\text{th}}\) layer. To prove Rademacher complexity bounds for neural networks, we first list several useful lemmas. Given the compositional nature of equation 1, the first lemma below helps control the Rademacher complexity of function classes under Lipschitz compositions. **Lemma 6.3** (Talagrand's Contraction Lemma): **(Ledoux and Talagrand, 2013)** _Let \(\phi_{1},\cdots\phi_{N}\) be \(\gamma\)-Lipschitz functions mapping from \(\mathbb{R}\rightarrow\mathbb{R}\) for some \(\gamma>0\). Then_ \[\hat{R}_{N}((\phi_{1},\cdots,\phi_{N})\circ\mathcal{H}):=\mathbb{E}_{\mathcal{ R}}\bigg{[}\sup_{h\in\mathcal{H}}\frac{1}{N}\sum_{i=1}^{N}\Omega_{i}\phi_{i}(h( \mathbf{z}_{i}))\Big{|}\{\mathbf{z}_{i}\}_{i=1}^{N}\bigg{]}\] \[\leq\gamma\mathbb{E}_{\mathcal{R}}\bigg{[}\sup_{h\in\mathcal{H}}\frac{1}{N} \sum_{i=1}^{N}\Omega_{i}h(\mathbf{z}_{i})\Big{|}\{\mathbf{z}_{i}\}_{i=1}^{N} \bigg{]}=\gamma\hat{R}_{N}(\mathcal{H})\] _where the \(\circ\) notation denotes function composition._ In other words, we can use the (empirical) Rademacher complexity of \(\mathcal{H}\) to control its (empirical) Rademacher complexity after an element-wise composition with \(\gamma\)-Lipschitz functions. Talagrand's contraction lemma provides a useful way to analytically control the expressivity of functions/classifiers that exhibit compositional representations. Feedforward NNs naturally admit compositional descriptions, with the original input data undergoing interleaving affine transformations and activations. Virtually all activation functions that are used in practice are Lipschitz continuous, with popular choices such as tanh, ReLU, etc being 1-Lipschitz. Popular operators, most notably the convolutional operator commonly used in computing settings, are also Lipschitz. Talagrand's contraction lemma thus allow us to study broad classes of feedforward neural networks. Linear transformations also form a crucial part of neural networks. The following lemma gives us control over Rademacher complexity of linear transformations under weights with bounded \(L_{1}\) norm. **Lemma 6.4** (Rademacher Complexity of a Linear Class): _Given an i.i.d. sample \(\{\mathbf{x}_{i}\in\mathbb{R}^{d}\}_{i=1}^{N}\) and a function class \(\mathcal{F}^{B}_{linear}:=\{\mathbf{x}\mapsto\langle\mathbf{w},\mathbf{x} \rangle\mid\mathbf{w}\in\mathbb{R}^{d},\ ||\mathbf{w}||_{1}\leq B\}\), suppose that \(||\mathbf{x}_{i}||_{\infty}\leq C\) for all \(\mathbf{x}_{i}\) in the dataset, we have_ \[\hat{R}_{N}(\mathcal{F}^{B}_{linear})\leq BC\sqrt{\frac{2\log(2d)}{N}}\] This is a standard result whose proof is based on a lemma of Massart (2000). A complete proof can be found in many references, for example section 26.2 of Shalev-Shwartz and Ben-David (2014). The assumption of bounded \(\mathrm{L}_{1}\) norm of the weights \(\mathbf{w}\) is appropriate for our context of studying neural network sparsity, and the assumption of uniformly bounded \(\mathrm{L}_{\infty}\) norm on the data points in the dataset is usually going to be satisfied in practice. A small modification of the above lemma would lend itself to the scenario of a weighted \(L_{1}\) scenario that is applicable to the Fiedler regularization setting: **Corollary 6.5** (Rademacher Complexity of a Linear Class under Weighted \(L_{1}\) Constraints): _Given an i.i.d. sample \(\{\mathbf{x}_{i}\in\mathbb{R}^{d}\}_{i=1}^{N}\) and a function class \(\mathcal{F}_{1}:=\{\mathbf{x}\mapsto\langle\mathbf{w},\mathbf{x}\rangle\mid \mathbf{w}\in\mathbb{R}^{d},\ \sum_{i=1}^{d}\mathbf{c}_{i}|\mathbf{w}_{i}|\leq B\}\), where \(\mathbf{c}\geq\mathbf{0}\) is a fixed \(d\)-dimensional weighting vector,_ suppose that \(||{\bf x}_{i}||_{\infty}\leq C\) for all \({\bf x}_{i}\) in the dataset, we have_ \[\hat{R}_{N}({\cal F}_{1})\leq\frac{B}{\min({\bf c})}C\sqrt{\frac{2\log(2d)}{N}}\] _where we use \(\min({\bf c})\) to denote the minimum entry in the vector \({\bf c}\)._ _Proof:_ Note that \(\min({\bf c})\sum_{i=1}^{d}|{\bf w}_{i}|\leq\sum_{i=1}^{d}{\bf c}_{i}|{\bf w}_{ i}|\leq B\). This implies \(||{\bf w}||_{1}\leq\frac{B}{\min({\bf c})}\). Note that this implies \({\cal F}_{1}\subseteq{\cal F}_{linear}^{\frac{B}{\min({\bf c})}}\). Invoking Lemma 6.4, we obtain the desired upper bound \(\hat{R}_{N}({\cal F}_{1})\leq\hat{R}_{N}({\cal F}_{linear}^{\frac{B}{\min({ \bf c})}})\leq\frac{B}{\min({\bf c})}C\sqrt{\frac{2\log(2d)}{N}}\). Recall that by the Langrangian dual formulation in optimization, an \(L_{1}\) penalty added to the objective corresponds to imposing a \(L_{1}\) constraint on the domain on the objective. Analogously, in the case of Fiedler regularization, since a weighted \(L_{1}\) penalty is added to the objective, it is equivalent to imposing a weighted \(L_{1}\) constraint on the weights. We now have the tools to control the Rademacher complexity a neural network layer by layer. Let \(d_{0}=d\) be the dimension of the input data, and \(d_{l}\) be the width of layer \(l\) in the neural network. Let \({\bf c}^{0},{\bf c}^{1},\cdots,{\bf c}^{l-1}\) be non-negative weighting vectors of dimensions \(d_{0},d_{1},\cdots,d_{l-1}\) respectively. Let \(B_{0},B_{1},\cdots,B_{l-1}\) be non-negative constants. Let the base class be \({\cal F}_{1}:=\{{\bf x}\mapsto\langle{\bf w},{\bf x}\rangle\mid{\bf w}\in \mathbb{R}^{d},\ \sum_{i=1}^{d}{\bf c}_{i}^{0}|{\bf w}_{i}|\leq B_{0}\}\). Recursively define \({\cal F}_{l}\) for \(l\) running through \(2\) to \(\Lambda\) as \[{\cal F}_{l}:=\{{\bf x}\mapsto\sum_{i=1}^{d_{l-1}}{\bf w}_{i}\sigma(f_{i}({ \bf x}))\mid f_{i}\in{\cal F}_{l-1},\sum_{i=1}^{d_{l-1}}{\bf c}_{i}^{l-1}|{ \bf w}_{i}|\leq B_{l-1}\}\] Currently, we leave \({\bf c}^{0},{\bf c}^{1},\cdots,{\bf c}^{l-1}\) as generic non-negative weight vectors to derive a general result, and later we choose them to correspond to the case of Fiedler regularization specifically. We can now state our main result: **Theorem 6.6** (Rademacher Complexity Bound for Neural Network under Weighted \(L_{1}\) Penalty): _Let \({\cal F}_{\Lambda}\) denote the class of \(\Lambda\)-layer neural networks with a fixed feedforward architecture and \(\gamma\)-Lipschitz activations applied element-wise, where the weight matrix for the \(l^{\text{th}}\) layer is denoted \({\bf W}^{(l)}\). Assume the input features \(\{{\bf x}_{i}\in\mathbb{R}^{d}\}_{i=1}^{N}\) satisfy \(||{\bf x}_{i}||_{\infty}\leq C\) for all \({\bf x}_{i}\). Also assume that for every layer \(l\), the \({\bf c}^{l-1}\)-weighted \(L_{1}\) norm of every row of \({\bf W}^{(l)}\) is upper bounded by \(B_{l-1}\). Then we have_ \[\hat{R}_{N}({\cal F}_{\Lambda})\leq(2\gamma)^{\Lambda-1}(\prod_{l=1}^{\Lambda} \frac{B_{l-1}}{\min({\bf c}^{l-1})})C\sqrt{\frac{2\log(2d)}{N}}\] _Proof:_ It is easy to see that the rows of the weight matrices \({\bf W}^{(l)}\) corresponds precisely to the weights \({\bf w}\) of the linear transformation applied in \({\cal F}_{l}\). This means that the assumption where each row of \({\bf W}^{(l)}\) has \({\bf c}^{l-1}\)-weighted \(L_{1}\) norm at most \(B_{l-1}\) corresponds exactly to the constraints in \(\mathcal{F}_{l}\). Hence we can proceed with the analysis via the function classes \(\mathcal{F}_{l}\). We first note that \[\hat{R}_{N}(\mathcal{F}_{\Lambda})\leq 2\gamma\frac{B_{\Lambda-1}}{\min(\mathbf{c} ^{\Lambda-1})}\hat{R}_{N}(\mathcal{F}_{\Lambda-1}) \tag{2}\] To see this, use the definition \[\begin{split}&\hat{R}_{N}(\mathcal{F}_{\Lambda})=\mathbb{E}_{ \mathcal{R}}\bigg{[}\sup_{f\in\mathcal{F}_{\Lambda}}\frac{1}{N}\sum_{i=1}^{N} \Omega_{i}f(\mathbf{z}_{i})\Big{|}\{\mathbf{z}_{i}\}_{i=1}^{N}\bigg{]}\\ &=\mathbb{E}_{\mathcal{R}}\bigg{[}\sup_{f_{j}\in\mathcal{F}_{ \Lambda-1},\sum_{j=1}^{d_{\Lambda-1}}\mathbf{c}_{j}^{\Lambda-1}\mathbf{w}_{j} \leq B_{\Lambda-1}}\frac{1}{N}\sum_{i=1}^{N}\Omega_{i}\sum_{j=1}^{d_{\Lambda- 1}}\mathbf{w}_{j}\sigma(f_{j}(\mathbf{z}_{i}))\Big{|}\{\mathbf{z}_{i}\}_{i=1} ^{N}\bigg{]}\\ &=\mathbb{E}_{\mathcal{R}}\bigg{[}\sup_{f_{j}\in\mathcal{F}_{ \Lambda-1},\sum_{j=1}^{d_{\Lambda-1}}\mathbf{c}_{j}^{\Lambda-1}\mathbf{w}_{j} \leq B_{\Lambda-1}}\sum_{j=1}^{d_{\Lambda-1}}\mathbf{w}_{j}\frac{1}{N}\sum_{i =1}^{N}\Omega_{i}\sigma(f_{j}(\mathbf{z}_{i}))\Big{|}\{\mathbf{z}_{i}\}_{i=1} ^{N}\bigg{]}\end{split}\] Apply Cauchy-Schwartz, get: \[\leq\mathbb{E}_{\mathcal{R}}\bigg{[}\sup_{f_{j}\in\mathcal{F}_{\Lambda-1}, \sum_{j=1}^{d_{\Lambda-1}}\mathbf{c}_{j}^{\Lambda-1}\mathbf{w}_{j}\leq B_{ \Lambda-1}}||\mathbf{w}||_{1}\max_{j}\bigg{|}\frac{1}{N}\sum_{i=1}^{N}\Omega_{ i}\sigma(f_{j}(\mathbf{z}_{i}))\bigg{|}\Big{|}\{\mathbf{z}_{i}\}_{i=1}^{N} \bigg{]}\] Using the constraint \(\sum_{j=1}^{d_{\Lambda-1}}\mathbf{c}_{j}^{\Lambda-1}\mathbf{w}_{j}\leq B_{ \Lambda-1}\), which implies \(||\mathbf{w}||_{1}\leq\frac{B_{\Lambda-1}}{\min(\mathbf{c}^{\Lambda-1})}\), we have: \[\leq 2\frac{B_{\Lambda-1}}{\min(\mathbf{c}^{\Lambda-1})}\mathbb{E}_{ \mathcal{R}}\bigg{[}\sup_{f\in\mathcal{F}_{\Lambda-1}}\frac{1}{N}\sum_{i=1}^{ N}\Omega_{i}\sigma(f(\mathbf{z}_{i}))\Big{|}\{\mathbf{z}_{i}\}_{i=1}^{N}\bigg{]}\] Applying lemma 6.3 (Talagrand's contraction lemma), get: \[\leq 2\gamma\frac{B_{\Lambda-1}}{\min(\mathbf{c}^{\Lambda-1})}\mathbb{E}_{ \mathcal{R}}\bigg{[}\sup_{f\in\mathcal{F}_{\Lambda-1}}\frac{1}{N}\sum_{i=1}^{ N}\Omega_{i}f(\mathbf{z}_{i})\Big{|}\{\mathbf{z}_{i}\}_{i=1}^{N}\bigg{]}\] \[=2\gamma\frac{B_{\Lambda-1}}{\min(\mathbf{c}^{\Lambda-1})}\hat{R}_{N}( \mathcal{F}_{\Lambda-1})\] This shows the claim 2. Applying the inequality 2 recursively \(\Lambda-1\) times, we obtain \[\hat{R}_{N}(\mathcal{F}_{\Lambda})\leq 2^{\Lambda-1}\gamma^{\Lambda-1}\left( \prod_{l=2}^{\Lambda}\frac{B_{l-1}}{\min(\mathbf{c}^{l-1})}\right)\hat{R}_{N}( \mathcal{F}_{1})\] Applying corollary 6.5, get: \[\hat{R}_{N}(\mathcal{F}_{\Lambda})\leq 2^{\Lambda-1}\gamma^{\Lambda-1}\left(\prod_{l= 2}^{\Lambda}\frac{B_{l-1}}{\min(\mathbf{c}^{l-1})}\right)\frac{B_{0}}{\min( \mathbf{c}^{0})}C\sqrt{\frac{2\log(2d)}{N}}\] \[=(2\gamma)^{\Lambda-1}\prod_{l=1}^{\Lambda}\frac{B_{l-1}}{\min(\mathbf{c}^{l- 1})}C\sqrt{\frac{2\log(2d)}{N}}\] This shows the desired result. The above result allows us to control the Rademacher complexity of a neural network under a weighted \(L_{1}\) penalty in a layer-wise fashion. In the context of Fiedler regularization, the penalty applied is \(\sum_{(a,b)\in E}(\mathbf{u}(a)-\mathbf{u}(b))^{2}|\mathbf{W}_{ab}|\), where we recall that the \(\mathbf{W}\) without superscript denotes the weighted adjacency of the underlying graph of the entire neural network, and \(\mathbf{u}\) being a fixed test vector (which can be chosen as the second Laplacian eigenvector \(\mathbf{v}_{2}\) for exact results). We can rewrite this in matrix form by defining a \(n\times n\) matrix \(\mathbf{U}\) as \(\mathbf{U}_{ab}=(\mathbf{u}(a)-\mathbf{u}(b))^{2}\). We thus obtain an equivalent expression of the penalty term as \(\sum_{(a,b)\in E}\mathbf{U}_{ab}|\mathbf{W}_{ab}|\). This penalty is separable, and we can split it by layers. Denote the nodes in layer \(l\) by \(V_{l}\) and the edges that connects nodes from \(V_{l-1}\) to \(V_{l}\) as \(E_{l}\). We obtain the equivalent expression for the penalty term \(\sum_{l=1}^{\Lambda}\sum_{(a,b)\in E_{l}}\mathbf{U}_{ab}|\mathbf{W}_{ab}^{(l)}|\). This now has a weighted \(L_{1}\) form that is similar to the layer-wise weighted \(L_{1}\) constraints used in the function classes \(\mathcal{F}_{l}\). Thus, the weighting vectors \(\mathbf{c}^{0},\mathbf{c}^{1},\cdots,\mathbf{c}^{\Lambda-1}\) used in theorem 6.6 above can now be chosen accordingly. Recall that \[\mathcal{F}_{l}:=\{\mathbf{x}\mapsto\sum_{i=1}^{d_{l-1}}\mathbf{w}_{i}\sigma( f_{i}(\mathbf{x}))\ |\ f_{i}\in\mathcal{F}_{l-1},\sum_{i=1}^{d_{l-1}}\mathbf{c}_{i}^{l-1}|\mathbf{ w}_{i}|\leq B_{l-1}\}\] The weights \(\mathbf{w}\) in \(\mathcal{F}_{l}\) map the nodes in \(V_{l-1}\) to a single node in layer \(l\), and corresponds to a row of the matrix \(\mathbf{W}^{(\mathrm{I})}\). Thus one way to select \(\mathbf{c}^{l-1}\) is to pick its \(b^{\mathrm{th}}\) entry, where \(b\) indexes the nodes in \(V_{l-1}\), as the maximum entry inside the \(b^{\mathrm{th}}\) column of \(\mathbf{U}\). Due to the feed-forward nature of the network (without any skip connections), this corresponds to finding the maximum of \(\mathbf{U}\) over the edges that connects node \(b\) in \(V_{l-1}\) to all the nodes in \(V_{l}\), i.e. \(\mathbf{c}^{l-1}(b)=\max_{\{a|(a,b)\in E_{l}\}}\mathbf{U}_{a,b}\). Selecting the max entry along the \(b^{\mathrm{th}}\) column ensures that the resulting function class \(\mathcal{F}_{\Lambda}\) is large enough to include the Fiedler regularized neural network. We then have the following corollary: **Corollary 6.7** (Rademacher Complexity Bound for Fiedler Regularized Neural Network): _Assume the same conditions of Theorem 6.6. In addition, fix a test vector \(\mathbf{u}\) for Fiedler regularization, which specifies a matrix \(\mathbf{U}\). For each \(l\) from \(1\) to \(\Lambda\), select weighting vectors \(\mathbf{c}^{l-1}\) according to \(\mathbf{c}^{l-1}(b)=\max_{\{a|(a,b)\in E_{l}\}}\mathbf{U}_{a,b}\), where \(b\) indexes \(V_{l-1}\). The empirical Rademacher complexity of the resulting function class is upper bounded as follows:_ \[\hat{R}_{N}(\mathcal{F}_{\Lambda})\leq(2\gamma)^{\Lambda-1}(\prod_{l=1}^{\Lambda} \frac{B_{l}}{\min_{\{b\in V_{l-1}\}}(\max_{\{a|(a,b)\in E_{l}\}}\mathbf{U}_{a,b} )})C\sqrt{\frac{2\log(2d)}{N}}\] _Proof:_ Simply set the vectors \(\mathbf{c}^{l-1}\) according to \(\mathbf{c}^{l-1}(b)=\max_{\{a|(a,b)\in E_{l}\}}\mathbf{U}_{a,b}\) and apply Theorem 6.6. \(\blacksquare\) There are more recent results (Golowich et al., 2018) that use a more refined Rademacher analysis to remove the exponential dependency on depth from the \((2\gamma)^{\Lambda-1}\) term. However, building on such results to obtain more refined bounds is a future direction, and does not affect the interpretation/derivations for Fielder regularization, which controls the norm of the weight matrices. The above bound in corollary 6.5 yields insight into how Fiedler regularization works. A larger value for \(\mathbf{U}_{ab}=(\mathbf{u}(a)-\mathbf{u}(b))^{2}\) implies that the edge \((a,b)\) is "less important" for connectivity. Thus the \(\max\) operation \(\max_{\{a|(a,b)\in E_{l}\}}\mathbf{U}_{a,b\}\) can be interpreted as looking for the least important edge that node \(b\) is associated with. The subsequent \(\min_{\{b\in V_{l-1}\}}\) operation finds the node in layer \(l-1\) whose least important edge has the best connectivity. It can be thought of as a way of characterizing the connectivity bottleneck inside a layer in a minimax/worst-case manner. The higher this value, the stronger the penalization, and hence the smaller the Rademacher complexity. We can combine theorem 6.2 and corollary 6.7 to obtain the generalization error bound on a Fiedler regularized neural network. **Corollary 6.8** (Generalization Error Bound for Fiedler Regularized Neural Network): _Let \(\mathcal{H}:=\{(x,y)\mapsto\mathcal{L}(f(x),y):f\in\mathcal{F}_{\Lambda}\}\), where \(\mathcal{L}\) is a 1-Lipschitz continuous loss function. Then for any \(\delta\in(0,1)\), with probability at least \(1-\delta\) under the product measure \(\mathcal{P}^{N}\), the following inequality holds:_ \[\sup_{h\in\mathcal{H}}\Bigg{[}\frac{1}{N}\sum_{i=1}^{N}h(\mathbf{z}_{i})- \mathbb{E}_{\mathcal{P}}(h(\mathbf{z}))\Bigg{]}\] \[\leq 2(2\gamma)^{\Lambda-1}(\prod_{l=1}^{\Lambda}\frac{B_{l}}{\min_{\{b\in V_{ l-1}\}}(\max_{\{a|(a,b)\in E_{l}\}}\mathbf{U}_{a,b})})C\sqrt{\frac{2\log(2d)}{N}}+O \bigg{(}\sqrt{\frac{\log(1/\delta)}{N}}\bigg{)},\] _where each \(\mathbf{z}_{i}\) is distributed according to \(\mathcal{P}\) independently._ _Proof:_ Apply Talagrand's contraction lemma to obtain \(\hat{R}_{N}(\mathcal{H})\leq 1\times\hat{R}_{N}(\mathcal{F}_{\Lambda})\), and then apply theorem 6.2. \(\blacksquare\) ## 7 Supervised Classification: Experiments and Results Deep/multilayer feedforward NNs are useful in many classification problems, ranging from popular image recognition tasks to scientific and biomedical problems such as classifying diseases. We examine the performance of Fiedler regularization on the standard benchmark image classification datasets MNIST and CIFAR10. We also tested Fiedler regularization on the TCGA RNA-Seq PANCAN tumor classification dataset (Weinstein et al., 2013) from the UCI Machine Learning Repository. We compare the performance of several standard regularization approaches for NNs on these datasets, including Dropout, L\({}_{1}\) regularization and weight decay. Extension of such experiments to other classification tasks is straightforward. The purpose of the experiments below is not to use the deepest NNs, the latest architectures or the most optimized hyperparameters. Nor is the purpose to show the supremacy of NNs versus other classification methods like random forests or logistic regression. Rather, we attempt to compare the efficacy of Fiedler regularization against other NN regularization techniques as a proof of concept. Extensions to more complicated and general network architectures are explored in the discussion section. For all our experiments, we consider 5-layer feedforward NNs with ReLU activations and fully connected layers. We used PyTorch 1.4 and Python 3.6 for all experiments. We adopt stochastic gradient descent with a momentum of 0.9 for optimization and a learning rate of 0.001. To select the dropping probability for dropout, as well as the regularization hyperparameter for L\({}_{1}\), Fiedler regularization and weight decay, we performed a very rough grid search on a small validation dataset. The dropout probability is selected to be 0.5 for all layers, and the regularization hyperparameters for L\({}_{1}\), Fiedler regularization and weight decay are 0.001, 0.01 and 0.01 respectively. All models in the experiments were trained under the cross-entropy loss. Each experiment was run 5 times, with the median and the standard deviation of the performances reported. All experiments were run on a Unix machine with an Intel Core i7 processor. The code used for the experiments can be found at the first author's Github repository ([https://github.com/edrictam/FiedlerRegularization](https://github.com/edrictam/FiedlerRegularization)). ### Mnist **Dataset and setup**. MNIST is a standard handwriting recognition dataset that consists of 60,000 \(28\times 28\) training images of individual hand-written digits and \(10,000\) testing images. We picked the hidden layers of our NN to be 500 units wide. We used a batch size of 100 and the networks were trained with 10 epochs. **Results**. The results for MNIST are displayed in Table 1. For the MNIST dataset, we obtained very good accuracies for all the methods, with Fiedler regularization standing out, followed by weight decay and dropout. The high accuracies obtained for the MNIST dataset with feedforward NNs are consistent with results from previous studies (Srivastava et al., 2014). Fiedler regularization showed gains over its competitors. ### Cifar10 **Dataset and setup**. CIFAR10 is a benchmark object recognition dataset that consists of \(32\times 32\times 3\) down-sampled RGB color images of 10 different object classes. There are 50,000 training images and 10,000 test images in the dataset. We picked the hidden layers of our NN to be 500 units wide. We used a batch size of 100 and the networks were trained with 10 epochs. **Results**. The results for CIFAR10 are displayed in Table 2. While this is a more difficult image classification task than MNIST, the ordering of performances among the regularization methods is similar. Fiedler regularization performed the best, followed by dropout, weight decay and L\({}_{1}\) regularization. ### TCGA Cancer Classification **Dataset and setup**. The TCGA Pan-Cancer tumor classification dataset consists of RNA-sequencing as well as cancer classification results for 800 subjects. The input features are 20531-dimensional vectors of gene expression levels, whereas the outputs are tumor classification labels (there are 5 different tumor types under consideration). We used 600 subjects for training and 200 for testing. Due to the highly over-parametrized nature of this classification task, We picked the width of the hidden layers to be narrower, at 50 units. We used a batch size of 10 and the networks were trained with 5 epochs. **Results** The results for the TCGA tumor classification experiment are displayed in Table 3. Fiedler regularization and L\({}_{1}\) had similarly high performances, followed by weight decay. It is interesting that Dropout achieved a relatively low accuracy, slightly better than chance. Since this dataset is relatively small (the testing set has only 200 data points and training set 600), the standard deviation of the accuracies are higher. L\({}_{1}\) and Fiedler regularization, which explicitly induce sparsity, performed the best. \begin{table} \begin{tabular}{l c c} \hline \hline Regularization & Training & Testing \\ \hline L\({}_{1}\) & 90.32 \(\pm\) 0.17 & 90.25\(\pm\) 0.35 \\ Weight Decay & 95.12\(\pm\) 0.06 & 94.98\(\pm\) 0.07 \\ Dropout & 94.52\(\pm\) 0.07 & 94.5\(\pm\) 0.18 \\ Fiedler & 96.54\(\pm\) 0.08 & 96.1\(\pm\) 0.12 \\ \hline \hline \end{tabular} \end{table} Table 1: Classification accuracies for MNIST under various regularization schemes (units in percentages) \begin{table} \begin{tabular}{l c c} \hline \hline Regularization & Training & Testing \\ \hline L\({}_{1}\) & 28.52\(\pm\) 0.9 & 28.88\(\pm\) 1.11 \\ Weight Decay & 52.93 \(\pm\) 0.17 & 50.55\(\pm\) 0.39 \\ Dropout & 46.61\(\pm\) 0.35 & 44.63\(\pm\) 0.39 \\ Fiedler & 57.99 \(\pm\) 0.13 & 52.26\(\pm\) 0.27 \\ \hline \hline \end{tabular} \end{table} Table 2: Classification accuracies for CIFAR10 under various regularization schemes (units in percentages) ### Analysis of Results We note that both MNIST and CIFAR10 have more training samples than the dimension of their features. The results from MNIST and CIFAR10 largely agree with each other and confirm the efficacy of Fiedler regularization. Under this setting, other regularization methods like dropout and weight decay also exhibited decent performance. On the other hand, in the TCGA dataset, where the dimension of the input features (20531) is much higher than the number of training samples (600), L\({}_{1}\) and Fiedler regularization, which explicitly induce sparsity, performed substantially better than dropout and weight decay. An inspection of the TCGA dataset suggests that many of the gene expression levels in the input features are 0 (suggesting non-expression of genes), which likely implies that many of the weights in the network, particularly at the input layer, are not essential. It is thus not surprising that regularization methods that explicitly induce sparsity perform better in these "large p, small n" scenarios, often found in biomedical applications. We remark that Fiedler regularization enjoys practical running speeds that are fast, generally comparable to (but slightly slower than) that of most commonly used regularization schemes such as L\({}_{1}\) and dropout. The running time of Fiedler regularization could likely be improved with certain implementation-level optimizations to speed up the software. Performances would also likely improve if more refined grid searches or more sophisticated tuning parameter selection methods like Bayesian optimization are adopted. ## 8 Discussion The above experiments demonstrated several points of interest. The poorer performance of L\({}_{1}\) regularization in MNIST and CIFAR10 stands in sharp contrast to the much higher performance of Fiedler regularization, a weighted L\({}_{1}\) penalty. It is generally acknowledged that L\({}_{1}\) regularization does not enjoy good empirical performance in deep learning models. The precise reason why this happens is not exactly known. Previous studies have adopted a group-lasso formulation for regularization of deep NNs and have obtained good performance (Scardapane et al., 2017). These results suggest that modifications of L\({}_{1}\) through weighting or other similar schemes can often drastically improve empirical performance. We have tracked the algebraic connectivity of the NNs during the training process in our experiments. In general, without any regularization, the NNs tend to become more connected during training, i.e. their Fiedler value increases. In the Fiedler regularization \begin{table} \begin{tabular}{l c c} \hline \hline Regularization & Training & Testing \\ \hline L\({}_{1}\) & 91.5 \(\pm\) 13.73 & 94.53\(\pm\) 12.46 \\ Weight Decay & 57\(\pm\) 22.42 & 60.2\(\pm\) 20.94 \\ Dropout & 25.33\(\pm\) 5.9 & 23.88\(\pm\) 7.36 \\ Fiedler & 93.33\(\pm\) 20.31 & 90.55\(\pm\) 20.73 \\ \hline \hline \end{tabular} \end{table} Table 3: Classification accuracies for TCGA under various regularization schemes (units in percentages) case, the connectivity is penalized and therefore decreases during training in a very gradual manner. Interestingly, in the L\({}_{1}\) case, the algebraic connectivity of the NN can decrease very quickly during training, often leading to disconnection of the network very early in the training process. This is likely related to L\({}_{1}\) regularization's uniform penalization of all weights. It is therefore difficult to choose the regularization hyperparameter for L\({}_{1}\): if it is too small, sparsity induction might occur too slowly and we would under-regularize; if it is too big, we risk over-penalizing certain weights and lowering the model's accuracy. One advantage of a weighted scheme such as Fiedler penalization thus lies in its ability to adaptively penalize different weights during training. While we only considered relatively simple feedforward, fully connected neural architectures, potential extensions to more sophisticated structures are straightforward. Many convolutional NNs contain fully connected layers after the initial convolutional layers. One could easily extend Fiedler regularization to this case. In the context of ResNets, where there are skip connections, the spectral graph properties we have utilized still hold, and hence Fiedler regularization could be directly applied. In the non-classification setting, autoencoders exhibit very natural graph structures in the form of a bottleneck, and it is an open direction to study graph connectivity based penalizations, such as Fiedler regularization, in that setting. The spectral graph theory setup adopted in this paper generally holds for any undirected graph. An open direction is to establish appropriate spectral graph theory for regularization of directed graphs, which would be useful in training recurrent NNs. While Fiedler regularization leads to sparsely connected NNs in theory, in practice it often takes a higher penalty value or longer training time to achieve sparsity with Fiedler regularization. This might be due in part to the optimization method chosen. It is known that generally SGD does not efficiently induce sparsity in L\({}_{1}\) penalized models, and certain truncated gradient methods (Langford et al., 2009) might prove more effective in this setting. We remark that while Fiedler regularization emphasizes regularizing based on graphical/connectivity structure, global penalization approaches such as Dropout, L2 etc could still prove useful. One could combine the two regularization methodologies to achieve simultaneous regularization. There are many important statistical and machine learning models that can be cast as special cases of shallow neural networks, e.g. factor analysis, linear regression etc. One natural direction of further investigation is to apply Fiedler regularization to these models. There are intimate connections between the graph cut/edge expansion perspective considered above, and the geometric notion of isoperimetry. The Laplacian matrix considered above could be viewed as a discretized analog of the Laplace-Beltrami operator. An open direction is to investigate continuous relaxations of the Fiedler regularization approach. On the generalization error bound analysis, there is an independent line of work (Neyshabur et al., 2017) that utilizes the spectral norm of the neural network's weight matrices to provide margin bounds on the generalization error. Their focus is on utilizing the spectral norms of the weight matrices for the layers, whereas our focus is on leveraging the global structure via the spectrum of the Laplacian of the NN's underlying graph. Lastly, we have adopted a version of spectral graph theory that considers the un-normalized (combinatorial) Laplacian \(\mathbf{L}=\mathbf{D}-|\mathbf{W}|\) as well as the edge expansion of the graph. A similar theory for regularization could be developed for the normalized Laplacian \({\bf L}^{\prime}={\bf I}-{\bf D}^{-\frac{1}{2}}|{\bf W}|{\bf D}^{-\frac{1}{2}}\) and the conductance of the graph, after appropriately accounting for the total scale of the NN. While the combinatorial Laplacian that we considered is related to the notion of RatioCuts, the normalized Laplacian is associated with the notion of NCuts. Both notions could in theory be used for reducing connectivity/co-adaptation of the NN. ## Acknowledgments This research was partially supported by grant R01MH118927 of the National Institutes of Health, as well as funding from SAMSI.
2309.01127
Financial Fraud Detection using Quantum Graph Neural Networks
Financial fraud detection is essential for preventing significant financial losses and maintaining the reputation of financial institutions. However, conventional methods of detecting financial fraud have limited effectiveness, necessitating the need for new approaches to improve detection rates. In this paper, we propose a novel approach for detecting financial fraud using Quantum Graph Neural Networks (QGNNs). QGNNs are a type of neural network that can process graph-structured data and leverage the power of Quantum Computing (QC) to perform computations more efficiently than classical neural networks. Our approach uses Variational Quantum Circuits (VQC) to enhance the performance of the QGNN. In order to evaluate the efficiency of our proposed method, we compared the performance of QGNNs to Classical Graph Neural Networks using a real-world financial fraud detection dataset. The results of our experiments showed that QGNNs achieved an AUC of $0.85$, which outperformed classical GNNs. Our research highlights the potential of QGNNs and suggests that QGNNs are a promising new approach for improving financial fraud detection.
Nouhaila Innan, Abhishek Sawaika, Ashim Dhor, Siddhant Dutta, Sairupa Thota, Husayn Gokal, Nandan Patel, Muhammad Al-Zafar Khan, Ioannis Theodonis, Mohamed Bennai
2023-09-03T09:42:49Z
http://arxiv.org/abs/2309.01127v1
# Financial Fraud Detection using Quantum Graph Neural Networks ###### Abstract Financial fraud detection is essential for preventing significant financial losses and maintaining the reputation of financial institutions. However, conventional methods of detecting financial fraud have limited effectiveness, necessitating the need for new approaches to improve detection rates. In this paper, we propose a novel approach for detecting financial fraud using Quantum Graph Neural Networks (QGNNs). QGNNs are a type of neural network that can process graph-structured data and leverage the power of Quantum Computing (QC) to perform computations more efficiently than classical neural networks. Our approach uses Variational Quantum Circuits (VQC) to enhance the performance of the QGNN. In order to evaluate the efficiency of our proposed method, we compared the performance of QGNNs to Classical Graph Neural Networks using a real-world financial fraud detection dataset. The results of our experiments showed that QGNNs achieved an AUC of 0.85, which outperformed classical GNNs. Our research highlights the potential of QGNNs and suggests that QGNNs are a promising new approach for improving financial fraud detection. _Keywords_: Quantum Machine Learning, Quantum Graph Neural Network, Variational Quantum Circuit, Fraud Detection ## 1 Introduction In today's dynamic technological landscape, the rapid surge in digital transactions and financial activities has ushered in unprecedented conveniences. However, this digital transformation has also fostered a parallel escalation in financial fraud, posing significant threats to global industries and economies. As financial operations increasingly adopt digital complexities, the susceptibility to exploitation from malicious actors increases, leading to the pursuit of innovative fraud detection methods [1]. The importance of fraud detection extends beyond a single industry, resonating across diverse sectors, including Banking, e-Commerce, Healthcare, FinTech, and Insurance. The integrity of financial transactions is pivotal for optimal functionality in these domains, making robust fraud detection systems indispensable. The banking sector, exemplifying the forefront of this challenge, confronts expanding attack surfaces due to rising online and mobile banking adoption [2]. Conventional rule-based approaches, while partially effective, struggle to match the ever-evolving tactics of fraudsters. This necessitates advanced, adaptable techniques in order to keep pace with the dynamic landscape of financial fraud [3]. The research community is constantly exploring new ways to detect fraud, as the methods used by fraudsters become increasingly sophisticated. An emerging avenue combines Quantum Machine Learning (QML), and Graph Neural Networks (GNNs); a groundbreaking approach poised to revolutionise financial fraud detection [4]. By harnessing the distinct attributes of Quantum Computing (QC) -- superposition and entanglement -- and integrating them with the effectiveness of GNNs, this hybrid paradigm endeavours to tackle the intricate and ever-changing realm of financial fraud. In this paper, we investigate the challenges of financial fraud detection and the potential of Quantum Graph Neural Networks (QGNNs) as a transformative approach to address these challenges. We conduct comprehensive analyses and experiments to demonstrate the efficacy and viability of QGNNs for fraud detection. Our findings contribute to the discourse on advanced fraud detection techniques and pave the way for enhanced security in the financial ecosystem. QML emerges at the intersection of QC and conventional Machine Learning (ML) techniques, offering promising avenues for solving complex problems in various domains. In the context of financial fraud detection, QML presents an intriguing approach that harnesses the inherent power of quantum computations to address the intricate challenges posed by fraudulent activities within the financial sector. By leveraging QGNNs, the combination of quantum and graphical techniques offers a novel framework for analysing and classifying financial transactions. In financial fraud detection, QML encodes transactional data into quantum states. This can improve the efficiency and accuracy of fraud detection by enabling efficient parallel processing and enhanced feature representation. The unique property of quantum entanglement facilitates the capture of intricate relationships among transactional features. This fosters a more comprehensive understanding of fraudulent patterns. However, this emerging paradigm also poses significant challenges, including the interpretability of quantum computations and concerns over quantum system security. Nonetheless, the promising outcomes showcased in this study highlight the potential of QML to significantly impact fraud detection by improving accuracy and scalability, opening the door to a new era of enhanced financial security. The inherent ability of quantum systems to process and model complex relationships among variables aligns well with the intricacies of financial transactions. In the realm of fraud detection, conventional methods often struggle to navigate the intricate tapestry of relationships and intricate patterns that underlie fraudulent activities. As the complexity and diversity of fraudulent schemes continue to evolve, the demand for adaptable and nuanced detection techniques becomes increasingly apparent. In response, graph-based methods have emerged as a promising avenue, harnessing the intrinsic strength of graph structures to capture and dissect the multifaceted interconnections that define fraudulent behaviours. Built upon the foundation of the mathematical study of graph theory, these methods provide an intuitive and comprehensive framework to model, depict, and analyse the labyrinthine-like relationships among entities. From individuals and accounts to transactions and organisations, a broad spectrum of entities can be seamlessly encapsulated within interconnected nodes and edges. This unique arrangement empowers graph structures to illustrate the intricate dynamics inherent in fraudulent schemes vividly. Diverging from conventional approaches, which rely on isolated data points and predetermined rules, graph-based methods can unveil concealed connections and dependencies, thereby unveiling anomalous or suspicious behaviours that might go unnoticed [5]. The true effectiveness of graph structures in fraud detection lies in their unparalleled ability to uncover latent patterns that elude customary detection techniques. Fraudulent endeavours rarely occur in isolation; rather, they unravel through intertwined actions involving multiple entities. These connections, often obscured by noise and obfuscation, are revealed through meticulous graph analysis. By representing and exploring these relationships, graph-based methods empower fraud detection systems to transcend the confines of isolated data points, capturing the holistic context in which fraudulent activities manifest and thrive. This quantum potential extends seamlessly to the detection of financial fraud, where quantum-inspired techniques can transform the landscape. By integrating the strengths of quantum mechanics, QC could potentially revolutionise classical ML algorithms used for fraud detection. Techniques such as Quantum Neural Networks (QNNs) can harness the property of quantum parallelism to process and analyse financial data more efficiently. Exploiting superposition, these networks can simultaneously examine multiple data points, accelerating tasks like pattern recognition and data classification, crucial elements in detecting fraudulent activities. Furthermore, quantum feature mapping enhances the ability to identify intricate patterns in financial transactions that might evade classical methods. This intersection of QML and financial fraud detection promises a future where quantum-inspired techniques amplify the accuracy and efficiency of identifying and combating fraudulent behaviours. The integration of quantum properties into graph-based fraud detection methodologies is motivated by the imperative to confront the escalating sophistication of fraudulent activities and the inherent limitations of classical computing paradigms. In today's landscape of intricate financial systems, fraudulent behaviours manifest intricate and interwoven patterns that defy conventional computational approaches. These conventional methods struggle to unravel the complexities inherent in fraud networks, marked by exponential data growth and non-linear dynamics. As a result, a critical need arises for innovative techniques that transcend classical computing boundaries, leading us to explore the distinctive attributes of QC. While graph-based fraud detection methods have shown their ability to capture the intricate relationships within fraudulent activities, they face limitations in handling the explosive data growth and complex dynamics of fraud networks [6]. The conventional algorithms grounded in classical computing struggle to navigate the intricate patterns that define these networks, often characterised by non-linear structures and extensive solution spaces. This disparity underscores a compelling necessity for pioneering methodologies capable of transcending the confines of classical computation. By delving into quantum properties, we seek to bridge this gap, illuminating concealed fraud schemes and redefining the boundaries of fraud detection in the context of modern financial systems [7]. The primary objective of this study is to conduct a comprehensive investigation into the effectiveness of QGNNs for financial fraud detection. Specifically, we aim to comprehensively assess and analyse the potential advantages and enhancements that QGNNs offer in contrast to classical GNNs, specifically concerning their ability to identify and mitigate fraudulent activities within intricate networks of financial transactions. By meticulously evaluating and comparing the performance, adaptability, and overall effectiveness of QGNNs benchmarked against classical GNNs, we intend to shed light on the transformative possibilities of leveraging QC for refining fraud detection methodologies. Through this research endeavour, we aspire to comprehensively understand QGNNs potential to enhance the landscape of fraud detection strategies [8]. By closely examining the strengths and constraints of QGNNs _vis-d-vis_ classical GNNs, our study seeks to contribute meaningful insights to the QC and fraud detection disciplines. The structure of this paper is as follows: * Sec. 2, we present a comprehensive literature review on financial fraud detection, graph neural networks, and QML. We highlight the fundamental concepts of GNNs and emphasise the limitations of conventional methods. * In Sec. 3, we examine the theory of GNNs and different models, focusing on GraphSAGE architecture. * In Sec. 4, we conduct a comprehensive study of our proposed quantum graph neural network model for financial fraud detection. * In Sec. 5, we provide a comprehensive understanding of our selected dataset characteristics, including attribute highlighting, class imbalance, and preprocessing steps. * In Sec. 6, we evaluate the performance of QGNN and GNN on a real-world financial fraud dataset and discuss the results of our experiments. * In Sec. 7, we summarise the key findings of our study and suggest directions for future research. ## 2 Literature Review Transitioning our inquiry from the domain of conventional fraud detection techniques, we direct our attention towards the emerging promise of QGNNs. This transition represents a notable departure from established methodologies and carries the potential to reshape our understanding and implementation of fraud detection strategies. In adopting this advanced technological paradigm, we aim to uncover novel insights and methodologies that may prove instrumental in addressing the complexities of contemporary fraud detection challenges. In the classical computing area, there exists a plethora of noteworthy research. We highlight some of the outstanding application-based research works below. Ma _et al._, 2020 [9] provide an in-depth exploration of using Deep Learning (DL) techniques to detect anomalies in graph data. It emphasises the importance of anomaly detection in domains such as security, finance, and medicine. The paper highlights how conventional methods struggle with graph data complexities, leading to the rise of DL approaches. The authors systematically categorise and analyse contemporary techniques for graph anomaly detection based on their ability to identify different types of anomalous graph objects. The survey underscores the challenges inherent in this field and identifies future research directions. In today's rapidly evolving technological landscape, we are witnessing a growing variety of ways in which fraudulent transactions take place. This makes it crucial to understand how we detect fraud and to determine which approach works best to get accurate results. Researchers are on a widespread quest to explore different QML models that fit well for spotting fraud. In [10], Ahmad _et al._, 2021 explore the combination of QC and Deep Neural Networks (DNNs) to address network security through anomaly detection. Emphasising the transformative potential of QC, it develops a DNN-based quantum autoencoder to process quantum-encoded data. Applying dimensionality reduction techniques, the research enhances the model's ability to detect subtle anomalies within network data. The results reveal impressive accuracy rates of 100% during training and 99% during testing, demonstrating the framework's efficacy in capturing patterns and its potential to revolutionize anomaly detection in network security. This innovative research establishes a symbiotic relationship between QC and DL, offering a novel avenue for cybersecurity advancements. In [11], Zheng _et al._, 2021 introduce a Quantum Graph Convolutional Neural Network (QGCNN) model to address the challenge of applying a QNN to non-Euclidean spatial data, particularly graph-structured data. The QGCNN model efficiently captures graph topology and node features using quantum parametric circuits, making graph-level classification tasks effective. The study bridges the gap in QML research by extending QNNs to handle irregular spatial structures in graph data. The proposed QGCNN model showcases the potential of QC in enhancing graph-based ML tasks, contributing to the advancement of QML research. QGNNs offer a transformative approach to fraud detection in the financial sector, addressing the escalating complexity of fraudulent schemes. By leveraging their capacity for intricate pattern recognition, enhanced data representation, and adaptability to evolving strategies, these networks hold the potential to significantly enhance the accuracy of fraud detection while mitigating false positives. The study by Kyriienko _et al._, 2022 [12] focuses on utilising QML to enhance the detection of internal fraud in the financial sector, particularly fraudulent activities conducted by individuals within an organisation. The study employs quantum kernels generated through quantum feature maps based on Instantaneous Quantum Polynomial (IQP) circuits to transform classical data from credit card transactions into a higher-dimensional space for analysis. Applying the one-class support vector machine (OC-SVM) algorithm within this quantum feature space enables to detection of abnormal transactions. Simulations confirm the effectiveness of this quantum kernel-based approach in detecting internal fraud, highlighting the potential of QC to improve fraud detection accuracy in complex financial data. Recent research efforts, such as [13], Innan _et al._, 2023 investigate the utility of QML models in enhancing fraud detection within the financial sector. The authors address the pressing need for accurate fraud detection and propose leveraging QML techniques to improve system efficiency. Through a comparative analysis of four QML models -- Quantum Support Vector Classifier, Variational Quantum Classifier, Estimator Quantum Neural Network, and Sampler Quantum Neural Network -- the study assesses their performances in detecting financial fraud. Employing a synthetic dataset derived from BankSim, the authors employ data preprocessing, logical analysis, and visualisations to identify key discriminatory features. The QSVC emerges as the most effective model, yielding high F1 scores, exceeding 98% for both fraud and non-fraud classes. The study highlights the potential of QML in fraud detection, providing insights into its capabilities and implications while acknowledging areas for future advancement. In [14], Xiang _et al._, 2023 address the challenge of credit card fraud detection by introducing a novel semi-supervised approach utilising attribute-driven graph representation and a Gated Temporal Attention Network (GTAN). The proposed method effectively enhances fraud detection performance, especially with limited labelled data, according to the study's key findings. The authors constructed a temporal transaction graph based on transaction records, incorporating temporal transactions and interactions, and utilised GTAN for message passing and learning transaction representations. Risk patterns are further modelled through risk propagation amongst transactions. The research showcases that GTAN outperforms state-of-the-art baselines in detecting fraud across multiple datasets, demonstrating its ability to perform well with only a small fraction of labelled data. The study contributes a comprehensive framework that amalgamates attribute-driven embeddings, temporal attention mechanisms, and risk propagation to advance fraud detection methodologies, offering promising avenues for future research and innovation in the field. In [15], Schetakis _et al._, 2023 explore the application of fraud detection for small and medium-sized enterprises. The study employs a hybrid approach, comparing quantum classifiers with classical Artificial Neural Networks (ANN), demonstrating more efficient training and potential advantages in credit scoring. The study focuses on a classical-quantum hybrid model's performance using quantum classifiers and classical ANNs, revealing significant efficiency improvements with promising outcomes in credit scoring for SMEs. In [16], Beer _et al._, 2023 delve into the realm of QML by investigating the use of quantum neural networks for processing graph-structured quantum data. Addressing challenges and opportunities in the Noisy Intermediate-Scale Quantum (NISQ) devices era, the study introduces a novel concept of associating quantum states with graph vertices and correlations with edges. The paper proposes using modified loss functions and quantum training algorithms to learn and characterise complex graph structures with QNNs. The research contributes to the taxonomy of QML approaches, emphasising the significance of correlations and graph structure in advancing quantum information processing capabilities for various applications. ## 3 Classical Graph Neural Networks In this section, we present the theoretical foundations of classical graph neural networks, focusing on the type used in this study. Firstly, we briefly describe the mechanics of ANNs and thereafter describe the GNNs. Artificial Neural Networks are a class of ML algorithms whose structure is derived from the workings of the Biological neurons in sentient beings. Analogous to how the neurological systems of these beings transmit information from one neuron to another, the ANN consists of different layers of neurons that transmit information. Below, we clarify further. * These are the basic units of computation in the ANN. Each neuron consists of an input, hidden, and output layer. * The input layers ingest the initial data. * The hidden layer transforms the data received by the input layer and performs certain computations. * The output layer then receives the transformed data from the hidden layer and returns the predictive result. * **Weights and Biases:** Each connection between neurons has an associated weight, \(w_{ij}\in[0,1]\), between nodes \(i\) and \(j\) respectively, which indicates the strength of connections between neurons and is learned and updated during the training process. The actual interpretation of weights is different for different types of ANNs. In an ANN, a bias term is added to the weighted sum of the inputs to a neuron before the activation function is applied. The bias term allows the neuron to learn a non-linear decision boundary, which is necessary for ANNs to learn complex functions. In Fig. 1, the inputs are represented by \(x_{1},x_{2},x_{3}\), and the weights are represented by \(w_{1},w_{2},w_{3}\) shown in a summation form in the second layer. In terms of the bias, \(b\), the output layer is expressed as \[\hat{y}=\sum_{i}w_{i}x_{i}+b=w_{1}x_{1}+w_{2}x_{2}+w_{3}x_{3}+b. \tag{1}\] * **Activation Functions:** The ANNs consist of an activation function that transforms the given output non-linearly. Several examples of activation functions include the sigmoid, the ReLU and its variations, the hyperbolic tangent, the swish, etc., as shown in Fig. 2. The choice of each of these functions is an artefact of the problem at hand that one is trying to solve, and each has its advantages and disadvantages. Figure 1: The basic structure of an ANN shows the weights and bias along with the respective layers. * **Final Output:** The final layer of a basic ANN is the output layer, which yields the output of the computations from the hidden layers. As we discussed, artificial neural networks are ML models that can be used to learn from data. However, ANNs cannot capture the relationships between entities in a sequence or a grid, as they cannot consider the complex relationships between entities. To solve this problem, we use the where graph neural networks. GNNs are a type of ANN specifically designed to process data structured as a graph. A graph is a group of nodes and edges representing relationships between them. The nodes in a GNN can represent entities such as people, objects, or places, and the edges can represent relationships such as friendships, kinship, or spatial proximity. GNNs can process graph-structured data by iteratively aggregating information from neighbouring nodes. This allows GNNs to learn the complex relationships between entities in a graph, making them a powerful tool for node classification, link prediction, and graph classification tasks. To express the edges and nodes of a graph as inputs to a neuron in an ANN, we first construct an adjacency matrix \(\mathbf{A}\). It is, essentially, a matrix of dimensions \(n\times n\) where \(n\) is the number of nodes in a graph. The entries in the matrix are 1 if an edge exists between the nodes and 0 if there is no edge. Mathematically for each \(A_{ij}\in\mathbf{A}\), and \(1\leq i,j\leq n\), we have that \[A_{ij}=\begin{cases}1,\text{if there exists an edge between nodes $i$ and $j$},\\ 0,\text{otherwise}.\end{cases} \tag{2}\] The adjacency matrix approach has several advantages: If the graph is undirected, the adjacency matrix becomes symmetric and has several interesting properties, including the diagonals representing self-loop vertices, the degree of the graph can be inferred from the sum of any row or column, the number of edges in the graphs (the number of connections required in the ANN) is just half the count of the number of nonzero entries, and properties relating the eigenvalues of \(\mathbf{A}\). In Tab. 1, we observe no self-loops in the graph structure; thus, the diagonal entries of the adjacency matrix will be 0, This is illustrated in Fig. 3, which shows a directed graph with no self-loops. Below, we elaborate on the critical components of GNNs. * **Graph Convolution** This is the key concept underpinning GNN architectures. Graph convolution predicts the features of the node in the next layer as a function of the neighbours' features. It transforms the node's features \(x_{i}\) in a latent space \(h_{i}\) that can be used for various reasons, as shown in Fig. 4. * **Node classification** For a GNN, the objective is firstly to generate latent, from which we would \begin{table} \begin{tabular}{|c|c|c|c|c|c|} \hline & A & B & C & D & E \\ \hline A & 0 & 1 & 0 & 0 & 0 \\ \hline B & 0 & 0 & 1 & 1 & 0 \\ \hline C & 0 & 0 & 0 & 0 & 1 \\ \hline D & 1 & 0 & 0 & 0 & 0 \\ \hline E & 0 & 0 & 0 & 1 & 0 \\ \hline \end{tabular} \end{table} Table 1: Adjacency matrix representing directed edges between nodes \(A\), \(B\), \(C\), \(D\), and \(E\). Figure 4: A graphical representation showing the dependency of the feature of nodes on the features of its neighbouring nodes. Figure 3: A directed graph. The arrows indicate the direction of flow. The graph consists of nodes labelled \(A\), \(B\), \(C\), \(D\), and \(E\). Figure 2: Plot showing the ReLU, Sigmoid, and Tanh activation functions along with vertical and horizontal lines at \(x=0\) and \(y=0\), respectively. then be able to work on a wide variety of standard tasks. Mathematically, we have that \[Z_{i}=f(h_{i}),\] (3) where \(h_{i}\) is the feature vector associated with node \(i\), and it can also be represented in the Fig. 5. * **Edge Classification:** Similarly, we can use it to classify edges based on their features. To accomplish this, we generally need both the adjacent node vectors and the edge features, if they exist. Mathematically, we have that \[Z_{ij}=f(h_{i},h_{j},e_{ij}),\] (4) where \(h_{i},h_{j}\) are the feature vectors associated with nodes \(i\) and \(j\) respectively, and \(e_{ij}\) is the edge connecting nodes \(i\) and \(j\) as shown in Fig. 6. ### Types of Graph Neural Networks There are a variety of graph neural networks. Below, we focus on some of the important types of GNNs: #### 3.1.1 Feed-forward GNNs Also known as "Deep feedforward Networks" or "Multi-layer Perceptrons". In these model architectures, input data is propagated through a graph of neurons to produce output by applying the transfer function at the edge weights between each node as represented in Fig. 7. Feedforward graph neural networks are simplified versions of GNNs that work straightforwardly. They process graph data in just one pass and update node information using neighbouring node data. #### 3.1.2 Graph Recurrent Neural Networks (GRNNs) GRNNs relay information from previous to neighbouring nodes. At each step, the GRNN uses a hidden state as a memory of what the network has encountered thus far in the sequence, as represented in Fig. 9. The network is updated with each new step based on the current input and the previous hidden state. When working with sequences, the RNN "unrolls" itself through time, treating each step as a separate layer of the network. This helps the GRNN handle sequences of different lengths. In [17], it was observed that Recurrent neural networks allow for loops and cycles, giving rise to dynamical systems and flexible behaviour in computation. In [18], it has been observed that graph neural Networks are an evolution of Recurrent Neural Networks (RNNs) that address the limitations of RNNs by combining gated RNN architectures with graph convolutions. #### 3.1.3 Graph Convolutional Neural Networks (GCNNs) These architectures are one of the most popular and widely used GNNs in the literature, and they can be represented as shown in Fig. 8. The main property of GCNNs is their ability to maintain stability under stochastic perturbations. This means that GCNNs are less likely to be affected by noise or randomness in the data, which can be a major advantage in many applications. In [19], a new RES and a GFT model were employed over a GCNNs to test the robustness of the graph filter. GCNN is stable to stochastic perturbations with a factor proportional to the link loss probability. In particular, a wider and deeper GCNN decreases the stability while improving the performance, Figure 5: Graphical representation illustrating node classification. Nodes are associated with expressions \(Z_{i}=f(h_{i})\), where \(i\) ranges from 1 to 7, capturing relationships between features \(Z_{i}\) and hidden features \(h_{i}\). Figure 6: Graphical representation showcasing edge classification Figure 7: Basic structure of Feed-Forward GNNs. The network consists of an input layer with 3 nodes, a hidden layer with 4 nodes, and an output layer. indicating a trade-off between these two factors. In [20], the study leverages the stability property of GNNs to seek stable representations within a distribution. #### 3.1.4 GraphSAGE (Graph Sample and Aggregated) Networks: GraphSAGE is a node classification algorithm that samples and aggregates information from a node's local neighbourhood in a graph. It improves over GCNNs by allowing nodes to aggregate information from a sampled set of neighbours, making GraphSAGE more scalable and generalisable to different graph structures. In [21], Lo and _et al._ proposed E-GraphSAGE, a GNN-based intrusion detection system which outperforms state-of-the-art methods in evaluating network-based intrusion detection systems. These networks use a message-passing scheme to update node representations by aggregating and transforming information from the neighbourhood. They have been shown to be effective in capturing both the edge features and topological information of a graph, making them suitable for analysing interconnected patterns in network flows. The modified E-GraphSAGE and E-ResGAT algorithms integrate residual learning into GNNs to address the challenge of class imbalance and improve performance in minority classes. The GraphSAGE model architecture includes two graph convolution layers and uses the mean aggregation method to effectively capture node information from neighbours in the graph, as shown in Fig. 10. For homogeneous graphs, the feature update rule is the mean aggregator, where the aggregation of features of the neighbours of the node \(v\) are given by \[h_{N(v)}^{i}=\frac{1}{||N(v)||}D_{p}\left[h_{u}^{i-1}\right],\forall u\in N(v), \tag{5}\] where the forward passes through layer \(k\) can be added in the future nodes and is given by \[h_{v}^{i}=\sigma\left(\text{concat}\left[W_{\text{self}}^{k}D_{p}\left[h_{v} ^{i-1}\right],W_{\text{neigh}}^{i}h_{N(v)}^{i}\right]+b^{k}\right). \tag{6}\] In Eq.(5) \(D_{p}\left[\ldots\right]\) is a random dropout with probability \(p\) applied to its argument vector, and \(b^{k}\) is an optional bias. Eqs.(5) and (6) are the rules deciding how the features get updated in the GNN. The GraphSAGE algorithm was implemented on the dataset to perform predictions using StellarGraph. From the original graph, 30% of edges were removed to form a test set, 65% acted as the train set, and 5% acted as the validation set where the internal parameters were optimised over 10 epochs using the ADAM optimiser. The classifier was then applied to the test set; Scores were generated for the classifier's predictions and are provided in the Sec. 6. In the following, we describe the steps of the GraphSAGE algorithm. The algorithm 1 first assigns unique node identifiers to each sample in the dataset. A graph is then constructed using the StellarGraph library, where nodes are identified by their unique identifiers. The GraphSAGENodeGenerator is then used to generate a stream of node samples and their corresponding labels. During the training phase, the GraphSAGE model is instantiated by specifying the sizes of the layers and activation functions. The model includes a dense output layer with a sigmoid activation function for generating predictions. After defining the input and output tensors, a Keras model is created Figure 8: Architecture of Graph Convolutional Neural Network. The network includes a convolution layer followed by a ReLU activation function, a subsequent convolution layer with another ReLU activation function, an intermediate dense layer, and finally, a sigmoid activation function before the output layer. Figure 9: Structure of a Graph Recurrent Neural Network. The GRNN consists of an input layer with 4 nodes, a hidden layer with 5 nodes, and an additional layer with 3 nodes. The architecture is completed with an output layer. and compiled using the Adam optimiser, binary cross-entropy loss, and accuracy metric. The model is trained over a number of epochs using the generated data stream. For non-training data, the trained model is used to predict labels. The predictions are then post-processed by calculating the mode threshold and converting the predicted scores to binary form. Precision-recall curves are then computed to evaluate the model's performance, and the area under the precision-recall curve (AUC-PR) is used to quantify its effectiveness. ## 4 Quantum Graph Neural Networks Our research methodology draws inspiration from the pioneering work of Hu _et al._, 2022 [22] in quantum graph neural network development. Our approach unfolds in the following manner: * transaction amount and time. In this framework, nodes represent encoded features. At the same time, edges symbolise their fusion to get novel graph configurations, and each graph in our feature grouping employs interconnected nodes, totalling 28 nodes per graph. * **Step 2: Topological Data Analysis (TDA) for Graph Projection** Utilising topological data analysis, the graph is embedded into a one-dimensional scatter plot. This technique discriminates between graphs based on their distinct elements, facilitating differentiation between fraudulent and non-fraudulent cases. Following scatter plot creation, node clustering reduces nodes while encapsulating the initial 28 features, minimising quantum resource requirements. A final 28-dimensional feature vector representing the positional attributes is generated. * **Step 3: Encoding within Quantum Circuit and Linear Transformation** Upon acquiring the graphical representation of each transaction, the subsequent step entails encoding it into a quantum state utilising the angle-encoding technique, employing a range of qubits from 1 to 28. To initiate, the encoding Figure 10: Architecture of the GraphSage. It comprises successive GraphSAGE layers, each followed by a ReLU activation function. An intermediate dense layer bridges the structure, culminating in a sigmoid activation function in the output layer. process is applied to all node-level features (\(N\times 28\)), resulting in a dimensionally apt vector (\(N\times q\)) facilitated by a fully connected linear layer. This vector is subsequently channelled into the designated quantum circuit with \(q\) qubits as defined \[\ket{x}=\bigotimes_{i=1}^{N}\cos(x_{i})\ket{0}+i\sin(x_{i})\ket{1}.\] (7) * **Step 4: Enhancing Node Features with Variational Quantum Circuits** Following the previous steps, a sequence of two-local ansatz constructs orchestrates the implementation of a multi-layered Variational Quantum Circuit (VQC) calibrated for the transactional dataset. Fig. 11 visually portrays a circuit encompassing a 6-qubit with the angle encoding alongside 2 concealed VQC layers. Notably, the ansatz capitalises on Rx, Ry, and CNOT operations while adopting Rx rotations for angle encoding, as explained in the 3rd step. Subsequently, circuit measurement culminates in using Pauli-Z expectation. This strategic circuit design is a conscientious outcome of considerations concerning circuit expressibility and intricate node-node interactions embedded within graphical data. We enhance node features using the VQC, emulating the operational principles of conventional classical graph neural networks with fully connected layers. VQC entails the successive application of variational layers. A single layer transformation \(L\) is depicted as \[L:\ket{\psi(x)}\rightarrow\ket{\psi(y)}=U(w)\ket{\psi(x)},\] (8) where \(U(w)\) represents the VQC with \(N\) layers, defined as \[U(w)=T\bigotimes_{k=1}^{N}R_{y}(w_{k})\ket{\psi(x)}.\] (9) * **Step \(5\): Integration of Unitary Gates and Classification** In order to meet the requirements of a quantum graph neural network, it is necessary to have unitary gates that act on two states simultaneously while preserving the others. As we explained, rotational gates are essential to integrate the graph into the quantum circuit. Once these gates are in place, a linear layer can classify the graph as fraudulent or non-fraudulent. The comprehensive procedure outlined in Fig. 12 sheds light on the architecture and operational aspects of the QGNN, highlighting the distinct components and their produced interplay in fraud detection. Additionally, Algorithm 4 provides a step-by-step algorithm description. ``` Inputs: Graph data (training, validation) Initialise QGNN for each epoch in training do for each graph batch in training data do Extract graph features and edges Apply angle encoding to the graph features Initialise Quantum Circuit for VQC Generate tunable parameters for VQC Update Quantum Circuit using inputs and VQC parameters Run the Quantum circuit (VQC) to obtain quantum output Perform average pooling for graph-level features Make predictions using a linear layer Compute loss and update parameters using Adam optimiser endfor Evaluate QGNN on validation data endfor Calculate optimal threshold for binary classification Convert predictions to binary using the threshold Calculate Precision-Recall curve and AUC-PR Return Classification metrics, loss values ``` **Algorithm 2** Quantum Graph Neural Networks ## 5 The Dataset We used the publicly available credit card fraud detection dataset [23] for our analysis. This dataset contains credit card transactions of European cardholders with encrypted feature labels obtained from principal component analysis on actual user data. Each transaction is labelled as either fraud (1) or not fraud (0) and contains 28 encrypted features along with amount and time values. The dataset is highly imbalanced, with only 492 frauds out of 284 807 transactions. To address this imbalance, we used random undersampling on the non-fraud transactions. For a comprehensive understanding of the dataset characteristics, we utilised visual representations. In Fig. 13, we present the correlation matrix (\(v_{1}-v_{28}\)) of the dataset. The figure effectively illustrates the relationships between the features \(v_{1}\) to \(v_{28}\) by displaying their correlation values. This information offers insights into how these features interact and influence one another. Additionally, Fig. 14 offers histograms that vividly depict the distribution of all features in the dataset. These histograms visually represent the data distribution patterns, assisting us in identifying potential trends and outliers. Furthermore, our approach involved translating each transaction as a graph using topological data analysis [24]. This technique allowed us to capture intricate relationships among the various feature vectors, enhancing our ability to analyse the data effectively. In the following steps, we explain how to apply and implement this technique. Given a transaction described by a vector \[\mathbf{V}=[\text{Time},V_{1},V_{2},\ldots,V_{28},\text{Amount}], \tag{10}\] We create the graph \(G=(N,E)\), where \(N\in\{R^{1},R^{2},\ldots,R^{28}\}\) represents the feature vector, and \(E\) represents the edge list, where, \(V_{1},V_{2},\ldots,V_{28}\) denotes the encrypted feature labels in the dataset. Next, we focus on converting the transaction, \(\{T_{i}\}_{i=1}^{284\;807}\), into its graphical representations \(G_{i}\) via the following steps using TDA: 1. Create a set \(\{S_{i}\}\) of 3D data points, where \(S_{i}=\left\{P_{j}\;|\;P_{j}=[\text{Time}_{i},V_{j},\text{Amount}_{i}]\,,\; \forall j\in[1,28]\;\right\}\). This helps in capturing the correlation of \(V_{j}\) with time and amount. 2. Project all data points \(P_{j}\in S_{i}\) onto a 1D plane. We denote these projected points as \(f_{j}\). 3. Draw covers around all the projected data points \(\{f_{j}\}_{j=1}^{28}\) and cluster them using a suitable clustering algorithm, here, we have used DBSCAN. Let these clusters form a set \(\{C_{i}\}\), where \(C_{i}=\left\{c_{k}\,|\;\exists_{j,k}\;:\;f_{j}\in c_{k},\,\forall j\in[1,28] \;and\;1<k<|C_{i}|\right\}\) 4. Draw edges between clusters with common data points to form the graph \(G_{i}\). Here, a node \(N_{k}\in G_{i}\), represents a cluster \(c_{k}\in\{C_{i}\}\), s.t. \(N_{k}=\left(0\ldots V_{j}\ldots 0\right)_{28},\;\forall f_{j}\in c_{k}\). Thus, the relation between different features is captured and grouped using the clustering algorithm of high-dimensional data via a more representative graphical structure. Each graph represents a transaction labelled Figure 11: Quantum circuit for angle encoding and VQC in the QGNN architecture with RY, RX, and CNOT gates. Figure 12: Architecture of the quantum graph neural network. The QGNN starts with a graph as input, followed by a feature compression step. Angle encoding prepares the data for the VQC processing. The output of the VQC is subjected to average pooling, then fed through a linear layer, and finally to the output layer fraud or non-fraud for the classification task. ## 6 Results and Discussion We tested the performance of our two classical and quantum algorithms on the same dataset described in Sec. 5. The results showed that the GraphSAGE model achieved promising results on the fraud classification task. The model was trained for 10 epochs using the Adam optimiser with a batch size of 5 using Keras, as shown in Tab. 2. The aggregation method was set to mean. These hyperparameters were chosen based on preliminary experiments and empirical observations to balance model complexity and generalisation performance. The receiver operating characteristic (ROC) curve presented in Fig. 15 shows the trade-off between the true positive rate (TPR) and the false positive rate (FPR) for the GraphSAGE model. The Area Under Cover (AUC) score measures how well a model can distinguish between positive and negative instances. A higher AUC score indicates a better model. The GraphSAGE model achieves an AUC of 0.77, within the acceptable range for fraud classification tasks. The performance metrics for the GraphSAGE model are also within the acceptable range, with an accuracy of 92.3%, and F1 score of 0.83. These scores are reported in Tab. 3. The loss curves in Fig. 16 show that the training loss decreases steadily over time while the validation loss decreases more slowly, which suggests that the model is well-fitted on both the training and validation data. We performed experiments on the quantum graph neural network using qiskit [25] under different scenarios, namely qubit count and hidden layers. The results in Tab. 4 show that a dense encoding scheme of node features using fewer qubits performed better than using more qubits and sparser representations, and this is evident as the model with 6 qubits, with an accuracy of 94.5% and F1 score of 0.86, performed best compared to that with 16 qubits, with an accuracy of 92.0% and F1-score of 0.81. The AUC for the precision-recall curve from Fig. 17 is estimated to be roughly 0.85, which shows high tolerance in our method towards biased datasets with high class imbalances, apart from having highly accurate predictions. A smoother transition curve leads to a better F1 score, and the loss curves show a decrease in the loss function over time for both training and validation, which shows that our model is well-fitted, as presented in Fig. 18. These results are observed on a basic network architecture of quantum circuits and outperform various classical approaches. This is due to the enhanced representation of graphical structures through quantum circuits and efficient feature relations using topological data analysis. We can see an improvement of \(\approx 3\%\) over classical GNN, such as GraphSAGE, across various metrics. However, it was observed that graphical techniques, in general, help enhance the precision and accuracy of these classification systems more than other non-graphical approaches. Careful analysis of quantum techniques suggests that better representation, deeper search space, state entanglement, and qubit parallelism are key factors contributing to the supremacy of quantum circuits for classification tasks. In our experiments, we observed the same with a smaller system with 6 qubits and \(\approx\)200 parameters, which makes our model QGNN outperform the classical GNN. These results suggest that with more advanced features and complex quantum systems, we can achieve a real quantum advantage in solving problems such as fraud detection \begin{table} \begin{tabular}{l l} \hline \hline **Hyperparameter** & **Value** \\ \hline Model Architecture & GraphSAGE \\ Number of Epochs & 10 \\ Optimiser & Adam \\ Batch Size & 5 \\ Aggregation Method & Mean \\ \hline \hline \end{tabular} \end{table} Table 2: Hyperparameters and training details for the GraphSAGE model. Figure 13: Correlation matrix (\(v_{1}-v_{28}\)) of the dataset. The figure illustrates the relationships between the features \(v_{1}\) to \(v_{28}\) by displaying their correlation values. in highly imbalanced datasets. \begin{table} \begin{tabular}{|c|c|c|c|c|c|} \hline **Num Qubits** & **Layers** & **Accuracy (\%)** & **Precision (\%)** & **Recall (\%)** & **F1 score** \\ \hline \hline 6 & 1 & 94.5 & 96.1 & 79.5 & 0.86 \\ 16 & 1 & 92.06 & 86.5 & 77.3 & 0.81 \\ 6 & 2 & 91.5 & 93.3 & 65.6 & 0.76 \\ 16 & 2 & 89.2 & 86.6 & 72 & 0.77 \\ \hline \end{tabular} \end{table} Table 4: Performance test metrics of QGNN. The table presents results for various configurations, including the number of qubits and layers. Figure 16: Training and validation loss curves for the GraphSAGE model. Figure 14: Histograms illustrating the distribution of all features in the dataset. Figure 15: Receiver Operating Characteristic Curve for the GraphSAGE model with an AUC of 0.77. ## 7 Conclusion Our research has demonstrated the potential of quantum graph neural networks in detecting financial fraud. We have compared the performance of QGNNs with classical graph neural networks and found that QGNNs outperformed GNNs in terms of accuracy and efficiency. Our experiments on a real-world financial dataset show that QGNNs can detect fraud with a remarkable accuracy of 94.5%, which is significantly higher than GNNs' accuracy of 92.3%. Moreover, we have also studied the influence of the number of qubits and layers on QGNNs' performance. Our research indicates that QGNNs with 6 qubits and one layer exhibit the best performance, with an accuracy of 94.5%. This can be attributed to the fact that fewer qubits are less prone to noise, and a single layer is sufficient to grasp the essential features of the data. Our research shows that QGNNs have the potential to revolutionise fraud detection and improve the security of financial systems. It also highlights the need for further research to address the challenges of implementing QC in real-world applications.
2307.14938
Efficient Interaction-Aware Interval Analysis of Neural Network Feedback Loops
In this paper, we propose a computationally efficient framework for interval reachability of systems with neural network controllers. Our approach leverages inclusion functions for the open-loop system and the neural network controller to embed the closed-loop system into a larger-dimensional embedding system, where a single trajectory over-approximates the original system's behavior under uncertainty. We propose two methods for constructing closed-loop embedding systems, which account for the interactions between the system and the controller in different ways. The interconnection-based approach considers the worst-case evolution of each coordinate separately by substituting the neural network inclusion function into the open-loop inclusion function. The interaction-based approach uses novel Jacobian-based inclusion functions to capture the first-order interactions between the open-loop system and the controller by leveraging state-of-the-art neural network verifiers. Finally, we implement our approach in a Python framework called ReachMM to demonstrate its efficiency and scalability on benchmarks and examples ranging to $200$ state dimensions.
Saber Jafarpour, Akash Harapanahalli, Samuel Coogan
2023-07-27T15:30:22Z
http://arxiv.org/abs/2307.14938v3
# Efficient Interaction-Aware Interval Analysis of Neural Network Feedback Loops ###### Abstract In this paper, we propose a computationally efficient framework for interval reachability of systems with neural network controllers. Our approach leverages inclusion functions for the open-loop system and the neural network controller to embed the closed-loop system into a larger-dimensional embedding system, where a single trajectory over-approximates the original system's behavior under uncertainty. We propose two methods for constructing closed-loop embedding systems, which account for the interactions between the system and the controller in different ways. The interconnection-based approach considers the worst-case evolution of each coordinate separately by substituting the neural network inclusion function into the open-loop inclusion function. The interaction-based approach uses novel Jacobian-based inclusion functions to capture the first-order interactions between the open-loop system and the controller by leveraging state-of-the-art neural network verifiers. Finally, we implement our approach in a Python framework called ReachM to demonstrate its efficiency and scalability on benchmarks and examples ranging to \(200\) state dimensions. ## I Introduction Problem Description and MotivationsRecent advances in machine learning are bringing learning algorithms into the heart of safety-critical control systems, such as autonomous vehicles, manufacturing sectors, and robotics. For control systems, these learning algorithms often act in the closed-loop setting, as direct feedback controllers [1] or motion planners [2]. Learning-based closed-loop controllers can improve the performance of systems while reducing their computational burden for online implementations as compared with more traditional optimization-based approaches. However, despite their impressive performance, learning models are known to be overly sensitive to input disturbances [3]: a small input perturbation can lead to comparatively large changes in their output. This issue amplifies in feedback settings, as disturbances can accumulate in the closed-loop. As a result, ensuring reliability of learning algorithms is an essential challenge in their integration into safety-critical systems. Typical learning architectures involve high-dimensional nonlinear function approximators, such as neural networks, necessitating special tools for their input-output analysis. The machine learning and control community have made significant progress in analyzing the safety of neural networks in isolation, including efficient and sound input-output bounds, worst-case adversarial guarantees, and sampling-based stochastic guarantees (cf. [4]). However, most of these existing frameworks for standalone neural networks do not address the unique challenges for closed-loop analysis--namely information propagation, non-stationarity of the bounds, and complex interactions between the system and the controller. In these cases, it is essential to understand and capture the nature of the interactions between the system and the neural network. Recently, several frameworks have emerged for safety verification of learning algorithms in the closed-loop. These frameworks usually incorporate neural network verification algorithms into the closed-loop safety analysis by studying their interactions with the open-loop system. However, most of these existing frameworks are either limited to a specific class of systems or learning algorithms, or they impose significant computational burdens, rendering them unsuitable for runtime safety verification. Literature ReviewSafety verification of nonlinear dynamical systems without learning-enabled systems is a classical problem and is typically solved using reachability analysis tools, although significant challenges remains even in this setting. Reachability of nonlinear systems has been studied using optimization-based methods such as the Hamilton-Jacobi approach [5] and the level set approach [6]. Several computationally tractable approaches including the ellipsoidal method [7] and the zonotope method [8] have been developed for reachability analysis of dynamical systems. We refer to [9] for a recent review of state-of-the-art reachability analysis techniques. Interval analysis is a classical framework for computing interval functional bounds [10] which has been successfully used for reachability analysis of dynamical systems [11, 12, 13]. A closely-related body of literature is the mixed monotone theory, which extends the classical monotone system theory by separating the cooperative and competitive effect of the dynamics [14, 15]. Recently, mixed monotone theory has been used as an efficient framework for reachability analysis of dynamical systems [16, 17, 18, 19]. Rigorous verification of standalone neural networks has been studied using abstract interpretation techniques such as Reluplex [20] and Neurify [21], using interval bound propagation methods [22, 23], and convex-relaxation approaches such as LipSDP [24] and CROWN [25] and its variants [26]. The simplest method for studying reachability of neural network controlled systems is via an _input-output approach_: using existing techniques for estimating the output of the neural network, the input-output approach performs reachability analysis of the closed-loop system by substituting the full output range of the neural network as the input set of the open-loop system. Examples of this approach include NNV [27], and simulation-guided interval analysis [28]. This approach is generally computationally efficient and applicable to general forms of neural networks and control systems, but it can lead to overly-conservative estimates of reachable sets [29, Section 2.1]. The reason for this over-conservatism is that this approach essentially treats neural networks controllers as adversaries and, thus, cannot capture the beneficial interactions between the controller and the system. An alternative framework is the _functional approach_, which is based on composing function approximations of the system and the neural network controller. Examples of this approach for linear systems include using linear programming in ReachLP [30], using semi-definite programming in Reach-SDP [31], and using mixed integer programming in [32]. For nonlinear system, the functional approach has been used in ReachNN [33], Sherlock [29], Verisig 2.0 [34], POLAR [35] and JuliaReach [36, 37]. Functional methods are able to capture beneficial interactions between the neural network controller and the system, but they are often computationally burdensome and generally do not scale well to large-scale systems. ContributionsIn this paper, we introduce a general and computationally efficient framework for studying reachability of continuous-time closed-loop systems with nonlinear dynamics and neural networks controllers. First, we review the notion of inclusion function from classical interval analysis to over-approximate the input-output behavior of functions. Our first minor result states that if an inclusion function is chosen to be minimal, then it provides tighter over-approximations of the output behavior than a Lipschitz bound of the function. For a given function, we study different approaches for constructing inclusion functions. In particular, we propose a novel Jacobian-based cornered inclusion function, which is specially amenable to analysis of closed-loop systems. We further show that this class of inclusion functions plays a critical role in integrating the existing off-the-shelf neural network verification algorithms into our framework. Second, using the notion of inclusion functions, we develop a general approach for interval analysis of continuous-time dynamical systems. The key idea is to use the inclusion functions to embed the original dynamical system into a higher dimensional embedding system. Then trajectories of the embedding system can be used to provide hyper-rectangular over-approximation for reachable sets of the original system. Our approach unifies and extends several existing approaches for interval analysis of dynamical systems. Noteably, our novel proof technique, based on the classical monotone comparison Lemma, allows for accuracy comparison between different inclusion functions. As the culminating contribution of this paper, we develop a computationally efficient framework for reachability analysis of nonlinear systems with neural network controllers. The key in our framework is a careful combination of the inclusion function for the open-loop system and the inclusion function for the neural network controller to obtain an inclusion function for the closed-loop system. We propose two methods for combining the open-loop inclusion function and the neural network inclusion function. The first method, called the interconnection-based approach, constructs a closed-loop embedding system using the feedback interconnection of the open-loop embedding system and the inclusion function for the neural network. This method is general, as it can be applied to any open-loop and neural network inclusion function, and is computationally efficient, as it uses the compositional property of inclusion functions. The second method, called the interaction-based approach, constructs a closed-loop embedding system using a Jacobian-based inclusion function for the open-loop system and local affine bounds for the neural network. Compared to the interconnection-based approach, the interaction-based method completely captures the first order interactions between the system and the neural network. Finally, we implement our approach in a Python toolbox called ReachMM and perform several numerical experiments to show the efficiency and accuracy of our framework. For several linear and nonlinear benchmarks, we show that our method beats the state-of-the-art methods. Moreover, we study scalability of our approach and compare it with the state-of-the-art methods on a platoon of vehicles with up to 200 state variables. Compared to our conference paper [38], this paper provides a more general framework for interval reachability using inclusion functions, introduces the interaction-based approach to capture the first order interactions between the system and the neural network controller, and includes a suite of numerical experiments. We would like to highlight that, in this paper, we focus on continuous-time dynamical systems. However, with minor modifications, our framework can be used to analyze reachability of discrete-time systems. ## II Mathematical Preliminary and Notations For every two vectors \(v,w\in\mathbb{R}^{n}\) and every subset \(S\subseteq\{1,\ldots,n\}\), we define the vector \(v_{[S:w]}\in\mathbb{R}^{n}\) by \(\big{(}v_{[S:w]}\big{)}_{j}=\begin{cases}v_{j}&j\not\in S\\ w_{j}&j\in S\end{cases}\). Given a matrix \(B\in\mathbb{R}^{n\times m}\), we denote the non-negative part of \(B\) by \([B]^{+}=\max(B,0)\) and the nonpositive part of \(B\) by \([B]^{-}=\min(B,0)\). Given a square matrix \(A\in\mathbb{R}^{n\times n}\) the Metzler and non-Metzler part of \(A\) are denoted by \([A]^{\mathrm{M}}\) and \([A]^{\mathrm{mM}}\), respectively, where \(([A]^{\mathrm{M}})_{ij}=\begin{cases}A_{ij}&A_{ij}\geq 0\text{ or }i=j\\ 0&\text{otherwise,}\end{cases}\) and \([A]^{\mathrm{mM}}=A-[A]^{\mathrm{M}}\). Given a map \(g:\mathbb{R}^{n}\to\mathbb{R}^{m}\), the \(\ell_{\infty}\)-norm Lipschitz bound of \(g\) is the smallest \(L\in\mathbb{R}_{\geq 0}\) such that \[\|g(x)-g(y)\|_{\infty}\leq L\|x-y\|_{\infty},\qquad\text{ for all }x,y\in\mathbb{R}^{n}.\] We denote the \(\ell_{\infty}\)-norm Lipschitz constant of \(g\) by \(\mathrm{Lip}_{\infty}(g)\). For a differentiable map \(g:\mathbb{R}^{n}\to\mathbb{R}^{m}\), we denote its Jacobian at point \(x\in\mathbb{R}^{n}\) by \(Dg(x)\). Consider the dynamical system \[\dot{x}=f(x,w),\qquad\qquad\text{ for all }t\in\mathbb{R}_{\geq 0}, \tag{1}\] where \(x\in\mathbb{R}^{n}\) is the state of the system and \(w\in\mathbb{R}^{q}\) is the disturbance. Given a piecewise continuous disturbance \(t\mapsto w(t)\) and an initial condition \(x_{0}\in\mathbb{R}^{n}\), the trajectory of (1) starting from \(x_{0}\) is denoted by \(\phi_{f}(t,x_{0},w(t))\). Let and \(\mathcal{W}\subseteq\mathbb{R}^{q}\), then the reachable set of (1) starting from the initial set \(\mathcal{X}\) and with the disturbance set \(\mathcal{W}\) is defined by: \[\mathcal{R}_{f}(t,\mathcal{X},\mathcal{W})=\left\{\begin{aligned} &\phi_{f}(t,t_{0},x_{0},w),\,\forall x_{0}\in \mathcal{X},\\ & w:\mathbb{R}\rightarrow\mathcal{W}\text{ piecewise cont.}\end{aligned}\right\} \tag{2}\] The set \(\mathcal{X}\) is _robustly forward invariant_ if \(\mathcal{R}_{f}(t,\mathcal{X},\mathcal{W})\subseteq\mathcal{X}\) for all \(t\geq 0\). The system (1) is continuous-time monotone on \(\mathcal{X}\subseteq\mathbb{R}^{n}\) if, for every \(i\in\{1,\ldots,n\}\), every \(x\leq y\in\mathcal{X}\) with \(x_{i}=y_{i}\), and every \(u\leq v\), we have \(f_{i}(x,u)\leq f_{i}(y,v)\). One can show that if a dynamical system (1) is monotone on \(\mathcal{X}\) and \(\mathcal{X}\) is robustly forward invariant, then its trajectories preserve the standard partial order by time, i.e., for every two trajectories \(t\mapsto x(t)\) and \(t\mapsto y(t)\) of the systems (1), if \(x(0)\leq y(0)\), then \(x(t)\leq y(t)\) for all \(t\in\mathbb{R}_{\geq 0}\)[39]. The _southeast_ partial order \(\leq_{\mathrm{SE}}\) on \(\mathbb{R}^{2n}\) is defined by \(\left[\frac{x}{2}\right]\leq_{\mathrm{SE}}\left[\frac{y}{y}\right]\) if and only if \(x\leq y\) and \(\tilde{y}\leq\tilde{x}\). We also define \(\mathcal{T}_{\geq 0}^{2n}=\{[\left\lceil\frac{x}{2}\right\rceil\in\mathbb{R}^{2n} \mid x\geq\tilde{x}]\text{ and }\mathcal{T}_{\leq 0}^{2n}=\{[\frac{x}{2}]\in \mathbb{R}^{2n}\mid x\geq\tilde{x}\}\text{ and }\mathcal{T}^{2n}=\mathcal{T}_{\geq 0}^{2n} \bigcup\mathcal{T}_{\leq 0}^{2n}\). ## III Problem Statement We consider a system described by: \[\dot{x}=f(x,u,w),\qquad\qquad\qquad t\in\mathbb{R}_{\geq 0}, \tag{3}\] where \(x\in\mathbb{R}^{n}\) is the state of the system, \(u\in\mathbb{R}^{p}\) is the control input, and \(w\in\mathbb{R}^{q}\) is the disturbance. We assume that \(f:\mathbb{R}^{n}\times\mathbb{R}^{p}\times\mathbb{R}^{q}\rightarrow\mathbb{R}^ {n}\) is a parameterized vector field and the state feedback is parameterized by a \(k\)-layer feed-forward neural network controller \(N:\mathbb{R}^{n}\rightarrow\mathbb{R}^{p}\) defined by: \[\xi^{(0)} =x\] \[\xi^{(i)} =\phi^{(i-1)}(W^{(i-1)}\xi^{(i-1)}+b^{(i-1)}),\quad i\in\{1, \ldots,k\}\] \[u =W^{(k)}\xi^{(k)}(x)+b^{(k)}:=N(x), \tag{4}\] where \(n_{i}\) is the number of neurons in the \(i\)th layer, \(W^{(i-1)}\in\mathbb{R}^{n_{i}\times n_{i-1}}\) is the weight matrix of the \(i\)th layer, \(b^{(i-1)}\in\mathbb{R}^{n_{i}}\) is the bias vector of the \(i\)th layer, \(\xi^{(i)}(y)\in\mathbb{R}^{n_{i}}\) is the \(i\)th layer hidden variable, and \(\phi^{(i-1)}:\mathbb{R}^{n_{i}}\rightarrow\mathbb{R}^{n_{i}}\) is the \(i\)th layer diagonal activation function satisfying \(0\leq\frac{\phi^{(i-1)}_{\mathrm{}}(x)-\phi^{(i-1)}_{\mathrm{}}(y)}{x-y}\leq 1\) for every \(j\in\{1,\ldots,n_{i}\}\). One can show that a large class of activation functions including ReLU, leaky ReLU, sigmoid, and tanh satisfies this condition (after a possible re-scaling of their co-domain). With this neural network feedback controller, the closed-loop system is given by: \[\dot{x}=f(x(t),N(x(t)),w):=f^{c}(x(t),w). \tag{5}\] We assume that \(\mathcal{X}_{0}\subseteq\mathbb{R}^{n}\) is the initial set of states for the closed-loop system (5). This set can represent the uncertainties in the starting state of the system or localization errors in estimating the current state of the system. Moreover, we assume that the disturbance \(w\) belongs to the set \(\mathcal{W}\subseteq\mathbb{R}^{n}\) representing the model uncertainty or exogenous disturbances on the system. In this paper, we focus on the target-avoid problem as defined below: **Target-Avoid Problem.** Given a target set \(\mathcal{G}\subset\mathbb{R}^{n}\), and an unsafe set \(\mathcal{S}_{\mathrm{unsafe}}\subset\mathbb{R}^{n}\) and a time interval \([0,T]\), check if the closed-loop system (5) reaches the target \(\mathcal{G}\) at time \(T\) while avoiding the unsafe region \(\mathcal{S}_{\mathrm{unsafe}}\). Mathematically, 1. \(\mathcal{R}_{f^{c}}(T,\mathcal{X}_{0},\mathcal{W})\subseteq\mathcal{G}\), 2. \(\mathcal{R}_{f^{c}}(t,\mathcal{X}_{0},\mathcal{W})\bigcap\mathcal{S}_{\mathrm{ unsafe}}=\emptyset\), for all \(t\in[0,T]\). The target-avoid problem is a classical and prevalent notion of safety in many engineering applications, especially those involving safety-critical systems [9]. Moreover, diverse objectives including multiagent coordination, complex planning specified with formal languages and logics, and classical control-theoretic criteria such as robust invariance and stability can be achieved by concatenating and combining different instantiations of the target-avoid problem. In general, computing the exact reachable sets of the closed-loop system (5) is not computationally tractable. Our approach to solve the target-avoid safety problem is based on constructing a computationally efficient over-approximation \(\overline{\mathcal{R}}_{f^{c}}(t,\mathcal{X}_{0},\mathcal{W})\) of the reachable set of the closed-loop system. Then, reaching the target is guaranteed by \(\overline{\mathcal{R}}_{f^{c}}(T,\mathcal{X}_{0},\mathcal{W})\subseteq\mathcal{G}\) and avoiding the unsafe region is guaranteed when \(\overline{\mathcal{R}}_{f^{c}}(t,\mathcal{X}_{0},\mathcal{W})\bigcap\mathcal{S}_{ \mathrm{unsafe}}=\emptyset\), for every \(t\in[0,T]\). ## IV Interval Analysis and Inclusion Functions In this section, we develop a theoretical framework for interval reachability analysis of arbitrary mappings. The key element in our framework is the notion of inclusion function from interval arithmetic [10, 40]. ### _Inclusion Functions_ Given a nonlinear input-output map \(g:\mathbb{R}^{n}\rightarrow\mathbb{R}^{m}\) and an interval input, the inclusion function of \(g\) provides interval bounds on the output of \(g\). **Definition 1** (Inclusion function [10]).: Given a map \(g:\mathbb{R}^{n}\rightarrow\mathbb{R}^{m}\), the function \(\mathsf{G}=\left[\frac{\mathsf{G}}{\mathsf{G}}\right]:\mathcal{T}_{\geq 0}^{2n}\rightarrow \mathcal{T}_{\geq 0}^{2m}\) is 1. an _inclusion function_ for \(g\) if, for every \(x\leq\widehat{x}\) and every \(z\in[x,\widehat{x}]\), we have \[\underline{\mathsf{G}}(x,\widehat{x})\leq g(z)\leq\overline{\mathsf{G}}(x, \widehat{x}).\] (6) 2. a \([y,\widehat{y}]\)_-localized inclusion function_ if (6) holds for every \([x,\widehat{x}]\subseteq[y,\widehat{y}]\) and every \(z\in[x,\widehat{x}]\). Moreover, an inclusion function \(\mathsf{G}\) for \(g\) is 1. _monotone_ if, for every \([\frac{x}{2}]\leq_{\mathrm{SE}}\left[\frac{y}{y}\right]\), we have \(\mathsf{G}(x,\widehat{x})\leq_{\mathrm{SE}}\mathsf{G}(y,\widehat{y})\); 2. _thin_ if, for every \(x\in\mathbb{R}^{n}\), \(\underline{\mathsf{G}}(x,x)=\overline{\mathsf{G}}(x,x)=g(x)\); 3. _minimal_ if, for every \(x\leq\widehat{x}\), the interval \([\underline{\mathsf{G}}(x,\widehat{x}),\overline{\mathsf{G}}(x,\widehat{x})]\) is the smallest interval containing \(g([x,\widehat{x}])\). Given a nonlinear map \(g:\mathbb{R}^{n}\rightarrow\mathbb{R}^{m}\), one can show that its minimal inclusion function \(\mathsf{G}^{\min}=\left[\frac{\mathsf{G}^{\min}}{\mathsf{G}^{\min}}\right]\) is given by: \[\underline{\mathsf{G}}^{\min}_{i}(x,\widehat{x})=\inf_{z\in[x,\widehat{x}]}g_{i}( z),\quad\overline{\mathsf{G}}^{\min}_{i}(x,\widehat{x})=\sup_{z\in[x,\widehat{x}]}g_{i}(z), \tag{7}\] for every \(i\in\{1,\ldots,n\}\). The next theorem shows that the minimal inclusion function provides sharper over-approximations compared to Lipschitz bounds. **Theorem 1** (Minimal inclusion functions).: _Consider the function \(g:\mathbb{R}^{n}\rightarrow\mathbb{R}^{m}\) and the mapping \(\mathsf{G}^{\min}=\left[\frac{\mathsf{G}^{\min}}{\mathsf{G}^{\min}}\right]\) defined by (7). Then, for every \(x\leq\widehat{x}\), we have_ \[\|\mathsf{G}^{\min}(x,\widehat{x})-\overline{\mathsf{G}}^{\min}(x,\widehat{x} )\|_{\infty}\leq\mathrm{Lip}_{\infty}(g)\|x-\widehat{x}\|_{\infty}.\] Proof.: Let \(i\in\{1,\ldots,k\}\) be such that \(\|\overline{\mathsf{G}}^{\min}(x,\widehat{x})-\underline{\mathsf{G}}^{\min} (x,\widehat{x})\|_{\infty}=\left|\overline{\mathsf{G}}^{\min}_{i}(x,\widehat{ x})-\underline{\mathsf{G}}^{\min}_{i}(x,\widehat{x})\right|\). Note that since \(g\) is continuous and the box \([x,\widehat{x}]\) is compact, there exist \(\eta^{*},\xi^{*}\in[x,\widehat{x}]\) such that \[\max_{y\in[x,\widehat{x}]}g_{i}(y)=g_{i}(\eta^{*}),\qquad\min_{y\in[x, \widehat{x}]}g_{i}(y)=g_{i}(\xi^{*}).\] This implies that \(\|\overline{\mathsf{G}}^{\min}(x,\widehat{x})-\underline{\mathsf{G}}^{\min} (x,\widehat{x})\|_{\infty}=|g_{i}(\eta^{*})-g_{i}(\xi^{*})|\leq\|g(\xi^{*})-g (\eta^{*})\|_{\infty}\leq\mathrm{Lip}_{\infty}(g)\|\xi^{*}-\eta^{*}\|_{\infty} \leq\mathrm{Lip}_{\infty}(g)\|x-\widehat{x}\|_{\infty}\). ### _Designing Inclusion Functions_ Given a function \(g\), finding a suitable inclusion function for \(g\) is a central problem in interval analysis. We review three approaches for constructing inclusion functions. Natural inclusion functionAs we showed in the previous section, the minimal inclusion function can be computed using the optimization problem (7). However, for general functions, solving this optimization problem is not tractable. One feasible approach is to find the minimal inclusion function for a handful of elementary functions for which the optimization problem (7) is solvable. Then, for an arbitrary function, a natural inclusion function can be obtained by expressing it as a finite composition of operators and elementary functions [10, Theorem 2][41, Theorem 2]. Several software packages exist for automatically computing natural inclusions functions. In [41], we introduce the software package npinterval1 that implements intervals as a native data type within the Python toolbox numpy[42], yielding flexibility, efficiency through vectorization across arrays, and canonical constructions of natural inclusion functions. Footnote 1: The code for npinterval is available at [https://github.com/gftastlab/npinterval](https://github.com/gftastlab/npinterval) Jacobian-based inclusion functionsGiven a continuously differentiable function \(g:\mathbb{R}^{n}\rightarrow\mathbb{R}^{m}\), one can use upper and lower bounds on the Jacobian of \(g\) to construct inclusion functions for \(g\). These inclusion functions are often derived from the Taylor expansion of the function \(g\) around a certain point. Most commonly, this point is taken as the midpoint of an interval, leading to, in particular, the centered inclusion function [10, SS2.4.3] and the mixed-centered inclusion function [10, SS2.4.4]. In the next theorem, we develop a Jacobian-based inclusion function obtained by linearization around corners of an interval. As demonstrated in the sequel, such cornered inclusion functions turn out to be particularly amenable to analysis of closed-loop control systems. **Proposition 1** (Jacobian-based cornered inclusion function).: _Given a continuously differentiable function \(g:\mathbb{R}^{n}\rightarrow\mathbb{R}^{m}\) such that \(Dg(z)\in[\underline{J}_{[z,\widehat{x}]},\overline{J}_{[x,\widehat{x}]}]\), for every \(z\in[x,\widehat{x}]\). The function \(\mathsf{G}^{\mathrm{jac}}:\mathcal{T}_{\geq 0}^{2n}\rightarrow\mathcal{T}_{\geq 0}^{2n}\) defined by_ \[\mathsf{G}^{\mathrm{jac}}(x,\widehat{x})=\begin{bmatrix}-[\underline{J}_{[x, \widehat{x}]}]^{-}&-[\underline{J}_{[x,\widehat{x}]}]^{-}\\ -[\overline{J}_{[x,\widehat{x}]}]^{+}&\overline{[J}_{[x,\widehat{x}]}]^{+} \end{bmatrix}\begin{bmatrix}x\\ \widehat{x}\end{bmatrix}+\begin{bmatrix}g(x)\\ g(x)\end{bmatrix}\] _is an inclusion function for \(g\)._ Proof.: Since \(g\) is continuously differentiable, for every \(z\in[x,\widehat{x}]\), we have \(g(z)=g(x)+\int_{0}^{1}Dg(tz+(1-t)x)(z-x)dt\). Thus, for every \(x\in[x,\widehat{x}]\), \[g(z) \leq g(x)+\overline{J}_{[x,\widehat{x}]}(z-x)\] \[=g(x)+[\overline{J}_{[x,\widehat{x}]}]^{+}(z-x)+[\overline{J}_{[x, \widehat{x}]}]^{-}(z-x)\] \[\leq g(x)+[\overline{J}_{[x,\widehat{x}]}]^{+}(\widehat{x}-x)= \overline{\mathsf{G}}^{\mathrm{jac}}(x,\widehat{x})\] where the first inequality holds because \(z-x\geq\mathbb{O}_{n}\), the second equality holds by \(\overline{J}_{[x,\widehat{x}]}=[\overline{J}_{[x,\widehat{x}]}]^{+}+[ \overline{J}_{[x,\widehat{x}]}]^{-}\), and the last inequality holds because \(z-x\leq\widehat{x}-x\) and \(z-x\geq\mathbb{O}_{n}\). Similarly, one can show that, for every \(z\in[x,\widehat{x}]\), \(g(z)\geq g(x)+[\underline{J}_{[x,\widehat{x}]}]^{-}(\widehat{x}-x)=\underline{ \mathsf{G}}^{\mathrm{jac}}(x,\widehat{x})\), completing the proof. **Remark 1**.: (The role of corner points) The proof of Proposition 1 is based on Taylor expansion of \(g\) around the corner point \(x\). The proposition extends straightforwardly to the Taylor expansion of \(g\) around other corner points, i.e., around any point \(y\) such that \(y_{i}\in\{x_{i},\widehat{x}_{i}\}\), resulting in different inclusion functions. Both the Jacobian-based cornered inclusion function (Proposition 1) and the Jacobian-based centered inclusion function [10, SS2.4] are obtained using the Taylor expansion of the original function. In general, they are not comparable (cf. Example 1 and Table I). However, for functions that are monotone in their entries, the Jacobian-based cornered inclusion function will lead to the minimal inclusion function while the Jacobian-based centered inclusion function is often non-minimal. Figure 2 provides a pictorial comparison between the minimal, the centered, and the cornered inclusion functions. The accuracy of the Jacobian-based cornered inclusion function can be improved at a cost of a slightly more complicated formulation using mixed differentiation in the same way that Fig. 1: **Left:** npinterval is used to generate interval approximations for a function \(g(x_{1},x_{2})=[(x_{1}+x_{2})^{2},4\sin((x_{1}-x_{2})/4)]^{\top}\) using two different natural inclusion functions. Blue: using the inclusion functions for elementary functions \(x+x^{2}\) and \(x\mapsto\sin(x)\) in [41, Appendix A, Table I], \(\mathrm{G}^{\mathrm{recr}}\) rewriting \(g(x_{1},x_{2})=[x_{2}^{2}+2x_{1}x_{2}+x_{2}^{2},4\sin(x_{1}/4)\cos(x_{2}/4)-4 \cos(x_{1}/4)\sin(x_{2}/4)]^{\top}\) and obtains a different natural inclusion function based on composition of elementary inclusion functions in [41, Appendix A, Table I]. The approximations are generated using the initial set \([-1,1]\times[-1,1]\) and 2000 uniformly sampled outputs are shown in red. **Right:** the same function is analyzed, with the same two natural inclusion functions, but the initial set is partitioned into 1024 uniform sections, and the union of the interval approximations are shown. the Jacobian-based centered inclusion function is improved with the mixed-centered inclusion function [10, SS2.4.4]. The idea is to use a step-by-step differentiation of the function with respect to each variable. **Proposition 2** (Mixed Jacobian-based cornered inclusion function).: _Given a continuously differentiable function \(g:\mathbb{R}^{n}\to\mathbb{R}^{m}\) such that \(Dg(z)\in[\underline{\underline{I}}_{[x,\widehat{x}]},\overline{\underline{J}} _{[x,\widehat{x}]}]\), for every \(z\in[x,\widehat{x}]\). The function \(\mathsf{G}^{\mathrm{lac-m}}:\mathcal{T}_{2\geq 0}^{2n}\to\mathcal{T}_{20}^{2n}\) defined by_ \[\mathsf{G}^{\mathrm{jac-m}}(x,\widehat{x})=\begin{bmatrix}-[\underline{M}]^{- }&[\underline{M}]^{-}\\ -[\overline{M}]^{+}&[\overline{M}]^{+}\end{bmatrix}\begin{bmatrix}x\\ \widehat{x}\end{bmatrix}+\begin{bmatrix}g(x)\\ g(x)\end{bmatrix}\] _is an inclusion function for \(g\), where the \(i\)th columns of \(\underline{M}\) and \(\overline{M}\) are defined by_ \[\underline{M}_{i}=(\underline{J}_{[x,\widehat{x}[h_{i},i]}))_{i},\qquad \overline{M}_{i}=(\overline{J}_{[x,\widehat{x}[h_{i},i]}))_{i},\] _with \(R_{i}=\{i+1,\ldots,n\}\), for every \(i\in\{1,\ldots,n\}\). Moreover, for every \(x\leq z\leq\widehat{x}\), we have_ \[\underline{\mathsf{G}}^{\mathrm{jac}}(x,\widehat{x})\leq\underline{\mathsf{G} }^{\mathrm{jac-m}}(x,\widehat{x}),\qquad\overline{\mathsf{G}}^{\mathrm{jac- m}}(x,\widehat{x})\leq\overline{\mathsf{G}}^{\mathrm{jac}}(x,\widehat{x}).\] Proof.: Since \(g\) is continuously differentiable, for every \(z\in[x,\widehat{x}]\), we have \(g(z_{[R_{1};x]})=g(x)+\int_{0}^{1}D_{x_{1}}g(tz_{[R_{1};x]}+(1-t)x)(z_{1}-x_{ 1})dt\). Thus, for every \(x\in[x,\widehat{x}]\), \(g(z_{[R_{1};x]})\leq g(x)+\overline{J}_{[x,\widehat{x}[h_{1},i]}(z_{1}-x_{1}) \leq g(x)+[\overline{J}_{[x,\widehat{x}[h_{1},i]}]^{+}(\widehat{x}_{1}-x_{1}).\) where the first inequality holds because \(z_{1}-x_{1}\geq\mathbb{0}_{n}\) and the second inequality holds because \(z_{1}-x_{1}\leq\widehat{x}_{1}-x_{1}\) and \(z_{1}-x_{1}\geq\mathbb{0}_{n}\). By successively applying the above procedure on \(g(z_{[R_{1};x]})\), one can show that \(g(z)\leq\underline{\mathsf{G}}^{\mathrm{jac}}(x,\widehat{x})\). Similarly, one can show that \(g(z)\geq\overline{\mathsf{G}}^{\mathrm{jac}}(x,\widehat{x})\) and thus \(\mathsf{G}^{\mathrm{jac}}\) is an inclusion function for \(g\). Finally, one can show that \(\underline{J}_{[x,\widehat{x}]}\leq\underline{M}\) and \(\overline{M}\leq\overline{J}_{[x,\widehat{x}]}\). This implies that \(-[\underline{M}]^{-}x+[\underline{M}]^{-}\widehat{x}\leq-[\underline{J}_{[x, \widehat{x}]}^{-}x+[\overline{J}_{[x,\widehat{x}]}^{-}\widehat{x}.\) As a result \(\underline{\mathsf{G}}^{\mathrm{jac}}(x,\widehat{x})\leq\underline{\mathsf{G} }^{\mathrm{jac-m}}(x,\widehat{x})\). Similarly, one can show that \(\overline{\mathsf{G}}^{\mathrm{jac-m}}(x,\widehat{x})\leq\overline{\mathsf{G }}^{\mathrm{jac}}(x,\widehat{x})\). **Example 1** (Cornered inclusion functions).: Consider the function \(f:\mathbb{R}^{2}\to\mathbb{R}^{2}\) defined by \(f(x_{1},x_{2})=\begin{bmatrix}(x_{1}+x_{2})^{2}\\ x_{1}+x_{2}+2x_{1}x_{2}\end{bmatrix}\). We compute the natural inclusion function, the (mixed) Jacobian-based cornered inclusion function, and the (mixed) Jacobian-based centered inclusion function for \(f\) on the interval \([-0.1,0.1]\times[-0.1,0.1]\). The results are shown in Table I, for runtimes averaged over \(10\,000\) runs. We observe that the output interval estimated by the mixed Jacobian-based centered (cornered) is tighter than the interval obtained from the Jacobian-based centered (cornered) inclusion function. This observation is consistent with the comparison between mixed and non-mixed Jacobian-based cornered inclusion functions in Proposition 2. However, there is generally no ranking between other methods, as each can perform better in different scenarios. Decomposition-based inclusion functionsAnother approach for constructing inclusion functions is by decomposing the function into the sum of increasing and decreasing parts [43, 15]. This separation is often realized using a decomposition function. **Definition 2** (Decomposition function).: Given a function \(g:\mathbb{R}^{n}\to\mathbb{R}^{m}\), a _decomposition function_ for \(g\) is a map \(d:\mathcal{T}^{2n}\to\mathbb{R}^{m}\) that satisfies 1. \(g(x)=d(x,x)\), for every \(x\in\mathbb{R}^{n}\); 2. \(d(x,y)\leq d(\widehat{x},y)\), for every \(y\in\mathbb{R}^{n}\) and every \(x\leq\widehat{x}\); 3. \(d(x,\widehat{y})\leq d(x,y)\), for every \(x\in\mathbb{R}^{n}\) and every \(y\leq\widehat{y}\). One can show that every continuous function has at least one decomposition function. Given a map \(g:\mathbb{R}^{n}\to\mathbb{R}^{m}\), we define the tight decomposition function for \(g\) as the mapping \(d^{\mathrm{tight}}:\mathcal{T}^{2n}\to\mathbb{R}^{2m}\) given by \[d^{\mathrm{tight}}_{i}(x,\widehat{x})=\begin{cases}\min_{z\in[x,\widehat{x}]}g _{i}(z)&x\leq\widehat{x}\\ \max_{z\in[x,\widehat{x}]}g_{i}(z)&\widehat{x}\leq x\end{cases} \tag{8}\] for every \(i\in\{1,\ldots,n\}\). In general, the decomposition function for function \(g\) is not unique. The next theorem, whose proof is straightforward, shows how to construct inclusion functions from decomposition functions. **Proposition 3** (Decomposition-based inclusion functions).: _Consider a map \(g:\mathbb{R}^{n}\to\mathbb{R}^{m}\) with a decomposition function \(d:\mathcal{T}^{2n}\to\mathbb{R}^{m}\). Then, the following statements hold:_ 1. _the map_ \(\mathsf{G}^{d}:\mathcal{T}_{\geq 0}^{2n}\to\mathbb{R}^{2m}\) _defined by_ \[\mathsf{G}^{d}(x,\widehat{x})=\begin{bmatrix}d(x,\widehat{x})\\ d(\widehat{x},x)\end{bmatrix},\quad\text{ for all }x\leq\widehat{x}\] _is a thin monotone inclusion function for_ \(g\)_._ 2. _the mapping_ \(d^{\mathrm{tight}}\) _defined in (_8_) is a decomposition function for_ \(g\) _and_ \[\mathsf{G}^{\min}(x,\widehat{x})=\begin{bmatrix}d^{\mathrm{tight}}(x,\widehat{ x})\\ d^{\mathrm{tight}}(\widehat{x},x)\end{bmatrix},\quad\text{ for all }x\leq\widehat{x},\] _where_ \(\mathsf{G}^{\min}\) _is the minimal inclusion function for_ \(g\) Fig. 2: Pictorial comparison between the minimal (equation (7)), the Jacobian-based centered ([10, §2.4.3], and the Jacobian-based cornered (Proposition 1) inclusion functions for \(f(x)=x^{2}\) and \(f(x)=x^{3}\) on the interval \([-1,1]\). Note that, for the monotone function \(f(x)=x^{3}\), the intersection of the two Jacobian-based cornered inclusion functions (shown by blue and red dashed lines) leads to the minimal inclusion function. **Remark 2** (Comparison with the literature).: For a vector field \(f:\mathbb{R}^{n}\rightarrow\mathbb{R}^{n}\), the decomposition function has already been studied in mixed monotone theory (cf. [44, 16, Definition 2], [45, Definition 4], and [46]). Definition 2 extends this classical notion to arbitrary functions. Theorem 3(ii) shows that the minimal inclusion function, defined by equation (7), is a decomposition-based inclusion function. Moreover, the tight decomposition function \(d^{\rm tight}\) in equation (8) coincides with the tight decomposition function in [47, Definition 2]. One can combine two inclusion functions to obtain another inclusion function with tighter estimates for the output of the original function. **Proposition 4** (Intersection of inclusion functions).: _Given a map \(g:\mathbb{R}^{n}\rightarrow\mathbb{R}^{m}\) with two inclusion functions \(\mathsf{G}_{1}=\left[\frac{\mathsf{G}_{1}}{\mathsf{G}_{1}}\right]:\mathcal{T} _{\geq 0}^{2n}\rightarrow\mathcal{T}_{\geq 0}^{2m}\) and \(\mathsf{G}_{2}=\left[\frac{\mathsf{G}_{2}}{\mathsf{G}_{2}}\right]:\mathcal{T} _{\geq 0}^{2n}\rightarrow\mathcal{T}_{\geq 0}^{2m}\). Define the mapping \(\mathsf{G}_{1}\wedge\mathsf{G}_{2}=\left[\frac{\mathsf{G}_{1}\wedge\mathsf{G }_{2}}{\mathsf{G}_{1}\wedge\mathsf{G}_{2}}\right]:\mathcal{T}_{\geq 0}^{2n} \rightarrow\mathcal{T}_{\geq 0}^{2m}\) by_ \[[\underline{\mathsf{G}}_{1}\wedge\mathsf{G}_{2}](x,\widehat{x}) =\max\{\mathsf{G}_{1}(x,\widehat{x}),\mathsf{G}_{2}(x,\widehat{x})\},\] \[[\overline{\mathsf{G}}_{1}\wedge\overline{\mathsf{G}}_{2}](x, \widehat{x}) =\min\{\overline{\mathsf{G}}_{1}(x,\widehat{x}),\overline{\mathsf{G }}_{2}(x,\widehat{x})\}.\] _Then \(\mathsf{G}_{1}\wedge\mathsf{G}_{2}\) is an inclusion function for \(g\) and it provides over-approximations of the output of \(g\) which are tighter than both \(\mathsf{G}_{1}\) and \(\mathsf{G}_{2}\)._ Proof.: Note that both \(\mathsf{G}_{1}\) and \(\mathsf{G}_{2}\) are inclusion functions for \(g\). Thus, for every \(x\leq z\leq\widehat{x}\), we have \(\mathsf{G}_{1}(x,\widehat{x})\leq g(z)\) and \(\mathsf{G}_{2}(x,\widehat{x})\leq g(z)\). This implies that \(\max\{\underline{\mathsf{G}}_{1}(x,\widehat{x}),\underline{\mathsf{G}}_{2}(x,\widehat{x})\}=|\underline{\mathsf{G}}_{1}\wedge\underline{\mathsf{G}}_{2} |(x,\widehat{x})\leq g(z)\). Similarly, one can show that \(g(z)\leq[\overline{\mathsf{G}}_{1}\wedge\overline{\mathsf{G}}_{2}](x, \widehat{x})\). ### _Convergence of inclusion functions_ We now define the convergence rate of an inclusion function which can be used to capture the accuracy of the interval estimations. **Definition 3** (Convergence rate of inclusion functions).: Consider the mapping \(g:\mathbb{R}^{n}\rightarrow\mathbb{R}^{m}\) with an inclusion function \(\mathsf{G}=\left[\frac{\mathsf{G}}{\mathsf{G}}\right]:\mathcal{T}_{\geq 0}^{2n} \rightarrow\mathcal{T}_{\geq 0}^{2m}\). The rate of convergence of \(\mathsf{G}\) is the largest \(\alpha\in\mathbb{R}_{\geq 0}\cup\{\infty\}\) such that \[\|\overline{\mathsf{G}}(x,\widehat{x})-\underline{\mathsf{G}}(x,\widehat{x})\|_{\infty}-\max_{z,y\in[x,\widehat{x}]}\|g(z)-g(y)\|_{\infty}\] \[\leq\beta\|\widehat{x}-x\|_{\infty}^{\alpha} \tag{9}\] for some \(\beta\in\mathbb{R}_{\geq 0}\) and for every \(x\leq\widehat{x}\). Roughly speaking, the rate of convergence of an inclusion function \(\mathsf{G}\) shows how accurately it estimates the range of the original function \(g\). Indeed, for the minimal inclusion function, the interval \([\underline{\mathsf{G}}(x,\widehat{x}),\overline{\mathsf{G}}(x,\widehat{x})]\) is the tightest interval containing \(g([x,\widehat{x}]]\). Thus the left hand side of inequality (9) is always zero and the rate of convergence of the minimal inclusion function is \(\alpha=\infty\). It is shown that, in general, the convergence rate of the natural inclusion functions is \(\alpha=1\)[40, Lemma 4.1] and the convergence rate of the Jacobian-based inclusion functions are \(\alpha=2\)[10, SS2.4.5]. ### _Inclusion functions for Neural Networks_ Given a neural network \(N\) of the form (4) and any interval \([y,\widehat{y}]\subseteq\mathbb{R}^{n}\), as described in the sequel, our framework proposes using existing neural network verification algorithms to construct a \([y,\widehat{y}]\)-localized inclusion function of the form \(\mathsf{N}_{[y,\widehat{y}]}=\left[\frac{\mathsf{N}_{[y,\widehat{y}]}}{ \mathsf{N}_{[y,\widehat{y}]}}\right]:\mathcal{T}_{\geq 0}^{2n}\rightarrow\mathcal{T}_{ \geq 0}^{2p}\) for \(N\) satisfying \[\underline{\mathsf{N}}_{[y,\widehat{y}]}(x,\widehat{x})\leq N(x)\leq\overline {\mathsf{N}}_{[y,\widehat{y}]}(x,\widehat{x}), \tag{10}\] for any \(x\in[x,\widehat{x}]\subseteq[y,\widehat{y}]\). A large number of the existing neural network verification algorithms can provide bounds of the form (10) for the output of the neural networks, including CROWN [25], LipSDP [24], and IBP [23]. In particular, some neural network verification algorithms can provide _affine_\([y,\widehat{y}]\)-localized inclusion functions for \(N\). Examples of these neural network verification algorithms include CROWN and its variants [25]. Given an interval \([y,\widehat{y}]\), these algorithms provide a tuple \((\underline{C},\overline{C},\underline{d},\overline{d})\) defining affine upper and lower bounds for the output of the neural network \[\underline{C}(y,\widehat{y})x+\underline{d}(y,\widehat{y})\leq N(x)\leq \overline{C}(y,\widehat{y})x+\overline{d}(y,\widehat{y}), \tag{11}\] for every \(x\in[y,\widehat{y}]\). Using these linear bounds, we can construct the affine \([y,\widehat{y}]\)-localized inclusion function for \(N\): \[\underline{\mathsf{N}}_{[y,\widehat{y}]}(x,\widehat{x})=[\underline{C}(y, \widehat{y})]^{+}x+[\underline{C}(y,\widehat{y})]^{-}\widehat{x}+\underline{d}(y,\widehat{y}), \tag{12}\] \[\overline{\mathsf{N}}_{[y,\widehat{y}]}(x,\widehat{x})=[\overline{C} (y,\widehat{y})]^{+}\widehat{x}+[\overline{C}(y,\widehat{y})]^{-}x+\overline{d} (y,\widehat{y})\] for any \([x,\widehat{x}]\subseteq[y,\widehat{y}]\). **Remark 3**.: 1. _(Computational complexity):_ the computational complexity of finding the \([y,\widehat{y}]\)-localized inclusion function \(\mathsf{N}_{[y,\widehat{y}]}=\left[\frac{\mathsf{N}_{[y,\widehat{y}]}}{ \mathsf{N}_{[y,\widehat{y}]}}\right]\) depends on the neural network verification algorithm. For instance, for a neural network with \(k\)-layer and \(N\) neurons per layer, the computational complexity of CROWN [25] in finding the bounds of the form (10) is \(\mathcal{O}(k^{2}N^{3})\). 2. _(Inclusion function):_ Since the \([y,\widehat{y}]\)-localized inclusion function \(\mathsf{N}_{[y,\widehat{y}]}=\left[\frac{\mathsf{N}_{[y,\widehat{y}]}}{ \mathsf{N}_{[y,\widehat{y}]}}\right]\) can be obtained for every \([y,\widehat{y}]\), we can define an inclusion function \(\mathsf{N}=\left[\frac{\mathsf{N}}{\mathsf{N}}\right]\) for the neural network \(N\) by \(\mathsf{N}(x,\widehat{x})=\mathsf{N}_{[x,\widehat{x}]}(x,\widehat{x})\), for all \(x\leq\widehat{x}\). ## V Interval Reachability of Dynamical Systems In this section, we study reachability of the dynamical system (1) using interval analysis. Our key idea is to embed the original dynamical system (1) into an _embedding system_ on \(\mathbb{R}^{2n}\) and use trajectories of the embedding system to study the propagation of the state bounds with time. Our main goal is to use the notion of inclusion function (cf. Definition 1) to design embedding systems for dynamical systems. Consider the dynamical system (1) with an inclusion function \(\mathsf{F}=\left[\frac{\mathsf{F}}{\mathsf{F}}\right]:\mathcal{T}_{\geq 0}^{2n} \times\mathcal{T}_{\geq 0}^{2q}\rightarrow\mathcal{T}_{\geq 0}^{2n}\) for \(f\). We define the associated _embedding system_ on \(\mathbb{R}^{2n}\): \[\dot{x}_{i} =\mathsf{E}_{i}(x,\widehat{x}_{[i:x]},w,\widehat{w}),\] \[\dot{\widehat{x}}_{i} =\overline{\mathsf{F}}_{i}(x_{[i:\widehat{x}]},\widehat{x},w, \widehat{w}), \tag{13}\] for every \(i\in\{1,\ldots,n\}\). For instance, using the minimal inclusion function \(\mathsf{F}^{\min}=\left[\frac{\mathsf{F}^{\min}}{\mathsf{F}^{\min}}\right]\) for \(f\), the associated embedding system is given by: \[\dot{x}_{i} =\min_{\begin{subarray}{c}z\in[x,\overline{x}],\ z_{i}=x_{i},\\ u\in[w,\overline{w}]\end{subarray}}f_{i}(z,u),\] \[\dot{\bar{x}}_{i} =\max_{\begin{subarray}{c}z\in[x,\overline{z}],\ z_{i}=\bar{z} _{i},\\ u\in[w,\overline{w}]\end{subarray}}f_{i}(z,u), \tag{14}\] for every \(i\in\{1,\ldots,n\}\). Given the disturbance set \(\mathcal{W}=[\underline{w},\overline{w}]\) and the initial set \(\mathcal{X}_{0}=[\underline{x}_{0},\overline{x}_{0}]\), one can use a single trajectory of the embedding system (13) to obtain over-approximations of reachable sets of the system (1). Moreover, it can be shown that among all the inclusion functions used for constructing the embedding system (13), the embedding system obtained from the minimal inclusion function (i.e., the dynamical system (14)) provides the tightest reachable set over-approximations at any time \(t\in\mathbb{R}_{\geq 0}\). **Proposition 5** (Reachability using embedding systems).: _Consider the dynamical system (1) with the disturbance set \([\underline{w},\overline{w}]\) and the initial set \(\mathcal{X}_{0}=[\underline{x}_{0},\overline{x}_{0}]\). Suppose that \(\mathsf{F}=\left[\frac{\mathsf{F}}{\mathsf{F}}\right]\) is an inclusion function for \(f\), and \(t\mapsto\left[\frac{x}{\overline{x}(t)}\right]\) and \(t\mapsto\left[\frac{x}{\overline{x}^{\min}(t)}\right]\) are the trajectories of embedding systems (13) and (14), starting from \(\left[\frac{x_{0}}{\overline{x}_{0}}\right]\) with fixed disturbance \(\left[\frac{w}{\overline{w}}\right]=[\frac{w}{\overline{w}}]\). Then, for every \(t\in\mathbb{R}_{\geq 0}\), we have_ \[\mathcal{R}_{f}(t,[\underline{x}_{0},\overline{x}_{0}],[\underline{w}, \overline{w}])\subseteq[\underline{x}^{\min}(t),\overline{x}^{\min}(t)] \subseteq[\underline{x}(t),\overline{x}(t)].\] Proof.: We first show that the dynamical system (14) is a monotone dynamical system with respect to the southeast order \(\leq_{\mathrm{SE}}\). Let \(\left[\frac{x}{\overline{z}}\right]\leq_{\mathrm{SE}}\left[\frac{y}{\overline {y}}\right]\) be such that \(x_{i}=y_{i}\) and let \(\left[\frac{w}{\overline{w}}\right]\leq_{\mathrm{SE}}\left[\frac{v}{\overline {v}}\right]\). Then, we have \([y,\widehat{y}]\subseteq[x,\widehat{x}]\) and \([v,\widehat{v}]\subseteq[w,\widehat{w}]\), and we can compute \[\mathsf{E}^{\min}_{i}(x,\widehat{x},w,\widehat{w}) =\min_{\begin{subarray}{c}z\in[x,\overline{z}],\ z_{i}=x_{i},\\ u\in[w,\overline{w}]\end{subarray}}f_{i}(z,u)\] \[\leq\min_{\begin{subarray}{c}z\in[y,\widehat{y}],\ z_{i}=y_{i},\\ u\in[v,\overline{v}]\end{subarray}}f_{i}(z,u)=\mathsf{E}^{\min}_{i}(y, \widehat{y},v,\widehat{v}),\] for every \(i\in\{1,\ldots,n\}\). Similarly, let \(\left[\frac{x}{\overline{z}}\right]\leq_{\mathrm{SE}}\left[\frac{y}{\overline {y}}\right]\) be such that \(\widehat{x}_{i}=\widehat{y}_{i}\) and let \(\left[\frac{w}{\overline{w}}\right]\leq_{\mathrm{SE}}\left[\frac{v}{\overline {v}}\right]\). Then, we have \([y,\widehat{y}]\subseteq[x,\widehat{x}]\) and \([v,\widehat{v}]\subseteq[w,\widehat{w}]\), and similar reasoning implies \(\overline{\mathsf{F}}^{\min}_{i}(x,\widehat{x},w,\widehat{w})\leq\overline{ \mathsf{F}}^{\min}_{i}(y,\widehat{y},v,\widehat{v})\) for every \(i\in\{1,\ldots,n\}\). As a result, the embedding system (14) is continuous-time monotone with respect to \(\leq_{\mathrm{SE}}\). Let \(x_{0}\in[\underline{x}_{0},\overline{x}_{0}]\) and \(u\in[\underline{w},\overline{w}]\) and \(t\mapsto x_{u}(t)\) be the trajectory of the system (1) starting from \(x_{0}\) with disturbance \(u\). Note that \(t\mapsto\left[\frac{x_{u}(t)}{x_{u}(t)}\right]\) is a solution of the embedding system (14) with the initial condition \(\left[\frac{x_{0}}{x_{0}}\right]\) and the disturbance \(\left[\frac{u}{u}\right]\). Moreover, we know that \(\left[\frac{x_{0}}{x_{0}}\right]\leq_{\mathrm{SE}}\left[\frac{x_{0}}{x_{0}}\right]\) and \(\left[\frac{w}{\overline{w}}\right]\leq_{\mathrm{SE}}\left[\frac{u}{u}\right]\). Therefore, by monotonicity of the embedding system (14) with respect to \(\leq_{\mathrm{SE}}\), we get \(\left[\frac{x^{\min}(t)}{x^{\min}(t)}\right]\leq_{\mathrm{SE}}\left[\frac{x_{ u}(t)}{x_{u}(t)}\right]\), for every \(t\in\mathbb{R}_{\geq 0}\). This implies that \(\mathcal{R}_{f}(t,[\underline{x}_{0},\overline{x}_{0}],[\underline{w}, \overline{w}])\subseteq[\underline{x}^{\min}(t),\overline{x}^{\min}(t)]\), for every \(t\in\mathbb{R}_{\geq 0}\). On the other hand, \(\mathsf{F}^{\min}\) is the minimal inclusion function for \(f\) and therefore, for every \(x\leq\widehat{x}\) and every \(w\leq\widehat{w}\), we have \(\left[\frac{\mathsf{F}(x,\widehat{x},w,\widehat{w})}{\mathsf{F}(x,\widehat{x}, w,\widehat{w})}\right]\leq_{\mathrm{SE}}\left[\frac{\mathsf{F}^{\min}(x, \widehat{x},w,\widehat{w})}{\mathsf{F}^{\min}(x,\widehat{x},w,\widehat{w})}\right]\). Thus, for every \(i\in\{1,\ldots,n\}\), every \(x\leq\widehat{x}\), and every \(w\leq\widehat{w}\), \[\mathsf{E}_{i}(x,\widehat{x}_{[i:x]},w,\widehat{w})\leq\min_{ \begin{subarray}{c}z\in[\underline{x}],\ z_{i}=x_{i},\\ \xi\in[w,\widehat{w}]\end{subarray}}f_{i}(z,\xi),\] \[\mathsf{\overline{F}}_{i}(x_{[i:\widehat{x}]},\widehat{x},w, \widehat{w})\geq\max_{\begin{subarray}{c}z\in[x,\overline{z}],\ z_{i}=\bar{z} _{i},\\ \xi\in[w,\widehat{w}]\end{subarray}}f_{i}(z,\xi).\] Now, we can use the classical monotone comparison Lemma [48, Theorem 3.8.1] to obtain \(\left[\frac{x}{\overline{x}(t)}\right]\leq_{\mathrm{SE}}\left[\frac{\mathsf{F} ^{\min}_{i}(t)}{x^{\min}(t)}\right]\), for every \(t\in\mathbb{R}_{\geq 0}\). This implies that \([\underline{x}^{\min}(t),\overline{x}^{\min}(t)]\subseteq[\underline{x}(t), \overline{x}(t)]\), for every \(t\in\mathbb{R}_{\geq 0}\), and completes the proof. **Remark 4** (Comparison with the literature).: 1. It is straightforward to extend Proposition 5 to the case when the mapping \(\mathsf{F}\) is a \([y,\widehat{y}]\times\mathbb{R}^{q}\)-localized inclusion function for \(f\). In this setting, the results of Proposition 5 hold as long as we have \([\underline{x}(t),\overline{x}(t)]\subseteq[y,\widehat{y}]\). 2. Proposition 5 can be considered as a generalization of [49, Proposition 6] and [18, Proposition 1]. Indeed, in the special case that \(\mathsf{F}\) is a decomposition-based inclusion function constructed from the decomposition function \(d\), one can recover the embedding system \[\dot{x}_{i} =d(x,\widehat{x}_{[i:x]},w,\widehat{w}),\] \[\dot{\bar{x}}_{i} =d(\widehat{x},x_{[i:\widehat{x}]},\widehat{w},w)\] for every \(i\in\{1,\ldots,n\}\). This embedding system is identical to [49, Equation (7)] and [18, Equation (3)]. We highlight that this extension is crucial for our framework as the inclusion functions that we obtain for learning-based systems are neither thin nor decomposition-based. 3. Proposition 5 can alternatively be proved using [12, Theorem 2]. However, our proof of Proposition 5 is different in that it uses monotone system theory [50, 51] and classical monotone comparison Lemma [48, Theorem 3.8.1]. Indeed, compared to [12, Theorem 2], our proof techniques allow to compare accuracy of different over-approximations of reachable sets. We now study the accuracy of the over-approximations provided in Proposition 5. We first introduce the convergence rate of an embedding system for approximating the reachable set of the dynamical system (1). **Definition 4** (Convergence rate of embedding systems).: Consider the dynamical system (1) with the embedding system (13). Then the convergence rate of the embedding system (13) is the largest value of \(\alpha\in\mathbb{R system (13) and the convergence rate of its associated inclusion function \(\mathsf{F}\) (as in Definition 3)? In the special case when \(f\) is a discrete-time monotone vector field, one can choose the inclusion function \(\mathsf{F}(\underline{x},\overline{x})=\left[\begin{smallmatrix}f(\underline{x} )\\ f(\underline{x})\end{smallmatrix}\right]\) for \(f\). In this case, it can be shown that the convergence rate of both the embedding system and the inclusion function are the same and equal to \(\alpha=\infty\). Given a Lipschitz and monotone inclusion function \(\mathsf{F}\) for \(f\), one can show that the convergence rate of the embedding system (13) satisfies \(\alpha\geq 1\)[40, Theorem 4.1]. However, in general, the inclusion function \(\mathsf{F}\) does not reveal more information about the convergence rate of the embedding system (13). Even when the convergent rate of the inclusion function \(\mathsf{F}\) is \(\alpha=\infty\), i.e., the embedding system is given by equations (14), one might get a convergence rate of \(\alpha=1\) for the embedding system. ## VI Interval reachability of learning-based systems In this section, we develop a computationally efficient framework for studying reachability of neural network controlled systems. The key idea of our approach is to employ the framework of Section V and to capture the interactions between the open-loop system and the neural network controller using a suitable closed-loop embedding system. However, finding a closed-loop embedding system (or, equivalently, computing an inclusion function for the closed-loop vector field) using the approaches in Section IV is often not tractable, as the neural networks can have a large number of parameters. Instead, we propose to use a compositional approach based on an inclusion function for the open-loop dynamics and an inclusion function for the neural network controller. We develop two different approaches for designing the closed-loop inclusion function from the open-loop vector field \(f\) and the localized inclusion function of the neural network. First, we propose an _interconnection-based_ approach where the key idea is to consider the closed-loop embedding system as the feedback interconnection of the open-loop embedding system and the neural network inclusion function. This method, as elaborated below, can capture some of the stabilizing effects of the neural network controller by approximating the input-output behavior of the neural network separately on the faces of a hyperrectangle. Thus, we consider this approach a semi-input-output approach. The advantages of the interconnection-based approach are its computational speed and that it is amenable to any open-loop inclusion function. Second, we propose an _interaction-based_ approach where the key idea is to use the Jacobian-based cornered inclusion function (developed in Proposition 1) to more fully capture the interaction between the neural network controller and the system. The advantages of this approach are reduced conservatism compared to the interconnection-based inclusion function while retaining much of the computational efficiencies of interval reachability analysis. Our methods are applicable to general nonlinear systems with neural network controllers. Nonetheless, the essence of our approaches, and their advantages over a naive input-output approach, are evident even in the simple setting of a linear system with a linear feedback controller, as shown in the following illustrative example. **Example 2** (Invariant intervals).: Consider the control system \(\dot{x}=Ax+Bu\) where \(x\in\mathbb{R}^{2}\) and \(A=\left[\begin{smallmatrix}-2&1\\ 1&-2\end{smallmatrix}\right]\) and \(B=\left[\begin{smallmatrix}0\\ 1\end{smallmatrix}\right]\). Note that \(A\) is Hurwitz so the origin is the globally asymptotically stable equilibrium point of the open-loop system when \(u\equiv 0\). Consider a state feedback controller \(u=\pi(x)=Kx=k_{1}x_{1}+k_{2}x_{2}\) with \(k_{1}=k_{2}=-3\) designed to, _e.g._, achieve faster convergence to the origin. As a special case of reachability analysis, our goal is to characterize forward invariant intervals of the closed-loop system around the origin. We compare three different approaches for finding invariant intervals. _Naive input-output approach:_ this approach decouples the system from the controller and only uses knowledge of the output range of the controller. In particular, this approach seeks an interval \(S=[-\xi,\xi]\), \(\xi\in\mathbb{R}^{2}_{\geq 0}\) such that \(S\) is robustly forward invariant for the open loop system under any \(u\in\pi(S)\). However, such a robustly forward invariant set does not exist. By contradiction, suppose \(S=[-\xi,\xi]\) is forward invariant and consider the point \(x=\left[\begin{smallmatrix}0\\ \xi_{2}\end{smallmatrix}\right]\) on the boundary of this set and pick \(u=\pi(-x)=3\xi_{2}\in\pi(S)\), for which \(\dot{x}_{2}=-2\xi_{2}+u=\xi_{2}>0\) and the resulting trajectory immediately leaves \(S\). Despite the stability of the open-loop system and the stabilizing effect of the controller, this approach fails to capture the stability of the closed-loop system. _Interconnection-based approach:_ this approach also decouples the system from the controller and only assumes knowledge of the output of the controller to characterize forward invariant intervals \(S=[-\xi,\xi]\), for some \(\xi\in\mathbb{R}^{2}_{\geq 0}\). However, it considers the interconnection between the system and the controller on the edges of the interval \(S\). Let \(S^{-}_{1},S^{+}_{1},S^{-}_{2},S^{+}_{2}\) denote the edges of \(S\) defined by \(S^{\pm}_{i}=\{x\in S\mid x_{i}=\pm\xi_{i}\}\) for \(i\in\{1,2\}\). Then a sufficient condition for forward invariance of \(S\) is that \(\dot{x}_{i}\geq 0\) for every \(x\in S^{-}_{i}\), and \(\dot{x}_{i}\leq 0\) for every \(x\in S^{+}_{i}\). Note that, if \(\xi_{1}/\xi_{2}\geq\frac{1}{2}\), then we have \(\dot{x}_{1}\leq 0\) on \(S^{+}_{1}\) and we have \(\dot{x}_{1}\geq 0\) on \(S^{-}_{1}\). On \(S^{+}_{2}\), we have \(\dot{x}_{2}\in[-\xi_{1},\xi_{1}]-2\xi_{2}+u\) and \(u\in-3[-\xi_{1},\xi_{1}]-3\xi_{2}\). This implies that \(\dot{x}_{2}\in[4-\xi_{1},\xi_{1}]-5\xi_{2}\), and, therefore, we need \(\xi_{1}/\xi_{2}\leq\frac{5}{4}\) for \(\dot{x}_{2}\leq 0\). A similar condition is required to ensure \(\dot{x}_{2}\geq 0\) on \(S^{-}_{2}\). This implies that, using this interconnection-based approach, we certify \(S=[-\xi,\xi]\) is forward invariant for any \(\xi\in\mathbb{R}^{2}_{>0}\) satisfying \(\frac{1}{2}\leq\xi_{1}/\xi_{2}\leq\frac{5}{4}\). _Interaction-based approach:_ this approach uses the knowledge of the controller functional dependency \(\pi(x)=Kx\) and the open-loop dynamics to obtain the closed-loop system \(\dot{x}=(A+BK)x=\left[\begin{smallmatrix}-2&-2\\ -2&-5\end{smallmatrix}\right]x\). One can show that the interval \(S=[-\xi,\xi]\) is forward invariant for this closed-loop system for any \(\xi\in\mathbb{R}^{2}_{\geq 0}\) satisfying \(\frac{1}{2}\leq\xi_{1}/\xi_{2}\leq\frac{5}{2}\). Now, we develop a mathematical framework for reachability analysis of the learning-based closed-loop system (5). Given an open-loop system of the form (1), we use approaches developed in Section IV-B to construct an inclusion function \(\mathsf{F}^{\rm o}=\left[\begin{smallmatrix}\overline{\mathsf{F}}^{\rm o}\\ \overline{\mathsf{F}}^{\rm o}\end{smallmatrix}\right]:\mathcal{T}^{2n}_{\geq 0} \times\mathcal{T}^{2p}_{\geq 0}\times\mathcal{T}^{2q}_{\geq 0}\to\mathcal{T}^{2n}_{\geq 0}\) for the open-loop vector field \(f\). We also assume that we have access to a neural network inclusion function \(\mathsf{N}\) as developed in Section IV-D. We construct two classes of inclusion functions for the closed-loop vector field \(f^{c}\) in (5). ### _Interconnection-based approach_ In the first approach, which we refer to as interconnection-based approach, we obtain the closed-loop inclusion function from a feedback interconnection of the open-loop embedding system and the neural network inclusion function. **Theorem 2** (Closed-loop interconnection-based inclusion function).: _Consider the open-loop system (3) with an inclusion function \(\mathsf{F}^{\rm o}\) and a neural network controller of the form (4) with a \([y,\widehat{y}]\)-localized inclusion function \(\mathsf{N}_{[y,\widehat{y}]}=\left[\frac{\mathbbm{N}_{[y,\widehat{y}]}}{ \mathbbm{N}_{[y,\widehat{y}]}}\right]\). Then, the map \(\mathsf{F}^{\rm con}_{[y,\widehat{y}]}:\mathcal{T}^{2n}_{\geq 0}\times \mathcal{T}^{2q}_{\geq 0}\rightarrow\mathcal{T}^{2n}_{\geq 0}\) defined by_ \[\frac{\mathsf{F}^{\rm con}_{[y,\widehat{y}]}}{\mathsf{F}^{\rm con }_{[y,\widehat{y}]}}(x,\widehat{x},w,\widehat{w}) =\mathsf{\overline{F}}^{\rm o}(x,\widehat{x},\eta,\widehat{\eta},w, \widehat{w}) \tag{15}\] _is a \([y,\widehat{y}]\times\mathbb{R}^{q}\)-localized inclusion function for the closed-loop vector field \(f^{c}\), where_ \[\xi =\mathbbm{N}_{[y,\widehat{y}]}(x,\widehat{x}),\quad\widehat{\xi} =\overline{\mathsf{N}}_{[y,\widehat{y}]}(x,\widehat{x}),\] \[\eta =\overline{\mathsf{N}}_{[y,\widehat{y}]}(x,\widehat{x}),\quad \widehat{\eta}=\underline{\mathsf{N}}_{[y,\widehat{y}]}(x,\widehat{x}).\] Proof.: Let \(z\in[x,\widehat{x}]\subseteq[y,\widehat{y}]\) and \(v\in[w,\widehat{w}]\). Since \(\mathsf{N}_{[y,\widehat{y}]}=\left[\frac{\mathbbm{N}_{[y,\widehat{y}]}}{ \mathbbm{N}_{[y,\widehat{y}]}}\right]\) is a \([y,\widehat{y}]\)-localized inclusion function for the neural network controller \(N\), we have \(\underline{\mathsf{N}}_{[y,\widehat{y}]}(x,\widehat{x})\leq N(z)\leq\overline{ \mathsf{N}}_{[y,\widehat{y}]}(x,\widehat{x})\). Therefore, we can compute \(\mathsf{F}^{\rm con}_{[y,\widehat{y}]}(x,\widehat{x},w,\widehat{w})=\mathsf{ \underline{F}}^{\rm o}(x,\widehat{x},\xi,\xi,w,\widehat{w})\leq f(z,N(z),v)=f ^{c}(z,v)\), where the second inequality holds because \(\mathsf{F}^{\rm o}\) is an inclusion function for the open-loop vector field \(f\). Similarly, one can show that \(\overline{\mathsf{F}}^{\rm con}_{[y,\widehat{y}]}(x,\widehat{x},w,\widehat{w} )\geq f^{c}(z,v)\). This implies that \(\mathsf{F}^{\rm con}_{[y,\widehat{y}]}\) is a \([y,\widehat{y}]\)-localized inclusion function for \(f^{c}\). ### _Interaction-based approach_ The second approach, which we refer to as interaction-based approach, uses a Jacobian-based cornered inclusion function for the open-loop system and an affine neural network bound to capture the first order interaction between the neural network controller and the system. **Theorem 3** (Closed-loop interaction-based inclusion function).: _Consider the closed-loop system (5) and assume the open-loop vector field \(f\) is continuously differentiable and the neural network controller (4) satisfies affine bounds of the form (11) on the interval \([y,\widehat{y}]\). Assume that, for every \(z\in[x,\widehat{x}]\subseteq[y,\widehat{y}]\), every \(\xi\in[u,\widehat{u}]\), and every \(\eta\in[w,\widehat{w}]\),_ \[D_{\xi}f(z,\xi,\eta) \in[\underline{J}_{[x,\widehat{x}]},\overline{J}_{[x,\widehat{x}]}],\] \[D_{\xi}f(z,\xi,\eta) \in[\underline{J}_{[u,\widehat{u}]},\overline{J}_{[u,\widehat{u}]}],\] \[D_{\eta}f(z,\xi,\eta) \in[\underline{J}_{[u,\widehat{u}]},\overline{J}_{[w,\widehat{u}]}]. \tag{16}\] _Then, the map \(\mathsf{F}^{\rm act}_{[y,\widehat{y}]}:\mathcal{T}^{2n}_{\geq 0}\times \mathcal{T}^{2q}_{\geq 0}\rightarrow\mathcal{T}^{2n}_{\geq 0}\) defined by_ \[\mathsf{F}^{\rm act}_{[y,\widehat{y}]}(x,\widehat{x},w,\widehat{w})=\left[ \frac{[\underline{H}]^{+}-\underline{J}_{[x,\widehat{x}]}}{[\overline{H}]^{-} }-\overline{J}_{[x,\widehat{x}]},\overline{[\overline{H}]^{+}}\right]\left[ \frac{x}{\widehat{x}}\right]+L\left[\frac{w}{\widehat{w}}\right]+Q, \tag{17}\] _is a \([y,\widehat{y}]\times\mathbb{R}^{q}\)-localized inclusion function for the closed-loop vector field \(f^{c}\), where_ \[\frac{H}{H} =\underline{J}_{[x,\widehat{x}]}+[\underline{J}_{[u,\widehat{u}]}] ^{+}\underline{C}(y,\widehat{y})+[\underline{J}_{[u,\widehat{u}]}]^{-} \overline{C}(y,\widehat{y})\] \[\overline{H} =\overline{J}_{[x,\widehat{x}]}+[\overline{J}_{[u,\widehat{u}]}] ^{+}\overline{C}(y,\widehat{y})+[\overline{J}_{[u,\widehat{u}]}]^{-} \underline{C}(y,\widehat{y}),\] \[L =\left[\begin{smallmatrix}-[\underline{J}_{u,\widehat{u}]}]^{-} \underline{[J}_{u,\widehat{u}]}^{-}\\ -[\overline{J}_{[u,\widehat{u}]}]^{+}\overline{[J}_{[u,\widehat{u}]}]^{-} \end{smallmatrix}\right],\] \[Q =\left[\begin{smallmatrix}-\underline{J}_{u,\widehat{u}]}u+[ \underline{J}_{u,\widehat{u}]}u+\underline{d}(y,\widehat{y})+[\underline{J}_{u, \widehat{u}]}]^{-}\overline{d}(y,\widehat{y})+f(x,u,w)\\ -\overline{J}_{[u,\widehat{u}]}u+[\overline{J}_{[u,\widehat{u}]}]^{+} \overline{d}(y,\widehat{y})+[\overline{J}_{[u,\widehat{u}]}]^{-}\underline{d} (y,\widehat{y})+f(x,u,w)\end{smallmatrix}\right].\] Proof.: Let \(z\in[x,\widehat{x}]\) and \(\eta\in[w,\widehat{w}]\). Since \(f\) is continuously differentiable, the fundamental theorem of Calculus gives \[f^{c}(z,\eta) =f(z,N(z),\eta)=f(x,u,w)+M(z,u,w)(z-x)\] \[+P(z,u,w)(N(z)-u)+R(z,\eta,w)(\eta-w),\] where \(M(z,u,w)=\int_{0}^{1}D_{x}f(\tau z+(1-\tau)x,u,w)d\tau\), \(P(z,u,w)=\int_{0}^{1}D_{u}f(z,\tau N(z)+(1-\tau)u,w)d\tau\), and \(R(z,\eta,w)=\int_{0}^{1}D_{w}f(z,N(z),\tau\eta+(1-\tau)w)d\tau\). Using the bounds (16), we get \(M(z,u,w)\geq\underline{J}_{[x,\widehat{x}]}\), \(P(z,u,w)\geq\underline{J}_{[u,\widehat{u}]}\), and \(R(z,\eta,w)\geq\underline{J}_{[w,\widehat{w}]}\). Moreover, we have \(N(z)-u\geq 0_{p}\). Therefore, using the affine bounds (11) for the neural network, \(P(z,u,w)(N(z)-u)\geq[P(z,u,w)]^{+}(\underline{C}(y,\widehat{y})z+\underline{d}(y,\widehat{y})-u)+[P(z,u,w)]^{-}(\overline{C}(y,\widehat{y})z+\underline{d}(y,\widehat{y})-u)\). Using the fact that \(z-x\geq 0_{n}\) and \(\eta-w\geq 0_{q}\), we have \[f^{c}(z,\eta) \geq f(x,u,w)+M(z,u,w)(z-x)\] \[+[P(z,u,w)]^{+}(\underline{C}(y,\widehat{y})z+\overline{d}(y, \widehat{y})-u)\] \[+[P(z,u,w)]^{-}(\overline{C}(y,\widehat{y})z+\overline{d}(y, \widehat{y})-u)\] \[+R(z,\eta,w)(\eta-w)\] \[\geq\underline{H}z-\underline{J}_{[x,\widehat{x}]}x+\underline{J}_{[ w,\widehat{w}]}\eta-\underline{J}_{[w,\widehat{w}]}w\] \[+[\underline{J}_{[w,\widehat{w}]}]^{+}\underline{d}(y,\widehat{y})+[ \underline{J}_{[w,\widehat{w}]}]^{-}\overline{d}(y,\widehat{y})+f(x,u,w),\] where the second inequality follows from the Jacobian bounds. Now, we note that \(x\leq z\leq\widehat{x}\) and \(w\leq\eta\leq\widehat{w}\) and therefore \(\underline{H}z\geq[\underline{H}]^{+}x+[\underline{H}]^{+}\widehat{x}\) and expense. Second, as it is clear from the proof of Theorem 3, the Jacobian-based cornered inclusion function is particularly well-suited for integrating the neural network bounds into the closed-loop inclusion function and for studying the interaction between the system and the neural network controller. 2. _(Mixed Jacobian-based inclusion functions):_ Theorem 3 uses the Jacobian-based cornered inclusion function (as in Proposition 1) for the open-loop vector field \(f\). Alternatively, one can use the mixed Jacobian-based cornered inclusion function (as in Proposition 2) for the open-loop vector \(f\) and obtain a different class of inclusion functions for \(f^{c}\). This class of closed-loop inclusion functions can be obtained from (17) by replacing \(\underline{J}_{[x,\widehat{x}]},\overline{J}_{[x,\widehat{x}]},\underline{J}_ {[u,\widehat{u}]},\overline{J}_{[u,\widehat{w}]},\underline{J}_{[w,\widehat{ w}]}\), and \(\overline{J}_{[w,\widehat{w}]}\) with their counterparts \(\underline{M}_{[x,\widehat{x}]},\overline{M}_{[x,\widehat{x}]},\underline{M} _{[u,\widehat{u}]},\overline{M}_{[u,\widehat{w}]},\) and \(\overline{M}_{[w,\widehat{w}]}\) as defined in Proposition 2 and is demonstrated in the numerical experiments below. Our numerical results show that, in most cases, mixed Jacobian-based cornered inclusion functions significantly reduces the conservatism of the over-approximation as compared to their non-mixed counterparts. 3. _(Comparison):_ The interconnection-based approach provides a general and computationally efficient framework for constructing closed-loop inclusion functions. This approach can be applied using any inclusion function for the open-loop system and any inclusion function of the form (10) for the neural network. The computational efficiency of the interconnection-based approach is a direct consequence of its compositional structure. On the other hand, the interaction-based approach fully captures the first-order interaction between the system and the neural networks using a Jacobian-based decomposition. However, this approach requires affine bounds of the form (11) for the neural network and Jacobian bounds of the form (16) for the open-loop system. As a result, computing the closed-loop inclusion functions using the interaction-based approach is generally more computationally expensive. When the open-loop system (3) is linear, one can significantly simplify the expression for the closed-loop inclusion functions obtained from the interconnection-based and the interaction-based approaches. **Corollary 1** (Linear open-loop systems).: _Consider the closed-loop system (5) and assume that the open-loop vector field \(f\) is linear with the form \(f(x,u,w)=Ax+Bu+Dw\), where \(A\in\mathbb{R}^{n\times n}\), \(B\in\mathbb{R}^{n\times p}\) and \(D\in\mathbb{R}^{n\times q}\). Then the following statements hold:_ 1. _[label=()]_ 2. _using the minimal inclusion function for the open-loop vector field_ \(f\) _and affine neural network inclusion functions of the form (_12_), the closed-loop inclusion function_ \(\mathsf{F}^{\mathrm{con}}_{[y,\widehat{y}]}\) _defined in (_15_) is given by:_ \[\mathsf{F}^{\mathrm{con}}_{[y,\widehat{y}]} =\begin{bmatrix}[A]^{+}+[B^{+}\underline{C}+B^{-}\overline{C}]^{+ }&[A]^{+}-[B^{+}\underline{C}+B^{-}\overline{C}]^{-}\\ [A]^{+}+[B^{+}\overline{C}+B^{-}\underline{C}]^{-}&[A]^{+}+[B^{+}\overline{C} +B^{-}\underline{C}]^{+}\end{bmatrix}\begin{bmatrix}\frac{x}{2}\\ \frac{y}{2}\end{bmatrix}\] \[+\begin{bmatrix}D^{+}\ D^{-}\ \big{[}\frac{w}{2}\big{]}+ \begin{bmatrix}B^{+}\underline{d}+B^{-}\overline{d}\\ \frac{y}{2}\end{bmatrix}.\] (18) 3. _the inclusion function_ \(\mathsf{F}^{\mathrm{act}}_{[y,\widehat{y}]}\) _defined in (_17_) is given by_ \[\mathsf{F}^{\mathrm{act}}_{[y,\widehat{y}]} =\begin{bmatrix}[A]^{+}+B^{+}\underline{C}+B^{-}\overline{C}]^{+ }&[A]^{+}+B^{+}\underline{C}+B^{-}\overline{C}]^{-}\\ [A]^{+}+B^{+}\overline{C}+B^{-}\underline{C}]^{-}&[A]^{+}+B^{+}\overline{C}+B^ {-}\underline{C}]^{+}\end{bmatrix}\begin{bmatrix}\frac{x}{2}\\ \frac{y}{2}\end{bmatrix}\] \[+\begin{bmatrix}D^{+}\ D^{-}\ D^{+}\ \big{[}\frac{w}{2}\big{]}+ \begin{bmatrix}B^{+}\underline{d}+B^{-}\overline{d}\\ \frac{y}{2}\end{bmatrix}.\] (19) Proof.: Regarding part (i), it is easy to see that the minimal inclusion function of the linear open-loop vector field \(f\) is \[\mathsf{F}^{\mathrm{o}}(x,\widehat{x},u,\widehat{u},w,\widehat{w}) =\begin{bmatrix}A^{+}\ A^{-}\ A^{+}\ \big{[}\frac{x}{2}\big{]}+\begin{bmatrix}B^{+}\ B^{-}\ B^{-}\end{bmatrix} \begin{bmatrix}\frac{w}{2}\\ \frac{w}{2}\end{bmatrix}\] \[+\begin{bmatrix}D^{+}\ D^{-}\ D^{+}\ \big{[}\frac{w}{2}\big{]}\,. \end{bmatrix}.\] One can then replace the above minimal inclusion function and the affine bounds (12) into equation (15) and use Theorem 2 to obtain the result. Regarding part (ii), we use the bounds \(\underline{J}_{[x,\widehat{x}]}=\overline{J}_{[x,\widehat{x}]}=A\), \(\underline{J}_{[u,\widehat{u}]}=\overline{J}_{[u,\widehat{u}]}=B\), and \(\underline{J}_{[w,\widehat{w}]}=\overline{J}_{[w,\widehat{w}]}=D\) in Theorem 3. Thus, using the notation of Theorem 3, we compute \[\underline{H} =A+B^{+}\underline{C}(y,\widehat{y})+B^{-}\overline{C}(y,\widehat {y}),\] \[\overline{H} =A+B^{+}\overline{C}(y,\widehat{y})+B^{-}\underline{C}(y,\widehat {y}),\] \[L =\begin{bmatrix}-D^{-}\ D^{-}\end{bmatrix},\qquad Q=\begin{bmatrix} Ax+Dw+B^{+}\underline{d}(y,\widehat{y})+B^{-}\overline{d}(y,\widehat{y})\\ Ax+Dw+B^{+}\overline{d}(y,\widehat{y})+B^{-}\underline{d}(y,\widehat{y})\end{bmatrix}.\] The result then follows by replacing the above terms into equation (17) and using Theorem 3. **Remark 6** (The role of interactions).: The closed-form expressions (18) and (19) demonstrate the difference between the interconnection-based and the interaction-based approach. In both cases, one can interpret the term \(A\) as the effect of open-loop dynamics and the terms \(B^{+}\underline{C}+B^{-}\overline{C}\) and \(B^{+}\overline{C}+B^{-}\underline{C}\) as the effect of the neural network controller. The interconnection-based approach considers the interconnection of the cooperative and competitive effect of the open-loop system and the neural network controller, separately. This leads to the terms \([A]^{\pm}+[B^{+}\underline{C}+B^{-}\overline{C}]^{\pm}\) and \([A]^{\pm}+[B^{+}\overline{C}+B^{-}\underline{C}]^{\pm}\). On the other hand, the interaction-based approach first considers the interaction between the open-loop system and the neural network controller via the terms \(A+B^{+}\underline{C}+B^{-}\overline{C}\) and \(A+B^{+}\overline{C}+B^{-}\underline{C}\) and then the cooperative and competitive effect of these interactions are separated. ### _Interval Reachability of Closed-loop Systems_ Our culminating conclusion is that, using inclusion functions constructed by the interconnection-based and the interaction-based approaches, we obtain computationally efficient over-approximations of reachable sets of the closed-loop system. **Theorem 4** (Reachability of closed-loop system).: _Let \(\mathrm{c}\in\{\mathrm{con},\mathrm{act}\}\), the disturbance set \(\mathcal{W}=[\underline{w},\overline{w}]\), and the initial set \(\mathcal{X}_{0}=[\underline{x}_{0},\overline{x}_{0}]\). For the closed-loop dynamical system (5) with \(t\mapsto\left[\frac{\underline{x}^{\mathrm{c}}(t)}{\mathbb{E}^{\mathrm{c}}(t)}\right]\) being the trajectory of the embedding system_ \[\dot{x}_{i} =\left(\mathsf{E}^{\mathrm{c}}_{[x,\widehat{x}]}(x,\widehat{x} _{[i:x]},\underline{w},\overline{w})\right)_{i},\] \[\dot{\hat{x}}_{i} =\left(\overline{\mathsf{F}}^{\mathrm{c}}_{[x,\widehat{x}]}(x_{[ i:\widehat{x}]},\widehat{x},\overline{w},\underline{w})\right)_{i}, \tag{20}\] _for every \(i\in\{1,\ldots,n\}\), starting from \(\left[\frac{x}{\mathbb{F}_{0}}\right]\), the following statements hold:_ 1. _for all_ \(t\in\mathbb{R}_{\geq 0}\)_,_ \[\mathcal{R}_{f^{c}}(t,[\underline{x}_{0},\overline{x}_{0}],[\underline{w}, \overline{w}])\subseteq[\underline{x}^{\mathrm{c}}(t),\overline{x}^{\mathrm{c }}(t)].\] 2. _if the open-loop system (_3_) is linear, then for all_ \(t\in\mathbb{R}_{\geq 0}\)_,_ \[[\underline{x}^{\mathrm{act}}(t),\overline{x}^{\mathrm{act}}(t)]\subseteq[ \underline{x}^{\mathrm{con}}(t),\overline{x}^{\mathrm{con}}(t)].\] Proof.: Regarding part (i), using Theorem 2 and Theorem 3, we show that \(\mathsf{F}^{\mathrm{con}}_{[y,\widehat{y}]}\) and \(\mathsf{F}^{\mathrm{act}}_{[y,\widehat{y}]}\) are \([y,\widehat{y}]\times\mathbb{R}^{q}\)-localized inclusion functions for the closed-loop vector field \(f^{c}\). Thus, one can use the localized version of Proposition 5 (see Remark 4(i)) with \(y=x\) and \(\widehat{y}=\widehat{x}\) to obtain the result. Regarding part (ii), for linear open-loop systems, using Theorem 1, the embedding system associated to the interconnection-based inclusion function function has the following form: \[\frac{d}{dt}\left[\frac{x}{\widehat{x}}\right]=\left[\begin{smallmatrix}[A^{ \mathrm{M}}+B^{\mathrm{t}}\underline{C}+B^{-}\overline{C}]^{\mathrm{M}}&[A^{ \mathrm{M}}]^{\mathrm{M}}+[B^{\mathrm{t}}\underline{C}+B^{-}\overline{C}]^{ \mathrm{M}}\\ [A^{\mathrm{M}}+[B^{\mathrm{t}}\underline{C}+\overline{C}]^{\mathrm{M}}]&[A^{ \mathrm{M}}]^{\mathrm{M}}+[B^{\mathrm{t}}\underline{C}+B^{-}\overline{C}]^{ \mathrm{M}}\end{smallmatrix}\right]\left[\frac{x}{\widehat{x}}\right]\] \[+\left[\begin{smallmatrix}D^{+}D^{-}\\ D^{-}D^{+}\end{smallmatrix}\right]\left[\frac{w}{\widehat{w}}\right]+\left[ \begin{smallmatrix}B^{\mathrm{t}}\underline{d}+B^{-}\overline{d}\\ B^{-}\underline{d}+B^{+}\overline{d}\end{smallmatrix}\right]=\mathsf{F}^{ \mathrm{con}}(x,\widehat{x},w,\widehat{w}), \tag{21}\] and the embedding system associated to the interaction-based inclusion function has the following form: \[\frac{d}{dt}\left[\frac{x}{\widehat{x}}\right]=\left[\begin{smallmatrix}[A^{ \mathrm{B}}+B^{\mathrm{t}}\underline{C}+B^{-}\overline{C}]^{\mathrm{M}}&[A^{ \mathrm{B}}+\underline{C}+B^{-}\overline{C}]^{\mathrm{M}}\\ [A^{\mathrm{B}}+\underline{C}+B^{-}\overline{C}]^{\mathrm{M}}&[A^{\mathrm{B}}+ B^{-}\overline{C}]^{\mathrm{M}}\end{smallmatrix}\right]\left[\frac{x}{\widehat{x}}\right]\] \[+\left[\begin{smallmatrix}D^{+}D^{-}\\ D^{-}D^{+}\end{smallmatrix}\right]\left[\frac{w}{\widehat{w}}\right]+\left[ \begin{smallmatrix}B^{\mathrm{t}}\underline{d}+B^{-}\overline{d}\\ B^{-}\underline{d}+B^{+}\overline{d}\end{smallmatrix}\right]=\mathsf{F}^{ \mathrm{act}}(x,\widehat{x},w,\widehat{w}). \tag{22}\] It is easy to check that both embedding systems (21) and (22) are continuous-time monotone. Moreover, we have \[[A+B^{+}\underline{C}+B^{-}\overline{C}]^{\mathrm{M}}\leq[A]^{ \mathrm{M}}+[B^{+}\underline{C}+B^{-}\overline{C}]^{\mathrm{M}},\] \[[A+B^{+}\underline{C}+B^{-}\overline{C}]^{\mathrm{M}}\geq[A]^{ \mathrm{M}}+[B^{+}\underline{C}+B^{-}\overline{C}]^{\mathrm{nM}}.\] Therefore, for every \(x\leq\widehat{x}\), we have \[[A+B^{+}\underline{C}+B^{-}\overline{C}]^{\mathrm{M}}x+[A+B^{+} \underline{C}+B^{-}\overline{C}]^{\mathrm{nM}}\widehat{x}\] \[\geq([A]^{\mathrm{M}}+[B^{+}\underline{C}+B^{-}\overline{C}]^{ \mathrm{M}})x+([A]^{\mathrm{nM}}+[B^{+}\underline{C}+B^{-}\overline{C}]^{ \mathrm{nM}})\widehat{x}.\] This implies that, \(\mathsf{F}^{\mathrm{con}}(x,\widehat{x},w,\widehat{w})\leq_{\mathrm{SE}} \mathsf{F}^{\mathrm{act}}(x,\widehat{x},w,\widehat{w})\), for every \(x\leq\widehat{x}\) and every \(w\leq\widehat{w}\). Now, we can use the classical monotone comparison Lemma [48, Theorem 3.8.1] to obtain \(\left[\frac{x^{\mathrm{con}}(t)}{\overline{x}^{\mathrm{con}}(t)}\right]\leq_{ \mathrm{SE}}\left[\frac{x^{\mathrm{an}}(t)}{\overline{x}^{\mathrm{an}}(t)}\right]\) for every \(t\in\mathbb{R}_{\geq 0}\). As a result, we get \([\underline{x}^{\mathrm{act}}(t),\overline{x}^{\mathrm{act}}(t)]\subseteq[ \underline{x}^{\mathrm{con}}(t),\overline{x}^{\mathrm{con}}(t)]\), for every \(t\in\mathbb{R}_{\geq 0}\). **Remark 7**.: 1. _(Comparison with the literature):_ For linear open-loop systems, a straightforward computation shows that Theorem 4 with \(c=\mathrm{act}\) coincides with [30, Lemma IV.3] with \(p=\infty\) and \(q=1\). 2. _(Computational complexity):_ from a computational perspective, the framework presented in Theorem 4 consists of two main ingredients: (i) the neural network verification algorithm for computing the inclusion function for the neural network (either in the form (10) or in the form (12)), and (ii) integration of a single trajectory of the embedding system (13). Part (i) includes querying the neural network verification once per integration step and its runtime depends on the computational complexity of the associated algorithm. The runtime of the part (ii) depends on the integration method and the form of the open-loop decomposition function \(\mathsf{F}\). ## VII Numerical Experiments We demonstrate the effectiveness of our reachability analysis, implemented as an open-source Python toolbox called ReachMM2, using numerical experiments3 for (i) a nonlinear bicycle model, (ii) the linear double integrator, (iii) several existing benchmarks in the literature, and (iv) a platoon of double integrator vehicles moving in a plane. We first briefly mention several algorithmic techniques that are implemented in the ReachMM toolbox and are used in several examples below to broaden the applicability and to improve the accuracy of our reachable set over-approximations. Footnote 2: [https://github.com/gftactslab/ReachMM_TAC2023](https://github.com/gftactslab/ReachMM_TAC2023) Footnote 3: All the experiments are performed using an AMD Ryzen 5 5600X CPU and 32 GB of RAM. Unless otherwise specified, runtimes are averaged over 100 runs, with mean and standard deviations reported. _Partitioning:_ The computational efficiency of our method makes it well-suited for partitioning to reduce compounding over-approximation error caused by the wrapping effect [10, Section 2.2.4]. In Section VII-B, we apply the partitioning methods proposed in [38, 52] to improve accuracy. _Redundant Variable Refinement:_ We accommodate a technique introduced in [13] to refine interval over-approximations of reachable sets using redundant state variables of the form \(y=Ax+b\) for some \(A\in\mathbb{R}^{m\times n}\) and \(b\in\mathbb{R}^{m}\). By augmenting the dynamical system (5) with the additional dynamics \(\dot{y}=A\dot{x}\), we create a new dynamical system with the new states \(z=\left[\begin{smallmatrix}x\\ y\end{smallmatrix}\right]\in\mathbb{R}^{n+m}\) and the affine constraints \(Mz=b\) where \(M=\left[-A&I_{m}\right]\in\mathbb{R}^{m\times(n+m)}\). Following [13], we use the interval bounds on \(z\) to improve the accuracy of the interval bounds on \(x\). We apply this technique in Section VII-C for the TORA benchmark. _Zero-order hold control:_ In some applications, we wish to explicitly account for the practical restriction that the control \(u(t)=N(x(t))\) cannot be continuously updated and, instead, the control must be implemented via, _e.g._, a zero-order hold strategy between sampling instances. It is straightforward to extend the interconnection-based approach to be able to capture the zero-order hold policy [52]. Adopting the zero-order hold policy in the interaction-based approach requires over-bounding the error and we omit this calculation for the sake of brevity. We refer to our code for details of this adaptation. We use this framework in Section VII-C. _Implementation:_ Our current implementation for all examples is in standard Python. For the interconnection-based approach, the inclusion function for the open-loop system is the natural inclusion functions computed using our package npinterval [41]. For neural networks, the affine inclusion functions are obtained from CROWN [25] and computed using autoLiRPA [53]. Further performance improvements of ReachMM are likely possible by, _e.g._, implementing as compiled code, and are subject of ongoing and future work. ### _Nonlinear bicycle model_ In the first experiment, we compare the interconnection-based and the interaction-based approach. Consider the non linear dynamics of a bicycle adopted from [54]: \[\dot{p_{x}} =v\cos(\phi+\beta(u_{2})) \dot{\phi} =\frac{v}{\ell_{r}}\sin(\beta(u_{2}))\] \[\dot{p_{y}} =v\sin(\phi+\beta(u_{2})) \dot{v} =u_{1} \tag{23}\] where \([p_{x},p_{y}]^{\top}\in\mathbb{R}^{2}\) is the displacement of the center of mass in the \(x-y\) plane, \(\phi\in[-\pi,\pi)\) is the heading angle in the plane, and \(v\in\mathbb{R}_{\geq 0}\) is the speed of the center of mass. Control input \(u_{1}\) is the applied force, input \(u_{2}\) is the angle of the front wheel, and \(\beta(u_{2})=\arctan\left(\frac{\ell_{f}}{\ell_{f}+\ell_{r}}\tan(u_{2})\right)\) is the slip slide angle where the parameter \(\ell_{f}\) (\(\ell_{r}\)) is the distance between the center of mass and the front (rear) wheel. In this example, for the sake of simplicity, we set \(\ell_{f}=\ell_{r}=1\). Let \(x=[p_{x},p_{y},\phi,v]^{\top}\) and \(u=[u_{1},u_{2}]^{\top}\). We apply the neural network controller (\(4\times 100\times 100\times 2\), ReLU activations) defined in [38], which was trained to mimic an MPC that stabilizes the vehicle to the origin while avoiding a circular obstacle centered at \((4,4)\) with a radius of \(2\). The dynamics are simulated using Euler integration with a step size of \(0.125\). In Figure 3, we compare the accuracy and runtime of different reachability approaches for the bicycle model. DiscussionFigure 3 shows that the naive input-output approach is the fastest approach with low accuracy of over-approximation. Using the interconnection-based approach with \(\mathsf{F}^{\rm con}\) improves the accuracy with a slight increase in the runtime. In comparison, the interaction-based approach with the Jacobian-based cornered inclusion function \(\mathsf{F}^{\rm act}\) is notably slower due to the computation of Jacobian bounds (16) in this approach. Over short time horizons, the interaction-based approach is more accurate, however, its accuracy deteriorates for longer horizons, which can be attributed to the decrease in accuracy of the Jacobian bounds (16). As has been shown in Proposition 4, the accuracy of the intersection \(\mathsf{F}^{\rm con}\wedge\mathsf{F}^{\rm act}\) is better than both \(\mathsf{F}^{\rm con}\) and \(\mathsf{F}^{\rm act}\). Finally, using the mixed Jacobian-based cornered inclusion function (cf. Remark 5(ii)) significantly improves the accuracy of the interaction-based approach with little effect on its runtime. ### _Double Integrator Model_ In the second experiment, we focus on reachability of linear open-loop systems with neural network controllers. We study the accuracy and efficiency of the interaction-based approach (19) for the double integrator benchmark system \[x(t+1)=\begin{bmatrix}1&1\\ 0&1\end{bmatrix}x(t)+\begin{bmatrix}0.5\\ 1\end{bmatrix}u(t). \tag{24}\] For this example, we use the discrete-time version of our framework as derived in [52, Section VII.B]. We apply the neural network controller (\(2\times 10\times 5\times 1\), ReLU activations) defined in [30] and consider the interaction-based approach with the closed-loop inclusion function \(\mathsf{F}^{\rm act}\) defined in (19). We use contraction-guided adaptive partitioning proposed in [52] to improve the accuracy. Additionally, we compare our proposed ReachMM to state-of-the-art algorithms for linear discrete-time systems: ReachLP [30] with uniform partitioning (ReachLP-Unif) and greedy simulation guided partitioning (ReachLP-GSG), and ReachLipBnB [55] (branch-and-bound using LipSDP [24]). Each algorithm is run with two different sets of hyper-parameters, aiming to compare their performances across various regimes. The setup for ReachMM is \((\varepsilon,\,D_{p},\,D_{\text{N}})\); ReachLP-Unif is \(\#\) initial partitions, ReachLP-GSG is \(\#\) of total propogator calls, ReachLipBnB is \(\varepsilon\). The results are shown in Figure 4 and the runtime comparisons are shown in Table II. DiscussionFigure 4 and Table II show that, when the open-loop system is linear, our interaction-based approach (Corollary 1(ii)) combined with a suitable partitioning scheme beats state-of-the-art approaches in both accuracy and runtime. Fig. 4: The over-approximated reachable sets of the closed-loop double integrator model (24) are compared for three different algorithms on two different runtime regimes, for the initial set \([2.5,3]\times[-0.25,0.25]\) and final time \(T=5\). The experiment setup and performances are reported in Table II. 200 true trajectories are shown in red. The horizontal axis is \(x_{1}\) and the vertical axis is \(x_{2}\). Fig. 3: Accuracy and runtime comparison between different reachability approaches for the bicycle model (23) from the initial set \([7.95,8.05]\times[6.95,7.05]\times[-2\pi/3-0.01,-2\pi/3+0.01]\times[1.99,2.01]\): (a) a naive input-output approach combining the natural inclusion function for the open-loop dynamics and the affine inclusion function for the neural network, (b) the interconnection-based approach with the closed-loop inclusion function \(\mathsf{F}^{\rm con}\) defined in (15) constructed from the natural inclusion function for the open loop dynamics and affine inclusion function for the neural network, (c) the interaction-based approach with Jacobian-based cornered inclusion function \(\mathsf{F}^{\rm act}\) defined in (17), (d) the intersection of the interconnection-based inclusion and interaction-based approach \(\mathsf{F}^{\rm con}\wedge\mathsf{F}^{\rm act}\), (e) the interaction-based approach with _mixed states_ Jacobian-based cornered inclusion function defined in (17) and Remark 5(ii), and (f) the interaction-based approach with _mixed states and control_ Jacobian-based cornered inclusion function defined (17) and Remark 5(ii). The blue boxes are hyper-rectangular over-approximation of reachable sets and 100 simulated trajectories of the system are shown in red. ### _ARCH-COMP Benchmarks_ In the third experiment, we analyze three of the benchmarks from ARCH-COMP22 [56]. Adaptive Cruise Control (ACC)We consider the Adaptive Cruise Control benchmark from [56, Equation (1)]. The neural network controller (\(5\times 20\times 20\times 20\times 20\times 20\times 1\), ReLU activations) with the input \((x_{\rm lead}-x_{\rm ego},v_{\rm lead}-v_{\rm ego},a_{\rm lead}-a_{\rm ego},v_{ \rm set},T_{\rm gap})^{\top}\in\mathbb{R}^{5}\) is applied with a zero-order holding of \(0.1\) seconds [56]. Our goal is to verify that from the initial set \(\mathcal{X}_{0}=[90,110]\times[32,32.2]\times[0,0]\times[10,11]\times[30,30.2 ]\times[0,0]\), the collision specification \[x_{\rm lead}-x_{\rm ego}\geq D_{\rm default}+T_{\rm gap}x_{\rm ego}\] is never violated in the next \(5\) seconds, where \(D_{\rm default}=10\) and \(T_{\rm gap}=1.4s\). To verify the specification, we define \(D_{\rm rel}=x_{\rm lead}-x_{\rm ego}\) and \(D_{\rm safe}=D_{\rm default}+T_{\rm gap}x_{\rm ego}\) and ensure that \(D_{\rm rel}-D_{\rm safe}\geq 0\) for the given time horizon. We consider the interconnection-based approach with the closed-loop inclusion function \(\mathsf{F}^{\rm con}\) defined in (15) constructed from the natural inclusion function for open-loop system and an affine inclusion function for the neural network. We use this interconnection-based inclusion function and the Euler integration with a step-size of \(0.01\) to compute upper and lower bounds on the states of the system starting from the initial set \(\mathcal{X}_{0}\). These bounds are then used to obtain upper and lower bounds on \(D_{\rm rel}\) and \(D_{\rm safe}\). The results are shown in Figure 5. the state-of-the-art methods POLAR [35] and JuliaReach [37]. On the other benchmarks in [56], our method is unable to verify the desired specification. In the next section, we show that our interconnection-based and interaction-based methods enjoy better scalability compared to POLAR and JuliaReach. ### _Vehicle Platooning_ In the fourth experiment, we investigate the scalability of our method. We consider a platoon of \(N\) vehicles \(\mathcal{V}=\{\mathcal{V}_{j}\}_{j=1}^{N}\), each with the two-dimensional double integrator dynamics \[\dot{p}_{x}^{j}=v_{x}^{j}, \dot{v}_{x}^{j}=\sigma(u_{x}^{j})+w_{x}^{j},\] \[\dot{p}_{y}^{j}=v_{y}^{j}, \dot{v}_{y}^{j}=\sigma(u_{y}^{j})+w_{y}^{j}, \tag{26}\] where \(p^{j}=(p_{x}^{j},p_{y}^{j})\in\mathbb{R}^{2}\) is the displacement of the center of mass of \(\mathcal{V}_{j}\), \(v^{j}=(v_{x}^{j},v_{y}^{j})\in\mathbb{R}^{2}\) is the velocity of the center of mass of \(\mathcal{V}_{j}\), \((u_{x}^{j},u_{y}^{j})\in\mathbb{R}^{2}\) are desired acceleration inputs limited by the softmax operator \(\sigma(u)=u_{\text{lim}}\tanh(u/u_{\text{lim}})\) with \(u_{\text{lim}}=5\), and \(w_{x}^{j},w_{y}^{j}\sim\mathcal{U}([-0.001,0.001])\) are uniformly distributed disturbances. We consider a leader-follower structure for the system, where the first vehicle \(\mathcal{V}_{1}\) chooses its control \(u=(u_{x}^{1},u_{y}^{1})\) as the output of a neural network (\(4\times 100\times 100\times 2\), ReLU activations), and the rest of the platoon \(\{\mathcal{V}_{j}\}_{j=2}^{N}\) applies a PD tracking control input \[u_{\text{d}}^{j}=k_{p}\left(p_{\text{d}}^{j-1}-p_{\text{d}}^{j}-r\frac{v_{ \text{d}}^{j-1}}{\|v^{j-1}\|_{2}}\right)+k_{v}(v_{\text{d}}^{j-1}-v_{\text{d}} ^{j}), \tag{27}\] for each \(\mathbf{d}\in\{x,y\}\) with \(k_{p}=k_{v}=5\) and \(r=0.5\). The neural network was trained by gathering data from an offline MPC control policy for the leader only (\(N=1\)). The offline policy minimized a quadratic cost aimed at stabilizing to the origin while avoiding a circular obstacle centered at \((4,4)\) with radius \(2.25\), implemented as a hard constraint with \(33\%\) padding and a slack variable. We consider the interconnection-based approach with closed-loop inclusion function \(\mathsf{F}^{\mathrm{con}}\) defined in (15) constructed from the natural inclusion function for open-loop system. We also consider the interaction-based approach with the closed-loop mixed Jacobian-based cornered inclusion function \(\mathsf{F}^{\mathrm{act}}\) as defined in (17) constructed for four corners \((x,u),(u,\widehat{u}),(\widehat{x},u),(\widehat{x},\widehat{u})\) (cf. Remark 5). We perform reachability analysis for platoons of \(N\) vehicles with \(N\in\{1,4,9,20,50\}\). For \(j\)th vehicle in the platoon, we compute the reachable sets for the time frame \(t\in[0,1.5]\) using the closed-loop inclusion functions \(\mathsf{F}^{\mathrm{con}}\) and \(\mathsf{F}^{\mathrm{act}}\) starting from the initial set \(([7.225+0.5(j-1)\cos(\pi/3),7.275+0.5(j-1)\cos(\pi/3)]\times[5.725+0.5(j-1) \sin(\pi/3),5.775+0.5(j-1)\sin(\pi/3)]\times[-0.5,-0.5]\times[-5,-5])\). All integration is performed using Euler discretization with a step size of \(0.0125\). Figure 8 visualizes the result for \(N=9\). Runtimes of our approach as well as POLAR [35] and JuliaReach [37] for platoons of varying size are reported in IV. Note that the implementations in POLAR and JuliaReach omit the disturbances \(w_{\text{d}}^{j}\) and the softmax \(\sigma\) in equation (26). DiscussionThis experiment demonstrates one of the key features of our interval analysis framework--its scalability to large-scale systems. In general, Figure 8 shows how \(\mathsf{F}^{\mathrm{act}}\) outperforms \(\mathsf{F}^{\mathrm{con}}\) in accuracy of the reachable set over-approximation. However, Table IV shows how \(\mathsf{F}^{\mathrm{con}}\) outperforms \(\mathsf{F}^{\mathrm{act}}\) in terms of scalability with respect to state dimensions. Moreover, both \(\mathsf{F}^{\mathrm{con}}\) and \(\mathsf{F}^{\mathrm{act}}\) demonstrate better runtime scalability than POLAR and JuliaReach. Fig. 8: **Left:** The over-approximation of the reachable sets computed using \(\mathsf{F}^{\mathrm{con}}\) for each individual unit in the platooning example with \(N=9\) are shown on \(p_{x}\)-\(p_{y}\) planes, with the circular obstacle in red. **Right:** The over-approximation of the reachable sets computed using \(\mathsf{F}^{\mathrm{act}}\) for each individual unit in the platooning example with \(N=9\) are shown on \(p_{x}\)-\(p_{y}\) planes, with the circular obstacle in red. Fig. 7: The reachable set for the TORA benchmark is shown on the \(x_{1}\)-\(x_{2}\) plane. The goal set is pictured in green, and 100 true trajectories of the system are pictured in red. **Left:** Every tenth over-approximation of the reachable set is pictured in blue. **Right:** The plot is zoomed into the goal set, and all over-approximations of the reachable set are shown in blue. ## VIII Conclusions We present a framework based on interval analysis for safety verification of neural network controlled systems. The main idea is to embed the closed-loop system into a higher dimensional system whose over-approximation of reachable sets can be easily computed using its extreme trajectory. Using an inclusion function of the open-loop system and interval bounds for neural networks, we proposed an interconnection-based approach and an interaction-based approach for constructing the closed-loop embedding system. We show how these approaches can capture the interactions between the nonlinear plant and the neural network controllers and we provide several numerical experiments comparing them with the state-of-the-art algorithms in the literature.
2304.11337
A Deep Neural Network Deployment Based on Resistive Memory Accelerator Simulation
The objective of this study is to illustrate the process of training a Deep Neural Network (DNN) within a Resistive RAM (ReRAM) Crossbar-based simulation environment using CrossSim, an Application Programming Interface (API) developed for this purpose. The CrossSim API is designed to simulate neural networks while taking into account factors that may affect the accuracy of solutions during training on non-linear and noisy ReRAM devices. ReRAM-based neural cores that serve as memory accelerators for digital cores on a chip can significantly reduce energy consumption by minimizing data transfers between the processor and SRAM and DRAM. CrossSim employs lookup tables obtained from experimentally derived datasets of real fabricated ReRAM devices to digitally reproduce noisy weight updates to the neural network. The CrossSim directory comprises eight device configurations that operate at different temperatures and are made of various materials. This study aims to analyse the results of training a Neural Network on the Breast Cancer Wisconsin (Diagnostic) dataset using CrossSim, plotting the innercore weight updates and average training and validation loss to investigate the outcomes of all the devices.
Tejaswanth Reddy Maram, Ria Barnwal, Bindu B
2023-04-22T07:29:02Z
http://arxiv.org/abs/2304.11337v1
# A Deep Neural Network Deployment Based on Resistive Memory Accelerator Simulation ###### Abstract The objective of this study is to illustrate the process of training a Deep Neural Network (DNN) within a Resistive RAM (ReRAM) Crossbar-based simulation environment using CrossSim, an Application Programming Interface (API) developed for this purpose. The CrossSim API is designed to simulate neural networks while taking into account factors that may affect the accuracy of solutions during training on non-linear and noisy ReRAM devices. ReRAM-based neural cores that serve as memory accelerators for digital cores on a chip can significantly reduce energy consumption by minimizing data transfers between the processor and SRAM and DRAM. CrossSim employs lookup tables obtained from experimentally derived datasets of real fabricated ReRAM devices to digitally reproduce noisy weight updates to the neural network. The CrossSim directory comprises eight device configurations that operate at different temperatures and are made of various materials. This study aims to analyze the results of training a Neural Network on the Breast Cancer Wisconsin (Diagnostic) dataset using CrossSim, plotting the innercore weight updates and average training and validation loss to investigate the outcomes of all the devices. ## I Introduction When we talk about the existing memory technologies, we mainly talk about SRAM, DRAM and flash memory. While all of them are charge based storage devices, they are used in different places according to their varied performances in different areas. SRAM devices are high speed, low power consuming devices which are often used as small cache memory units in the computers because of it's complexity to scale in size and costlier to manufacture. DRAM being a cheaper technology and better scalable, it is used for bigger RAM units which stores the temporary data that is required by the computer for the current program at volatile level. Flash memory is a highly scalable and low-power-consuming non-volatile memory technology, which makes it an ideal candidate for use as a secondary storage unit in computer systems. It is desired by the industry to create an ideal memory technology which has most of the upsides and very few if not none of the downsides of the current memory technologies. Hence with the aim of reinventing the current memory storage techniques, the industry is actively researching the development of a new hierarchy of memory often known as emerging memory technologies. The purpose of these emerging memory technologies is to enable the strengths of existing memory technologies like the rapid toggling capability of SRAMs, high storage capacity equivalent to DRAMs, and non-volatile capability of Flash memory. thus having the potential to be highly appealing alternatives to the next-generation memory hierarchy. [1] In contrast to charge-based memories technologies, these memory technologies works on the principle of making changes in the resistance of the cells to store the information. Few examples of this emerging memory technologies are : (i) PCM or phase change memory, (ii) STT-MRAM or spin-transfer torque magnetoresistive random access memory, and (iii) ReRAM or resistive random access memory. ReRAM is characterized as a non-volatile memory type that has the ability to preserve data even during the power absence. ReRAM stores the data in form of Low and High resistive states. The Metal Insulator Metal (MIM) structure of this memory type allows the fabrication to be simple. It comprises an insulating layer (I) positioned between two metal (M) electrodes. The storage and retrieval of data is dependent on the creation and breaking of a conductive filament between the electrodes, resulting in the low resistance state (LRS) and high resistance state (HRS) respectively. These states will be retained until it is changed with a writing voltage thus making the ReRAMS non volatile. A ReRAM uses a set voltage (Vs) to form a conductive filament between the electrodes representing the Low Resistive State(LRS). And a reset voltage (Vr) to rupture the filament representing the High Reistive State (HRS). In comparison with a conventional CPU, resistive memory crossbars can reduce the energy required to perform computations in neural algorithms by five orders of magnitude or Fig. 1: Existing memory technologies and their properties. Fig. 2: Advantages of ReRAM [2]
2307.08336
RAYEN: Imposition of Hard Convex Constraints on Neural Networks
This paper presents RAYEN, a framework to impose hard convex constraints on the output or latent variable of a neural network. RAYEN guarantees that, for any input or any weights of the network, the constraints are satisfied at all times. Compared to other approaches, RAYEN does not perform a computationally-expensive orthogonal projection step onto the feasible set, does not rely on soft constraints (which do not guarantee the satisfaction of the constraints at test time), does not use conservative approximations of the feasible set, and does not perform a potentially slow inner gradient descent correction to enforce the constraints. RAYEN supports any combination of linear, convex quadratic, second-order cone (SOC), and linear matrix inequality (LMI) constraints, achieving a very small computational overhead compared to unconstrained networks. For example, it is able to impose 1K quadratic constraints on a 1K-dimensional variable with an overhead of less than 8 ms, and an LMI constraint with 300x300 dense matrices on a 10K-dimensional variable in less than 12 ms. When used in neural networks that approximate the solution of constrained optimization problems, RAYEN achieves computation times between 20 and 7468 times faster than state-of-the-art algorithms, while guaranteeing the satisfaction of the constraints at all times and obtaining a cost very close to the optimal one.
Jesus Tordesillas, Jonathan P. How, Marco Hutter
2023-07-17T09:12:05Z
http://arxiv.org/abs/2307.08336v1
# RAYEN: Imposition of Hard Convex Constraints on Neural Networks ###### Abstract This paper presents RAYEN, a framework to impose hard convex constraints on the output or latent variable of a neural network. RAYEN guarantees that, for any input or any weights of the network, the constraints are satisfied at all times. Compared to other approaches, RAYEN does not perform a computationally-expensive orthogonal projection step onto the feasible set, does not rely on soft constraints (which do not guarantee the satisfaction of the constraints at test time), does not use conservative approximations of the feasible set, and does not perform a potentially slow inner gradient descent correction to enforce the constraints. RAYEN supports any combination of linear, convex quadratic, second-order cone (SOC), and linear matrix inequality (LMI) constraints, achieving a very small computational overhead compared to unconstrained networks. For example, it is able to impose 1K quadratic constraints on a 1K-dimensional variable with an overhead of less than 8 ms, and an LMI constraint with \(300\times 300\) dense matrices on a 10K-dimensional variable in less than 12 ms. When used in neural networks that approximate the solution of constrained optimization problems, RAYEN achieves computation times between 20 and 7468 times faster than state-of-the-art algorithms, while guaranteeing the satisfaction of the constraints at all times and obtaining a cost very close to the optimal one. Constraints, convex, neural network, optimization, differentiable. ## I Introduction and Related Work Convex constraints are widely used in areas such as computer vision [1], control [2], trajectory planning [3], supply chain [4], signal processing [5], and economics [6]. In recent years, there has been an extensive use of neural networks in all these applications due to their expressive power. However, their lack of constraint satisfaction guarantees greatly limits their applicability, especially for safety-critical applications. There are some constraints that can be easily imposed on the output (or latent variable) of a neural network. For instance, box constraints can be imposed using sigmod functions, nonnegative constraints can be enforced using relu functions, simplex constraints can be guaranteed using softmax functions, and some spherical or ellipsoidal constraints can be imposed using normalization. However, these methods are not applicable to more general types of constraints. One common way to bias the network towards the satisfaction of the constraints is via soft constraints, which consist of the addition of terms in the training loss to penalize the violation of the constraints [7]. Similar penalties are also used in physics-informed neural networks [8]. The main disadvantage of this approach is that there are no constraint satisfaction guarantees at test time. Figure 1: RAYEN applied to a batch of 500 samples with a feasible set (���⃝1) defined by linear, convex quadratic, SOC, and LMI constraints. For each sample in the batch, RAYEN lets the corresponding latent variable of the network be the vector that defines the step to take from an interior point of the feasible set (�⃝2). The length of this vector is then adjusted to ensure that the endpoint lies within the set (�⃝3). For visualization purposes, a section of the set has been removed in the right plots. When the constraints are homogeneous linear inequality constraints (i.e., \(\mathbf{Ay}\leq\mathbf{0}\)), Frerix et al. [9] leverage the Minkowski-Weyl theorem to guarantee the satisfaction of these linear constraints at all times.1 The main disadvantage of this approach is that it is only applicable to linear inequality constraints. Moreover, this method requires running offline the double description method [10, 11] to obtain the V-representation (vertices and rays) of the polyhedron defined by its H-representation (intersection of half-spaces). Even if done offline, the double description method quickly becomes intractable for high dimensions. Other related methods that focus on linear constraints include [12, 13, 14]. In contrast to these works, which focus only on linear constraints, RAYEN supports any combination of linear, convex quadratic, SOC, and LMI constraints. Footnote 1: The Minkowski-Weyl theorem can be leveraged for any (convex) polyhedron defined by \(\mathbf{Ay}\leq\mathbf{b}\), but [9] focuses on the case \(\mathbf{Ay}\leq\mathbf{0}\) There have also been many recent advances in implicit layers that solve different types of optimization problems [15, 16, 17, 18], with some works focusing on quadratic programming [19] or, more generally, convex optimization problems [20]. These implicit layers can be leveraged to enforce constraints on the network during training and/or testing by obtaining the orthogonal projection onto the feasible set. This orthogonal projection could also be obtained using the Dykstra's Projection Algorithm [21, 22, 23]. While the use of these orthogonal projections guarantees the satisfaction of the constraints, it is typically at the expense of very high computation times. By leveraging analytic expressions of the distance to the boundaries of the convex set, RAYEN is able to avoid this slow orthogonal projection step and guarantee the constraints in a much more computationally-efficient manner. With the goal of reducing the computation time, Donti et al. proposed DC3 [24], an algorithm that first uses completion to guarantee the equality constraints, and then enforces the inequality constraints by using an inner gradient decent procedure that takes steps along the manifold defined by the equality constraints. This inner gradient descent procedure is performed both at training and testing time. While DC3 is typically less computationally expensive that projection-based methods, this inequality correction may still require many steps, as we will show in Section V-A. Moreover, this inner gradient correction may also suffer from convergence issues for general convex constraints. Compared to DC3, RAYEN does not need to rely on an inner gradient descent correction, avoiding therefore any convergence issues and substantially reducing the computation time. The contributions of this work are therefore summarized as follows: * Framework to impose by construction hard convex constraints on the output or latent variable of a neural network. The constraints are guaranteed to be satisfied at all times, for any input and/or weights of the network. No conservative approximations of the set are used. * Any combination of linear, convex quadratic, SOC, and LMI constraints is supported. For example, RAYEN can impose 1K quadratic constraints on a 1K-dimensional variable with a computation overhead of only 8 ms. Similarly, a \(300\times 300\) dense LMI constraint can be imposed on a 10K-dimensional variable with an overhead of less than 11 ms. * When used in neural networks that approximate the solution of optimization problems, RAYEN showcases computation times between 20 and 7468 times faster than other state-of-the-art algorithms, while generating feasible solutions whose costs are very close to the optimal value. The notation used throughout the paper is available in Table I. ## II Problem Setup This work addresses the problem of how to ensure that the output (or a latent variable) \(\mathbf{y}:=\left[\begin{smallmatrix}\mathbf{y}_{[0]}&\cdots&\mathbf{y}_{[k-1]}\end{smallmatrix} \right]^{T}\in\mathbb{R}^{k}\) of a neural network lies in a convex set \(\mathcal{Y}\) defined by the following constraints: \[\mathbf{A}_{1}\mathbf{y}\leq\mathbf{b}_{1} \tag{1}\] \[\mathbf{A}_{2}\mathbf{y}=\mathbf{b}_{2}\] (2) \[g_{i}\left(\mathbf{y}\right):=\frac{1}{2}\mathbf{y}^{T}\mathbf{P}_{i}\mathbf{y }+\mathbf{q}_{i}^{T}\mathbf{y}+r_{i}\leq 0\;\;i=0,\ldots,\eta-1\] (3) \[h_{j}\left(\mathbf{y}\right):=\|\mathbf{M}_{j}\mathbf{y}+\mathbf{s}_{j}\|-\mathbf{c} _{j}^{T}\mathbf{y}-d_{j}\leq 0\;\;j=0,\ldots,\mu-1\] (4) \[\mathbf{W}(\mathbf{y}):=\mathbf{y}_{[0]}\mathbf{F}_{0}+\ldots+\mathbf{y}_{[k-1]}\mathbf{F }_{k-1}+\mathbf{F}_{k}\succeq\mathbf{0} \tag{5}\] where \(\mathbf{P}_{i}\succeq\mathbf{0}\;\forall i=0,...,\eta-1\), and where \(\mathbf{F}_{0},...,\mathbf{F}_{k}\) are symmetric matrices. This set \(\mathcal{Y}\), which can be bounded or unbounded, is defined by linear constraints (Eqs. 1 and 2), convex quadratic constraints (Eq. 3), SOC constraints (Eq. 4), and LMI constraints (Eq. 5, also known as semidefinite constraints). Constraints 1, 2, 3, and 4 could also be written as an LMI constraint, but for notational convenience \begin{table} \begin{tabular}{|c|l|} \hline **Symbol** & **Mearing** \\ \hline \hline \(c,c,\mathbf{C},\mathbf{C},\mathbf{C}\) & Scalar, column vector, matrix, and set \\ \hline \(\|c\|\) & Euclidean norm of the vector \(\mathbf{c}\) \\ \hline \(\mathbf{C}\succeq\mathbf{0}\) & \(\mathbf{C}\) is a (symmetric) positive semidefinite matrix \\ \hline \(\mathbf{C}\succeq\mathbf{0}\) & \(\mathbf{C}\) is a (symmetric) positive definite matrix \\ \hline \(\mathbf{I}\) & Identity matrix \\ \hline \(\mathbf{c}\) & \(\mathbf{c}^{-}\equiv\frac{1}{2\pi}\mathbf{c}\) \\ \hline \(\mathbf{C}^{\dagger}\) & Pseudoinverse of a matrix \(\mathbf{C}\) \\ \hline max \((\mathbf{c})\) & Maximum of the elements of the column vector \(\mathbf{c}\) \\ \hline max \((\mathbf{c})\) & Maximum of the elements of the set \(\mathbf{C}\) \\ \hline inf \((\mathbf{C})\) & Infimum of the set \(\mathbf{C}\) \\ \hline \(\mathbf{c}\) & Frontier of the set \(\mathbf{C}\) \\ \hline \(\mathbf{a}\leq\mathbf{b}\), \(\mathbf{a}=\mathbf{b}\) & Element-wise inequality, element-wise equality \\ \hline \(\mathbf{A}\odot\mathbf{B}\) & Element-wise division \\ \hline \multirow{3}{*}{\(\mathbf{0},\mathbf{1}\)} & Matrix or vector of zeros/(means dimensions given by the \\ & context). If the dimensions need to be specified, the subscript \(a\)\(\times\) rows \(\times\) columns will be empty. \\ \hline \(\mathbf{0}\) & Empty set \\ \hline inf \((\mathbf{5})\) & Affine hull of a set \(\mathbf{S}\) (i.e., smallest affine set containing \(\mathbf{S}\)) \\ \hline \(\mathbf{c}_{[i]}\) & \(\mathbf{i}\)-th element of the column vector \(\mathbf{c}\in\mathbb{R}^{n}\). \(i\in\{0,\ldots,a-1\}\). If \(\mathbf{C}\in\mathbb{R}^{n\times n}\), then \(\mathbf{c}_{[i]}\in\mathbb{R}^{n\times n}\) (i.e., \(\mathbf{x}\in\mathbf{0}\) vector). \\ \hline \(\mathbf{C}_{[S,i]}\cdot\mathbf{c}_{[S]}\) & \(\mathbf{C}_{[S,i]}\) is a matrix whose rows are the rows of \(\mathbf{C}\) whose \\ & indices are in the set \(\mathbf{S}\leq\mathbf{1}\). An analogous definition for \(\mathbf{c}_{[S]}\) \\ \hline abs \((\mathbf{a})\) & Element-wise absolute value \\ \hline softmax \((\mathbf{a})\) & Softmax function, in \(\mathbf{x}\) \(\mathbf{b}\) - softmax \((\mathbf{a})\), then \(\mathbf{b}_{[i]}=\mathbf{c}^{-}\equiv\mathbf{c}^{-}\equiv\mathbf{c}^{-}\equiv\mathbf{c}^{-}\equiv \mathbf{c}^{-}\equiv\mathbf{c}^{-}\equiv\mathbf{c}^{-}\equiv\mathbf{c}^{-}\equiv\mathbf{c}^{-}\) \\ \hline cig \((\mathbf{C})\) & Column vector containing all the eigenvalues of the matrix \(\mathbf{C}\) \\ \hline SOC & Second-order Cone \\ \hline LMI & Linear Matrix Inequality \\ \hline \end{tabular} \end{table} TABLE I: Notation used in this paper throughout the paper (and without any loss of generality), we explicitly distinguish them. Note also that several LMIs can be converted into one LMI by simply stacking the matrices appropriately (see, e.g., [25, Section 4.6.2]). Let us also introduce the following definitions: \[\mathcal{Y}_{L} :=\big{\{}\mathbf{y}\in\mathbb{R}^{k}|\mathbf{A}_{1}\mathbf{y}\leq\mathbf{b}_{1} \big{\}}\cap\big{\{}\mathbf{y}\in\mathbb{R}^{k}|\mathbf{A}_{2}\mathbf{y}=\mathbf{b}_{2}\big{\}}\] \[\mathcal{Y}_{Q} :=\big{\{}\mathbf{y}\in\mathbb{R}^{k}|g_{i}\left(\mathbf{y}\right)\leq 0 \ \forall i=0,\ldots,\eta-1\big{\}}\] \[\mathcal{Y}_{S} :=\big{\{}\mathbf{y}\in\mathbb{R}^{k}|h_{j}\left(\mathbf{y}\right)\leq 0 \ \forall j=0,\ldots,\mu-1\big{\}}\] \[\mathcal{Y}_{M} :=\big{\{}\mathbf{y}\in\mathbb{R}^{k}|\mathbf{W}(\mathbf{y})\succeq\mathbf{0} \big{\}}\] Hence, we have that \(\mathcal{Y}:=\mathcal{Y}_{L}\cap\mathcal{Y}_{Q}\cap\mathcal{Y}_{S}\cap \mathcal{Y}_{M}\). For simplicity, we will assume throughout the paper that \(\text{aff}\left(\mathcal{Y}_{L}\right)=\text{aff}\left(\mathcal{Y}\right)\), where \(\text{aff}\left(\cdot\right)\) denotes the affine hull. Some degenerate cases do not satisfy this assumption, but in those cases the same set \(\mathcal{Y}\) can be parametrized with a different set of constraints for which this assumption holds.2 Footnote 2: An example of a degenerate case in \(\mathcal{Y}\) (i.e., \(k=3\)) with only linear and quadratic constraints would be when \(\mathcal{Y}_{L}\) is the unit cube, and \(\mathcal{Y}_{Q}\) is a cylinder tangent to one of its faces such that \(\mathcal{Y}=\mathcal{Y}_{L}\cap\mathcal{Y}_{Q}\) is the segment they have in common. By simply reparametrizing \(\mathcal{Y}\) with only linear constraints (the segment itself), then the assumption \(\text{aff}\left(\mathcal{Y}_{L}\right)=\text{aff}\left(\mathcal{Y}\right)\) is satisfied. Overall, RAYEN works as follows (see also Fig. 2): In an offline phase (Section III), the affine hull of \(\mathcal{Y}\) is obtained, and the constraints are expressed in that linear subspace. Letting \(\mathcal{Z}\) denote the feasible set in this subspace, an interior point \(\mathbf{z}_{0}\) of this set \(\mathcal{Z}\) is also found. In the online phase (Section IV), a linear map is applied to an upstream latent variable of the network to obtain a vector \(\mathbf{v}\) of the same dimension of the subspace, that will determine the step direction from \(\mathbf{z}_{0}\). The length \(\lambda\geq 0\) of this step is adjusted to ensure that \(\mathbf{z}_{0}+\lambda\frac{\mathbf{v}}{\|\mathbf{v}\|}\) lies in \(\mathcal{Z}\). After lifting to the original dimension, the output is therefore guaranteed to lie in \(\mathcal{Y}\). ## III RAYEN: Offline ### _Affine Hull of \(\mathcal{Y}\)_ To find the affine hull of the set \(\mathcal{Y}\), we first express all the linear constraints (Eqs. 1 and 2) as linear inequality constraints by simply stacking the matrices: \[\tilde{\mathbf{A}} :=\big{[}\,\mathbf{A}_{1}^{T}\,\mathbf{A}_{2}^{T}-\mathbf{A}_{2}^{T}\,\big{]} ^{T}\] \[\tilde{\mathbf{b}} :=\big{[}\,b_{1}^{T}\,\mathbf{b}_{2}^{T}-\mathbf{b}_{2}^{T}\,\big{]}^{T}\] and therefore \(\mathcal{Y}_{L}\) is now \(\Big{\{}\mathbf{y}\in\mathbb{R}^{k}|\tilde{\mathbf{A}}\mathbf{y}\leq\tilde{\mathbf{b}}\Big{\}}\). To reduce the computation time during the online phase, the redundant constraints of the inequality system \(\tilde{\mathbf{A}}\mathbf{y}\leq\tilde{\mathbf{b}}\) (if there are any) are then deleted. This is done by solving a sequence of Linear Programs (see, e.g. [26, Eq. 1.5]), which obtains the reduced system of inequalities \(\mathbf{A}\mathbf{y}\leq\mathbf{b}\) such that \(\mathcal{Y}_{L}=\left\{\mathbf{y}\in\mathbb{R}^{k}|\mathbf{A}\mathbf{y}\leq\mathbf{b}\right\}\). Then, another sequence of Linear Programs is solved to find the set \[\mathcal{E}:=\left\{i|\mathbf{A}_{[i,:]}\mathbf{y}=\mathbf{b}_{[i]}\ \forall\mathbf{y}\in \mathcal{Y}_{L}\right\}\,\] which contains the indexes of the constraints that are always active for all the points in \(\mathcal{Y}_{L}\) (see, e.g. [27, Alg. 1.3.1] or [28, Section 5.2]). Defining \(\mathcal{I}:=\{0,...,a-1\}\backslash\mathcal{E}\) (where \(a\) is the number of rows of \(\mathbf{A}\)), let us now introduce the following notation:3 Footnote 3: Note that if \(\mathcal{I}=\emptyset\), then we need \(\mathbf{b}_{\mathcal{I}}=1\) (instead of \(\mathbf{b}_{\mathcal{I}}=0\)) to make sure that there exists a point in the interior of \(\mathcal{Z}_{L}:=\left\{\mathbf{z}\in\mathbb{R}^{n}|\mathbf{0}_{1\times n}\mathbf{z}\leq 1 \right\}\equiv\mathbb{R}^{n}\) (see Section III-C). \[\mathbf{A}_{\mathcal{I}}:=\begin{cases}\mathbf{0}_{1\times k}&\mathcal{I}=\emptyset\\ \mathbf{A}_{[\mathcal{I},:]}&\text{otherwise}\end{cases},\ \mathbf{b}_{ \mathcal{I}}:=\begin{cases}1&\mathcal{I}=\emptyset\\ \mathbf{b}_{[\mathcal{I}]}&\text{otherwise}\end{cases}\] Then, the affine hull of \(\mathcal{Y}\) is given by \[\text{aff}\left(\mathcal{Y}\right)=\left\{\mathbf{y}\in\mathbb{R}^{k}|\mathbf{A}_{ \mathcal{E}}\mathbf{y}=\mathbf{b}_{\mathcal{E}}\right\}\,\] where we have used the assumption that \(\text{aff}\left(\mathcal{Y}\right)=\text{aff}\left(\mathcal{Y}_{L}\right)\) (see Section II). The dimension of this affine hull is then \[n:=k-\text{rank}\left(\mathbf{A}_{\mathcal{E}}\right). \tag{6}\] Note also that \[\mathcal{Y}_{L}=\underbrace{\left\{\mathbf{y}\in\mathbb{R}^{k}|\mathbf{A}_{\mathcal{E }}\mathbf{y}=\mathbf{b}_{\mathcal{E}}\right\}}_{=\text{aff}\left(\mathcal{Y}_{L} \right)=\text{aff}\left(\mathcal{Y}\right)}\cap\left\{\mathbf{y}\in\mathbb{R}^{k}| \mathbf{A}_{\mathcal{I}}\mathbf{y}\leq\mathbf{b}_{\mathcal{I}}\right\}\.\] In general, \((\mathbf{A}_{\mathcal{E}},\mathbf{b}_{\mathcal{E}})\) may be different than \((\mathbf{A}_{\mathcal{I}},\mathbf{b}_{2})\), and \((\mathbf{A}_{\mathcal{I}},\mathbf{b}_{\mathcal{I}})\) may be different than \((\mathbf{A}_{\mathcal{I}},\mathbf{b}_{1})\). This can happen, for example, when \(\text{aff}\left(\left\{\mathbf{y}\in\mathbb{R}^{k}|\mathbf{A}_{1}\mathbf{y}\leq\mathbf{b}_{1} \right\}\right)\neq\mathbb{R}^{k}\) (intuitively this means that the inequality constraint defined by Eq. 1_hides_ equality constraints), or when there are redundant constraints in Eqs. 1 and/or 2. ### _Set \(\mathcal{Z}\)_ Any point in \(\mathbf{y}\in\text{aff}\left(\mathcal{Y}\right)\) can be expressed as \[\mathbf{y}=\mathbf{f}(\mathbf{z}):=\mathbf{N}\mathbf{z}+\underbrace{\mathbf{A}_{\mathcal{E}}^{\dagger }\mathbf{b}_{\mathcal{E}}}_{:=\mathbf{y}_{p}}\, \tag{7}\] where \(\mathbf{z}\in\mathbb{R}^{n}\), \(\mathbf{N}\) is a \(k\times n\) matrix whose columns form an orthonormal basis for the null space of \(\mathbf{A}_{\mathcal{E}}\), and \(\mathbf{A}_{\mathcal{E}}^{\dagger}\) is the pseudoinverse of \(\mathbf{A}_{\mathcal{E}}\). Using Eq. 7, we have that \(\mathbf{A}_{\mathcal{I}}\mathbf{y}\leq\mathbf{b}_{\mathcal{I}}\) is equivalent to: \[\mathbf{A}_{\mathcal{I}}\left(\mathbf{N}\mathbf{z}+\mathbf{y}_{p}\right)\leq\mathbf{b}_{ \mathcal{I}}\] \[\underbrace{\mathbf{A}_{\mathcal{I}}\mathbf{N}\mathbf{z}}_{:=\mathbf{A}_{p}}\leq \underbrace{\mathbf{b}_{\mathcal{I}}-\mathbf{A}_{\mathcal{I}}\mathbf{y}_{p}}_{:=\mathbf{b}_{p}} \tag{8}\] Defining now these sets (see also Fig. 2): \[\mathcal{Z}_{L}:= \left\{\mathbf{z}\in\mathbb{R}^{n}|\mathbf{A}_{p}\mathbf{z}\leq\mathbf{b}_{p}\right\}\] \[\mathcal{Z}_{Q_{i}}:= \left\{\mathbf{z}\in\mathbb{R}^{n}|g_{i}\left(\mathbf{f}(\mathbf{z})\right) \leq 0\right\}\qquad\mathcal{Z}_{Q}:=\bigcap_{i=0}^{\eta-1}\mathcal{Z}_{Q_{i}}\] \[\mathcal{Z}_{S_{j}}:= \left\{\mathbf{z}\in\mathbb{R}^{n}|h_{j}\left(\mathbf{f}(\mathbf{z})\right) \leq 0\right\}\qquad\mathcal{Z}_{S}:=\bigcap_{j=0}^{\mu-1}\mathcal{Z}_{S_{j}}\] \[\mathcal{Z}_{M}:= \left\{\mathbf{z}\in\mathbb{R}^{n}|\mathbf{W}\left(\mathbf{f}(\mathbf{z})\right) \succeq\mathbf{0}\right\}\] \[\mathcal{Z}:= \mathcal{Z}_{L}\cap\mathcal{Z}_{Q}\cap\mathcal{Z}_{S}\cap \mathcal{Z}_{M}\] Any point \(\mathbf{z}\in\mathcal{Z}\) can therefore be mapped to the corresponding point \(\mathbf{y}\in\mathcal{Y}\) using Eq. 7. ### _Interior point of \(\mathcal{Z}\)_ Finally, we obtain a point \(\mathbf{z}_{0}\) in the interior of \(\mathcal{Z}\), by solving the following convex program: \[(\mathbf{z}_{0},\epsilon^{*})=\underset{\mathbf{z},\epsilon}{\text{argmax}} \epsilon\] s.t.: \[\mathbf{A}_{p}\mathbf{z}-\mathbf{b}_{p}\leq-\epsilon\mathbf{1}\] \[g_{i}\left(\mathbf{f}\left(\mathbf{z}\right)\right)\leq-\epsilon\ \ i=0,...,\eta-1\] \[h_{j}\left(\mathbf{f}\left(\mathbf{z}\right)\right)\leq-\epsilon\ \ j=0,...,\mu-1\] \[\mathbf{W}\left(\mathbf{f}(\mathbf{z})\right)\succeq\epsilon\mathbf{I}\] \[\epsilon>0\] ## IV RAYEN: Online As shown in Fig. 3, to obtain an \(n\)-dimensional latent variable \(\mathbf{v}\) (where \(n\) is the dimension of \(\text{aff}\left(\mathcal{Y}\right)\), see Eq. 6), we first apply a linear layer to the upstream latent variable of the network \(\mathbf{x}\in\mathbb{R}^{m}\). This mapping can be omitted if \(m=n\). Assuming now \(\mathbf{v}\neq\mathbf{0}\),4 let us define the inverse distance to the frontier of \(\mathcal{Z}\) along \(\bar{\mathbf{v}}:=\frac{\mathbf{v}}{\|\mathbf{v}\|}\) as Footnote 4: If \(\mathbf{v}=\mathbf{0}\), we simply take \(\mathbf{z}_{1}:=\mathbf{z}_{0}\), and therefore \(\kappa\) does not need to be computed. \[\kappa:=\text{inf}\left\{\lambda^{-1}|\mathbf{z}_{0}+\lambda\bar{\mathbf{v}}\in\mathcal{Z },\ \lambda>0\right\}\.\] Then, it is clear that \[\mathbf{z}_{1}:=\left(\mathbf{z}_{0}+\text{min}\left(\frac{1}{\kappa},\|\mathbf{v}\|\right) \bar{\mathbf{v}}\right)\in\mathcal{Z}\, \tag{9}\] Figure 3: Neural network equipped with RAYEN. \(\kappa\) is computed as shown in Table II, and the map \(\mathbf{f}\left(\mathbf{z}_{0}+\text{min}\left(\frac{1}{\kappa},\|\mathbf{v}\|\right)\bar{ \mathbf{v}}\right)\) is used to guarantee \(\mathbf{y}\in\mathcal{Y}\). Here, L(\(m,n\)) denotes a linear layer with input size \(m\) and output size \(n\). This linear layer is not needed if \(m=n\). After the RAYEN module, there may be more downstream layers. During the training procedure, gradients can then be backpropagated through RAYEN. and that therefore \(\mathbf{f}\left(\mathbf{z}_{1}\right)\in\mathcal{Y}\). Note that no conservatism is introduced here. In other words, and given that \(\mathcal{Y}\) is a convex set, for any point \(\mathbf{y}\in\mathcal{Y}\), there exists at least one \(\mathbf{v}\) such that \(\mathbf{f}\left(\mathbf{z}_{1}\right)\in\mathcal{Y}\) holds. To obtain \(\kappa\), first note that \[\kappa=\max\left[\,\kappa_{L}\;\kappa_{Q}\;\kappa_{S}\;\kappa_{M}\,\right]^{T}\,\] where \(\kappa_{L}\), \(\kappa_{Q}\), \(\kappa_{S}\), and \(\kappa_{M}\) are defined in Table II and are, respectively, the inverses of the distances to \(\partial\mathcal{Z}_{L}\), \(\partial\mathcal{Z}_{Q}\), \(\partial\mathcal{Z}_{S}\), and \(\partial\mathcal{Z}_{M}\) along \(\bar{\mathbf{v}}\) (see also Figs. 2 and 4). In the following subsections we explain how \(\kappa_{L}\), \(\kappa_{Q}\), \(\kappa_{S}\), and \(\kappa_{M}\) can be obtained. ### _Computation of \(\kappa_{L}\)_ Given a face \(\mathcal{F}_{j}:=\left\{\mathbf{z}\in\mathbb{R}^{n}|\mathbf{A}_{p_{[j,:]}}\mathbf{z}=\mathbf{b }_{p_{[j]}}\right\}\) of the polyhedron \(\mathcal{Z}_{L}\), the inverse distance from \(\mathbf{z}_{0}\) to \(\mathcal{F}_{j}\) along the direction \(\bar{\mathbf{v}}\) can be easily obtained as \[\kappa_{L,j}=\text{relu}\left(\frac{\mathbf{A}_{p_{[j,:]}}\bar{\mathbf{v}}}{\mathbf{b}_{p _{[j]}}-\mathbf{A}_{p_{[j,:]}}\mathbf{z}_{0}}\right)\,\] where the \(\text{relu}(\cdot)\) operator is needed to enforce moving along \(\bar{\mathbf{v}}\). Taking into account now all the faces of \(\mathcal{Z}_{L}\), we have that \(\kappa_{L}\) is given by \[\kappa_{L}:=\text{relu}\left(\max\left(\underbrace{\mathbf{A}_{p}\oslash((\mathbf{b}_ {p}-\mathbf{A}_{p}\mathbf{z}_{0})\,\mathbf{1}_{1\times n})}_{:=\mathcal{D}}\bar{\mathbf{v}} \right)\right)\,\] where \(\oslash\) denotes the element-wise division between two matrices, and where \(\mathbf{D}\) can be computed offline because it does not depend on \(\bar{\mathbf{v}}\). Note that if \(\kappa_{L}=0\), then \(\mathcal{Z}_{L}\) is unbounded along the ray that starts at \(\mathbf{z}_{0}\) and follows \(\bar{\mathbf{v}}\). ### _Computation of \(\kappa_{Q}\)_ The inverse of the distance from \(\mathbf{z}_{0}\) to \(\partial\mathcal{Z}_{Q_{i}}\) along the direction \(\bar{\mathbf{v}}\) can be obtained by computing the nonnegative \(\kappa_{Q,i}\) that satisfies: \[g_{i}\left(\mathbf{f}\left(\mathbf{z}_{0}+\frac{1}{\kappa_{Q,i}}\bar{\mathbf{v}}\right) \right)=0\,\] where \(\mathbf{f}(\cdot)\) is defined in Eq. 7. Multiplying both sides of this equation by \(\kappa_{Q,i}^{2}\) yields a quadratic equation on \(\kappa_{Q,i}\), from which its nonnegative root \(\kappa_{Q,i}^{+}\) can be easily obtained. Taking now into account all the quadratic constraints, \(\kappa_{Q}\) is therefore given by: \[\kappa_{Q}:=\max\left(\left[\,\kappa_{Q,0}^{+}\cdots\kappa_{Q,\eta-1}^{+} \right]^{T}\right)\] ### _Computation of \(\kappa_{S}\)_ Similar to the previous case, the inverse of the distance from \(\mathbf{z}_{0}\) to \(\partial\mathcal{Z}_{S_{j}}\) along the direction \(\bar{\mathbf{v}}\) can be obtained by computing the nonnegative \(\kappa_{S,j}\) that satisfies: \[h_{j}\left(\mathbf{f}\left(\mathbf{z}_{0}+\frac{1}{\kappa_{S,j}}\bar{\mathbf{v}}\right) \right)=0\] \[\left\|\mathbf{M}_{j}\mathbf{f}\left(\mathbf{z}_{0}+\frac{1}{\kappa_{S,j}}\bar{\mathbf{v}} \right)+\mathbf{s}_{j}\right\|=\mathbf{c}_{j}^{T}\mathbf{f}\left(\mathbf{z}_{0}+\frac{1}{ \kappa_{S,j}}\bar{\mathbf{v}}\right)+d_{j} \tag{10}\] Squaring both sides of Eq. 10, and then multiplying them by \(\kappa_{S,j}^{2}\) yields a quadratic equation on \(\kappa_{S,j}\), from which its two roots \(\kappa_{S,j}^{(0)}\) and \(\kappa_{S,j}^{(1)}\) can be easily obtained. The inverse of the distance from \(z_{0}\) to \(\partial\mathcal{Z}_{S_{j}}\) along \(\bar{\mathbf{v}}\) will therefore be given by5 Footnote 5: The \(\text{relu}(\cdot)\) operator is needed because both roots can be negative due to the fact that we have squared both sides of Eq. 10. Both roots being negative means that in that case \(\mathcal{Z}_{S_{j}}\) is unbounded in the direction \(\bar{\mathbf{v}}\) and therefore we have \(\kappa_{S,j}=0\). When both roots are positive, we need to select the largest one, which is why the \(\max\left(\cdot\right)\) operator is needed. \[\text{relu}\left(\max\left(\left[\begin{array}{cc}\kappa_{S,j}^{(0)}& \kappa_{S,j}^{(1)}\end{array}\right]^{T}\right)\right)\.\] Taking into account all the SOC constraints, \(\kappa_{S}\) is therefore given by \[\kappa_{S}:=\text{relu}\left(\max\left(\left[\begin{array}{cc}\kappa_{S,0}^ {(0)}&\kappa_{S,0}^{(1)}\cdots\kappa_{S,\mu-1}^{(0)}&\kappa_{S,\mu-1}^{(1)} \end{array}\right]^{T}\right)\right)\.\] ### _Computation of \(\kappa_{M}\)_ The inverse of the distance from \(\mathbf{z}_{0}\) to \(\partial\mathcal{Z}_{M}\) along the direction \(\bar{\mathbf{v}}\) is defined as: \[\kappa_{M}:=\text{inf}\left\{\lambda^{-1}|\mathbf{z}_{0}+\lambda\bar{\mathbf{v}}\in \mathcal{Z}_{M},\ \lambda>0\right\}\] Noting that \[\mathbf{f}\left(\mathbf{z}_{0}+\lambda\bar{\mathbf{v}}\right)=\lambda\underbrace{\mathbf{N} \bar{\mathbf{v}}}_{:=\mathbf{p}}+\underbrace{\mathbf{N}\mathbf{z}_{0}+\mathbf{y}_{p}}_{:=\mathbf{y}_{0 }}=\left(\lambda\mathbf{\rho}+\mathbf{y}_{0}\right)\,\] then the condition \(\mathbf{z}_{0}+\lambda\bar{\mathbf{v}}\in\mathcal{Z}_{M}\) is equivalent to \[\mathbf{W}\left(\mathbf{f}\left(\mathbf{z}_{0}+\lambda\bar{\mathbf{v}}\right)\right)=\mathbf{F}_{ k}+\sum_{\alpha=0}^{k-1}\left(\lambda\mathbf{\rho}_{[\alpha]}+\mathbf{y}_{0_{[\alpha]}} \right)\mathbf{F}_{\alpha}\succeq\mathbf{0}\.\] Dividing everything by \(\lambda\) (recall that \(\lambda>0\)) and rearranging the terms we have \[\lambda^{-1}\underbrace{\left(\mathbf{F}_{k}+\sum_{\alpha=0}^{k-1}\left(\mathbf{y}_{ 0_{[\alpha]}}\mathbf{F}_{\alpha}\right)\right)}_{:=\mathbf{H}\succ\mathbf{0}}+\underbrace {\sum_{\alpha=0}^{k-1}\left(\mathbf{\rho}_{[\alpha]}\mathbf{F}_{\alpha}\right)}_{:=\mathbf{ S}}\succeq\mathbf{0}\,\] where \(\mathbf{H}\succ\mathbf{0}\) derives from the fact that \(\mathbf{z}_{0}\) is an interior point of \(\mathcal{Z}_{M}\). Hence: \[\kappa_{M}:=\text{inf}\left\{\delta|\delta\mathbf{H}+\mathbf{S}\succeq\mathbf{0},\ \delta>0\right\} \tag{11}\] Let us now distinguish two cases: * If \(\mathbf{S}\succeq\mathbf{0}\), then it is clear that \(\kappa_{M}=0\). * Otherwise, we need \(\kappa_{M}\mathbf{H}+\mathbf{S}\in\partial\mathcal{Z}_{M}\), and hence \[\kappa_{M}=\text{max}\left(\left\{\tau_{i}|\left(\tau_{i}\mathbf{H}+\mathbf{S}\right) \mathbf{v}_{i}=0\mathbf{v}_{i},\mathbf{v}_{i}\neq\mathbf{0}\right\}\right)\,\] where we have used the fact that the matrices that belong to \(\partial\mathcal{Z}_{M}\) have at least one zero eigenvalue (see also Fig. 5). Note also that: \[\left(\tau_{i}\mathbf{H}+\mathbf{S}\right)\mathbf{v}_{i}=0\mathbf{v}_{i}\iff-\mathbf{H}^{-1}\mathbf{S }\mathbf{v}_{i}=\tau_{i}\mathbf{v}_{i}\] (12) Letting \(\mathbf{L}\) denote the lower triangular matrix with positive diagonal entries such that \(\mathbf{H}^{-1}=\mathbf{L}\mathbf{L}^{T}\) (i.e., the Cholesky decomposition of \(\mathbf{H}^{-1}\)), and using the fact that \(\text{eig}\left(-\mathbf{H}^{-1}\mathbf{S}\right)=\text{eig}\left(\mathbf{L}^{T}\left(-\mathbf{S }\right)\mathbf{L}\right)\) (see proof in Appendix A), we have that6 Footnote 6: Eq. 12 can also be written as \(-\mathbf{S}\mathbf{v}_{i}=\tau_{i}\mathbf{H}\mathbf{v}_{i}\), and hence \(\kappa_{M}\) could also be found solving the generalized eigenvalue problem [25, 29] of the pair \((-\mathbf{S},\mathbf{H})\). \[\kappa_{M}=\text{relu}\left(\max\left(\text{eig}\left(\mathbf{L}^{T}\left(-\mathbf{S} \right)\mathbf{L}\right)\right)\right). \tag{13}\] As only the maximum eigenvalue is needed, we can use methods such as power iteration [31, 32, 33], LOBPCG [34], or the Lanczos algorithm [35, 36] to avoid computing the whole spectrum of the matrix. Note also that the matrix \(\mathbf{L}\) can be computed offline, since it does not depend on \(\mathbf{v}\). ### _Remarks_ We can have these two cases in Eq. 9: * If \(\mathbf{z}_{0}+\mathbf{v}\in\mathcal{Z}\), then \(\left\|\mathbf{v}\right\|\leq\frac{1}{\kappa}\), and therefore Eq. 9 becomes \(\mathbf{z}_{1}=\mathbf{z}_{0}+\mathbf{v}\). * If \(\mathbf{z}_{0}+\mathbf{v}\notin\mathcal{Z}\), then \(\left\|\mathbf{v}\right\|>\frac{1}{\kappa}\) and therefore Eq. 9 becomes \(\mathbf{z}_{1}=\mathbf{z}_{0}+\frac{1}{\kappa}\bar{\mathbf{v}}\). This operation performs a (nonorthogonal) projection of \(\mathbf{z}_{0}+\mathbf{v}\) onto \(\mathcal{Z}\) along the ray that starts at \(\mathbf{z}_{0}\) and follows \(\bar{\mathbf{v}}\). Note also that, if \(\mathcal{Z}\) (\(\mathcal{Z}_{L}\), \(\mathcal{Z}_{Q}\), \(\mathcal{Z}_{S}\), \(\mathcal{Z}_{M}\) respectively) is unbounded along the ray that starts at \(\mathbf{z}_{0}\) and follows \(\bar{\mathbf{v}}\), then \(\kappa\) (\(\kappa_{L}\), \(\kappa_{Q}\), \(\kappa_{S}\), \(\kappa_{M}\) respectively) will be zero. If \(\kappa=0\), then we have that \(\frac{1}{\kappa}=\infty\) and therefore \(\mathbf{z}_{1}=\mathbf{z}_{0}+\mathbf{v}\). Fig. 6 shows the results of RAYEN applied to 12 different sets \(\mathcal{Y}\). For each set, we generate 12K samples \(\mathbf{v}\in\mathbb{R}^{n}\) sampled uniformly in the box \([-2.5,2.5]^{n}\) (see Fig. 3), compute the corresponding \(\kappa\), and plot the resulting point \(\mathbf{y}=\mathbf{f}\left(\mathbf{z}_{1}\right)\in\mathbb{R}^{k}\) for each of those samples. All these points \(\mathbf{y}\) are guaranteed to lie in the set \(\mathcal{Y}\). Note also that the density of the produced points is higher in the frontiers of the set due to the \(\text{min}\left(\frac{1}{\kappa},\left\|\mathbf{v}\right\|\right)\) operation performed. ## V Results In this Section, we first apply RAYEN to approximate the optimal solution of a constrained optimization problem (Section V-A), and then analyze its computation time when applied to different constraints of varying dimensions (Section V-B). All the results were obtained using a desktop equipped with an Intel Core i9-12900 \(\times\) 24, 64GB of RAM, and an NVIDIA GeForce RTX 4080. The double-precision floating-point format float64 was used for all the results. ### _Optimization problems_ One of the (many) applications of being able to impose constraints on neural networks is when they are used to approximately solve optimization problems much faster than standard solvers. In this section, we analyze how a neural network equipped with RAYEN is able to approximate the optimal solution of an optimization problem while satisfying all the constraints. We use the optimization problems shown in Table IV: one with only linear constraints, and another one with both linear and convex quadratic constraints. Both are convex optimization problems in which the objective function depends on a parameter \(\mathbf{\gamma}\). Nonconvex objective functions could also be used, but we use convex objective functions to enable a direct comparison with the globally optimal solution obtained using a state-of-the-art convex optimization solver, Figure 6: RAYEN applied to 12 different constraints. For each of the constraints, we generate 12K samples \(\mathbf{v}\in\mathbb{R}^{n}\) sampled uniformly in the box \([-2.5,2.5]^{n}\), compute the corresponding \(\kappa\), and plot the resulting \(\mathbf{y}=\mathbf{f}\left(\mathbf{z}_{0}+\text{min}\left(\frac{1}{\kappa},\left\|\mathbf{v} \right\|\right)\bar{\mathbf{v}}\right)\in\mathbb{R}^{k}\) for each of those samples (see also Fig. 3). For each of the subfigures, the left plot shows the feasible set \(\mathcal{Y}\), while the right plot shows both \(\mathcal{Y}\) and the output samples \(\mathbf{y}\). Note how all these output samples satisfy the constraints. The constraints of the first row have \(k=n=2\). The first two constraints of the second row have \(k=3\) and \(n=2\). The rest of the constraints have \(k=n=3\). RAYEN works in any dimension, but, for visualization purposes, only 2D and 3D examples are shown here. such as Gurobi [37]. A detailed description of these problems is available in Appendix B. We compare RAYEN with the following approaches (see also Table III): * **UU:** Both training and testing are Unconstrained. This method produces directly \(\mathbf{y}=\mathbf{v}\). A soft cost, described below, is added to the training loss to penalize the violation of the constraints. * **UP:** When training, this method simply outputs \(\mathbf{f}(\mathbf{v})\) (see Eq. 7), meaning that \(\mathbf{y}\) is Unconstrained with respect to the inequality constraints. When testing, this method outputs \(\mathbf{f}(\mathbf{v}^{\prime})\), where \(\mathbf{v}^{\prime}\) is the orthogonal Projection of \(\mathbf{v}\) onto \(\mathcal{Z}\). The projection is computed using [20]. This method also has a soft cost in the training loss to penalize the violation of the constraints. * **PP:** The orthogonal Projection onto \(\mathcal{Z}\) is performed during both training and testing. These projections are implemented using [20]. * **DC3:** Algorithm proposed by [24]. Completion is used to enforce the equality constraints, and then an inner gradient decent method (which is also performed in the testing phase) enforces the inequality constraints. This method also includes a soft cost in the training loss to penalize the violation of the constraints. * **Bar:** Generalization of the barycentric coordinates method [9] (proposed for constraints \(\mathbf{A}\mathbf{y}\leq\mathbf{0}\)) for any constraint of the type \(\mathbf{A}\mathbf{y}\leq\mathbf{b}\). This method only supports linear constraints. The matrices of vertices \(\mathbf{V}\) and rays \(\mathbf{R}\) (see Table III) are computed offline using the double description method [10, 11] on the H-representation (half-space representation) of \(\mathcal{Y}_{L}\). As detailed in Table III, the \(\text{softmax}(\cdot)\) operator produces the weights for the convex combination of the vertices, while the \(\text{abs}(\cdot)\) operator produces the weights for the conical combination of the rays. Defining the following soft costs: \[p_{\text{soft},L} := \left\|\text{relu}\left(\mathbf{A}_{1}\mathbf{y}-\mathbf{b}_{1}\right) \right\|^{2}+\left\|\mathbf{A}_{2}\mathbf{y}-\mathbf{b}_{2}\right\|^{2} \tag{14}\] \[p_{\text{soft},Q} := \sum_{i=0}^{\eta-1}\left\|\text{relu}\left(g_{i}\left(\mathbf{y} \right)\right)\right\|^{2} \tag{15}\] the training and test losses in each algorithm are defined in Table IV. In these losses, the soft costs are weighted with \(\omega\geq 0\). The methods **Bar**, **PP**, and **RAYEN** do not need a soft cost since all the constraints are guaranteed to be satisfied both during training and testing. Note also that in **DC3**, the term \(\left\|\mathbf{A}_{2}\mathbf{y}-\mathbf{b}_{2}\right\|^{2}\) of \(p_{\text{soft},L}\) will always be zero since this algorithm satisfies the equality constraints by construction. All the methods are implemented in Pytorch[38], and the Adam optimizer [39] with a learning rate of \(10^{-4}\) is used for training. A total of 2000 epochs are performed for training, and the policy with the best validation loss is selected for testing. For each optimization problem, a total of 1216 samples of \(\mathbf{\gamma}\in\mathbb{R}^{n_{\mathbf{\gamma}}}\) are drawn from uniform distributions detailed in Appendix C, and \(\approx 70\%\) of them are used in the training set and \(\approx 30\%\) in the validation set. The batch size for training is 256. For each optimization problem \(j\in\{1,2\}\), we use two testing sets (each one with 512 samples \(\mathbf{\gamma}\in\mathbb{R}^{n_{\mathbf{\gamma}}}\)): \(\text{TE}_{j,\text{in}}\) and \(\text{TE}_{j,\text{out}}\). \(\text{TE}_{j,\text{in}}\) uses the same distribution as the one used for training, while \(\text{TE}_{j,\text{out}}\) does not. Details on these distributions are available in Appendix C. The goal of using the test set \(\text{TE}_{j,\text{out}}\) is to study how well the trained policy generalizes \begin{table} \begin{tabular}{|c|c|c|c|c|c|c|c|} \hline \multirow{2}{*}{**Method**} & \multirow{2}{*}{\begin{tabular}{c} **Num. of** \\ **params** \\ \end{tabular} } & \multicolumn{6}{c|}{**Optimization 1 (Linear Constraints)**} \\ \cline{3-8} & & \multicolumn{2}{c|}{**Same distribution as training: \(\mathbf{\gamma}\in\text{TE}_{1,\text{in}}\)**} & \multicolumn{2}{c|}{**Different distribution as training: \(\mathbf{\gamma}\in\text{TE}_{1,\text{out}}\)**} \\ \cline{3-8} & & **Normalized Loss** & **Violation** & **Inference Time (\(\mu s\))** & **Normalized Loss** & **Violation** & **Inference Time (\(\mu s\))** \\ \hline \multirow{2}{*}{\begin{tabular}{c} **UU**, \(\omega=0\) \\ **UU**, \(\omega=100\) \\ \end{tabular} } & 0.0006 & 1945.58 & 0.34 & 0.0013 & 1937.43 & 0.43 \\ & \(\omega=100\) & 2.4431 & 2.68 & 0.36 & 1.8362 & 14.02 & 0.43 \\ & \(\omega=100\) & 9872 & 1.0278 & 0.00418 & 0.36 & 1.0220 & 0.08535 & 0.43 \\ & \(\omega=1000\) & 1.4391 & 0.00255 & 0.36 & 1.2263 & 0.19527 & 0.44 \\ & \(\omega=5000\) & 2.1784 & 0.00325 & 0.36 & 1.4767 & 0.02354 & 0.43 \\ \hline \multirow{2}{*}{ \begin{tabular}{c} **UP**, \(\omega=0\) \\ **UP**, \(\omega=100\) \\ **UP**, \(\omega=1000\) \\ **UP**, \(\omega=1000\) \\ **UP**, \(\omega=1000\) \\ **UP**, \(\omega=1000\) \\ **UP**, \(\omega=1000\) \\ **UP**, \(\omega=1000\) \\ **UP**, \(\omega=1000\) \\ **UP**, \(\omega=1000\) \\ **UP**, \(\omega=1000\) \\ **UP**, \(\omega=1000\) \\ **UP**, \(\omega=1000\) \\ **UP**, \(\omega=1000\) \\ **UP**, \(\omega=1000\) \\ **UP**, \(\omega=1000\) \\ **UP**, \(\omega=1000\) \\ **UP**, \(\omega=1000\) \\ **UP**, \(\omega=1000\) \\ **UP**, \(\omega=1000\) \\ **UP**, \(\omega=1000\) \\ **UP**, \(\omega=1000\) \\ **UP**, \(\omega=1000\) \\ **UP**, \(\omega=1000\) \\ **UP**, \(\omega=1000\) \\ **UP**, \(\omega=1000\) \\ **UP**, \(\omega=1000\) \\ **UP**, \(\omega=1000\) \\ **UP**, \(\omega=1000\) \\ **UP**, \(\omega=1000\) \\ **UP**, \(\omega=1000\) \\ **UP**, \(\omega=1000\) \\ **UP**, \(\omega=1000\) \\ **UP**, \(\omega=1000\) \\ **UP**, \(\omega=1000\) \\ **UP**, \(\omega=1000\) \\ **UP**, \(\omega=1000\) \\ **UP**, \(\omega=1000\) \\ **UP**, \(\omega=1000\) \\ **UP**, \(\omega=1000\) \\ **UP**, \(\omega=1000\) \\ **UP**, \(\omega=1000\) \\ **UP**, \(\omega=1000\) \\ **UP**, \(\omega=1000\) \\ **UP**, \(\omega=1000\) \\ **UP**, \(\omega=1000\) \\ **UP**, \(\omega=1000\) \\ **UP**, \(\omega=1000\) \\ **UP**, \(\omega=1000\) \\ **UP**, \(\omega=1000\) \\ **UP**, \(\omega=1000\) \\ **UP**, \(\omega=1000\) \\ **UP**, \(\omega=1000\) \\ **UP**, \(\omega=1000\) \\ **UP**, \(\omega=1000\) \\ **UP**, \(\omega=1000\) \\ **UP**, \(\omega=1000\) \\ **UP**, \(\omega=1000\) \\ **UP**, \(\omega=1000\) \\ **UP**, \(\omega=1000\) \\ **UP**, \(\omega=1000\) \\ **UP**, \(\omega=1000\) \\ **UP**, \(\omega=1000\) \\ **UP**, \(\omega=1000\) \\ **UP**, \(\omega=1000\) \\ **UP**, \(\omega=1000\) \\ **UP**, \(\omega=1000\) \\ **UP**, \(\omega=1000\) \\ **UP**, \(\omega=1000\) \\ **UP**, \(\omega=1000\) \\ **UP**, \(\omega=1000\) \\ **UP**, \(\omega=1000\) \\ **UP**, \(\omega=1000\) \\ **UP**, \(\omega=1000\) \\ **UP**, \(\omega=1000\) \\ **UP**, \(\omega=1000\) \\ **UP**, \(\omega=1000\) \\ **UP**, \(\omega=1000\) \\ **UP**, \(\omega=1000\) \\ **UP**, \(\omega=1000\) \\ **UP**, \(\omega=1000\) \\ **UP**, \(\omega=1000\) \\ **UP**, \(\omega=1000\) \\ **UP**, \(\omega=10000\) \\ **UP**, \(\omega=1000\) \\ **UP**, \(\omega=1000\) \\ **UP**, \(\omega=1000\) \\ **UP**, \(\omega=1000\) \\ **UP**, \( to unseen inputs. The results for these test sets are shown in Table V and Fig. 7. Defining the normalized loss as the obtained loss divided by the globally-optimal loss found by Gurobi [37], the following conclusions can be extracted from these results: **Same distribution as in training:** * Optimization 1: **RAYEN** is able to obtain the normalized loss closest to the globally-optimal one, while guaranteeing a zero violation of the constraints. The methods **UP**, **PP**, **DC3** with \(\omega=5000\), **Bar**, and **RAYEN** generate feasible solutions. In terms of computation time, **RAYEN** is between 20 and 7468 times faster than these methods. * Optimization 2: Again, **RAYEN** is able to obtain the normalized loss closest to the globally-optimal one while guaranteeing a zero violation of the constraints. Compared to the feasible approaches (**UP** and **PP**), **RAYEN**'s computation time is between 2094 and 2417 times faster. **Generalization: Different distribution as in training:** * Optimization 1: Both **RAYEN** and **Bar** are able to obtain normalized losses very close to the globally-optimal one, while guaranteeing a zero violation of the constraints. Although **Bar**'s loss is slightly better than **RAYEN**'s (1.0070 vs. 1.0076), **Bar**'s method is 16 times slower, and it requires 197 times as many parameters as **RAYEN**. This high number of parameters required by **Bar** is due to the high number of vertices of the polyhedron \(\mathcal{Y}\). Note also that **Bar** only supports linear constraints. * Optimization 2: **RAYEN** is the algorithm that has the best generalization (smallest normalized loss) while achieving a zero violation of the constraints. It is also important to note that, when tested in the same distribution as the training set, the violations of both **UU** and **DC3** tend to decrease with higher values of \(\omega\). These violations however tend to become quite large when using a different distribution than the one used in training. ### _Computation time_ To study the computation time of the proposed approach, we generate random dense constraints of varying dimensions, and measure the computation time required by RAYEN to impose these constraints on \(\mathbf{y}\in\mathbb{R}^{k}\) for a random \(\mathbf{v}\in\mathbb{R}^{n}\) (see Fig. 3). All the details of how these random constraints are Figure 8: Computation times of RAYEN for different dense random constraints of varying size. In these plots, \(\mathbf{y}\in\mathbb{R}^{k}\), \(\eta\) is the number of quadratic constraints (see Eq. 3), and \(\mu\) is the number of SOC constraints (see Eq. 4). The plots show the inference time for each sample in a batch of 2000 samples. The double-precision floating-point format float64 was used. Figure 7: Comparison of the computation time vs. the normalized loss for the methods that generate feasible solutions. The dashed line corresponds to a normalized cost of 1. generated are available in the attached code. The computation times per sample (in a batch of 2000 samples) achieved by RAYEN are available in Fig. 8. Note that they are short, even for high-dimensional variables, as shown in the following statistics: * 2000 linear constraints on a 10K-dimensional variable: \(<0.9\) ms. * 1000 dense convex quadratic constraints on a 1K-dimensional variable: \(<8\) ms. * 500 dense SOC constraints on a 1K-dimensional variable with matrices \(\mathbf{M}_{j}\) of 300 rows: \(<8\) ms. * A dense \(300\times 300\) LMI constraint on a 10K-dimensional variable: \(<11\) ms. ## VI Discussion and Limitations ### _Nonconvex Constraints_ Compared to methods such as DC3 [24], one limitation of the proposed framework is that right now it does not support generic nonconvex constraints. However, and as we have seen from the results in Section V-A, when the constraints are convex the performance of our method is much better than [24]. As future work (see also Section VII), we plan to extend RAYEN to nonconvex constraints, leveraging techniques such as sequential convexification. ### _Non-fixed Constraints_ This paper has focused on the case where the parameters that define the constraints (i.e., \(\mathbf{A}_{1},\mathbf{b}_{1},\mathbf{A}_{2},\mathbf{b}_{2},\mathbf{P}_{i},...\)) are fixed and known beforehand. A natural question to ask is whether or not RAYEN could be used when these parameters are not fixed, and depend on the previous layers (or input) of the network. The answer turns out to be yes, as long as some extra care is taken: * The constraints must define a nonempty set at all times, and \(\mathcal{Z}\) must have interior points. There are many different ways to ensure this. For instance, if there are no equality constraints, one way would be to ensure these conditions: \[\mathbf{b}_{1}>\mathbf{0}\] (16) \[r_{i}<0\;\;i=0,...,\eta-1\] (17) \[d_{j}>\|\mathbf{s}_{j}\|\;\;\;j=0,...,\mu-1\] (18) \[\mathbf{F}_{k}\succ\mathbf{0}\] (19) Then, we can take \(\mathbf{z}_{0}=\mathbf{0}\), as it is guaranteed to be in the interior of \(\mathcal{Z}\). Eqs. 16, 17, and 18 can be easily enforced by, e.g., using sigmoid functions. Eq. 19 can be enforced by setting \[\mathbf{F}_{k}:=\mathbf{\Gamma}^{T}\mathbf{\Gamma}+\epsilon\mathbf{I}\;,\] where \(\epsilon>0\) is a predefined scalar, and where the matrix \(\mathbf{\Gamma}\) depends on the previous layers (or input) of the network. When there are only linear constraints, other ways to guarantee a nonempty feasible set are explained in [24, Section 4.1] and [19, Appendix A]. * \(\mathbf{P}_{i}\succeq\mathbf{0}\) (\(i=0,...,\eta-1\)) is required. Without any loss of generality, this can be enforced by setting \(\mathbf{P}_{i}:=\mathbf{V}_{i}^{T}\mathbf{V}_{i}\), where \(\mathbf{V}_{i}\) is a matrix that depends on the previous layers (or input) of the network. * The matrices \(\mathbf{F}_{\alpha}\) (\(\alpha=0,...,k\)) must be symmetric. One way to guarantee this is by setting \(\mathbf{F}_{\alpha}:=(\mathbf{\Delta}_{\alpha}+\mathbf{\Delta}_{\alpha}^{T})/2\), where \(\mathbf{\Delta}_{\alpha}\) is a matrix that depends on the previous layers (or input) of the network. * \(\text{aff}\left(\left\{\mathbf{y}\in\mathbb{R}^{k}|\mathbf{A}_{1}\mathbf{y}\leq\mathbf{b}_{1} \right\}\cap\mathcal{Y}_{\mathcal{Q}}\cap\mathcal{Y}_{\mathcal{S}}\cap\mathcal{ Y}_{M}\right)=\mathbb{R}^{k}\). Intuitively, this means that the inequality constraints must not _hide_ equality constraints. We can then take \(\mathbf{A}_{\mathcal{I}}\equiv\mathbf{A}_{1}\), \(\mathbf{b}_{\mathcal{I}}\equiv\mathbf{b}_{1}\), \(\mathbf{A}_{\mathcal{E}}\equiv\mathbf{A}_{2}\), and \(\mathbf{b}_{\mathcal{E}}\equiv\mathbf{b}_{2}\). If these conditions are satisfied, then the offline phase (Section III) is not needed, since \(\mathbf{z}_{0}\) is already known, and the matrices \(\mathbf{A}_{p}\) and \(\mathbf{b}_{p}\) can be easily found online by simply computing the nullspace of \(\mathbf{A}_{\mathcal{E}}\) (Eq. 8). ## VII Conclusion and Future work This work presented RAYEN, a framework to impose hard convex constraints on the output or latent variable of a neural network. RAYEN is able to guarantee by construction the satisfaction of any combination of linear, convex quadratic, SOC, and LMI constraints. When applied to approximate the solution of constrained optimization problems, RAYEN showcases computation times between 20 and 7468 times faster than state-of-the-art algorithms, while guaranteeing the satisfaction of the constraints at all times and obtaining a loss very close to the optimal one. Future work includes the incorporation of more types of convex constraints, like for example exponential cone constraints. RAYEN could still be used for any convex constraint as long as the corresponding \(\kappa_{\square}\) for that constraint can be found. Even if an analytic solution for \(\kappa_{\square}\) does not exist, one could always leverage implicit layers that find the roots of nonlinear equations [40] to numerically find it. We also plan to study how RAYEN could be used to impose generic nonconvex constraints [24, 41] (via, e.g., sequential convexification), to impose Lipschitz constraints [42], to impose generic matrix manifolds constraints [43], or leveraged for safe robot control [44]. _Proof of \(\text{eig}\left(-\mathbf{H}^{-1}\mathbf{S}\right)=\text{eig}\left(\mathbf{L}^{T}\left(- \mathbf{S}\right)\mathbf{L}\right)\)_ Given that \(\mathbf{H}^{-1}\succ\mathbf{0}\) (because \(\mathbf{H}\succ\mathbf{0}\)), we can write its Cholesky decomposition as \(\mathbf{H}^{-1}=\mathbf{L}\mathbf{L}^{T}\), where \(\mathbf{L}\) is a lower triangular matrix with positive diagonal entries. Hence: \[\text{eig}\left(-\mathbf{H}^{-1}\mathbf{S}\right)=\text{eig}\left(\mathbf{L}\mathbf{L}^{T} \left(-\mathbf{S}\right)\right)=\text{eig}\left(\mathbf{L}^{T}\left(-\mathbf{S}\right) \mathbf{L}\right)\;,\] where in the last step we have use the fact that \(\text{eig}\left(\mathbf{A}\mathbf{B}\right)=\text{eig}\left(\mathbf{B}\mathbf{A}\right)\) for square matrices \(\mathbf{A}\) and \(\mathbf{B}\) (see, e.g., [45]). As \(\mathbf{L}^{T}\left(-\mathbf{S}\right)\mathbf{L}\) is clearly a real symmetric matrix, this also proves that all the eigenvalues of \(-\mathbf{H}^{-1}\mathbf{S}\) are real, even though \(-\mathbf{H}^{-1}\mathbf{S}\) may not be a symmetric matrix [46]. ### _Planning problem_ The optimization problems used in Section V-A are trajectory optimization problems that aim at obtaining the clamped uniform B-Spline that minimizes a weighted sum of the velocity smoothness, the acceleration smoothness, and the jerk smoothness, while ensuring that the whole trajectory remains within a sequence of overlapping polyhedra that represent the free space. This problem (or small variations of it) appears extensively in many trajectory planning problems in Robotics, such as [3, 47, 52, 53]. Using the notation shown in in Table VI, the optimization problems are available in Table VII. The constraints are these: * **Initial and final constraints:** The initial and final states are stop conditions. The initial position is fixed, while the final position of the trajectory is included in the cost as a soft constraint. This final position is taken inside \(\mathcal{P}_{n_{\text{polyh}}-1}\) (the last polyhedron of the corridor). * **Corridor constraints:** Each interval of the trajectory is assigned to one polyhedron, and the convex hull property of the MINVO basis [54] is leveraged to ensure that each interval remains inside that assigned polyhedron. Compared to approaches that only impose constraints on discretization points along the trajectory, this approach guarantees safety for the whole trajectory \(t\in[0,t_{f}]\). * **Dynamic limit constraints:** Optimization 1 uses linear constraints to impose a maximum velocity \(v_{\text{max}}\) and acceleration \(a_{\text{max}}\). Optimization 2 uses quadratic constraints instead, and also imposes a maximum jerk \(j_{\text{max}}\). Similar to the corridor constraints, we also leverage here the convex hull property of the MINVO basis. Using RAYEN, some examples of the trajectories generated by the trained network for 100 different \(\boldsymbol{\gamma}\) taken from the testing set \(\text{TE}_{1,\text{in}}\) (see Appendix C) are shown in Fig. 9. All the constraints are guaranteed to be satisfied at all times.8 Footnote 8: As the degree of the spline of the Optimization 1 is 2, then the term \(\int_{0}^{t_{f}}\left\|\mathbf{j}(t)\right\|^{2}dt\) is clearly 0, and therefore \(\alpha_{\text{j}}\) does not affect the optimal solution. We keep this term simply for consistency purposes with Optimization 2, but it could also be removed as well. ### _Training, validation, and test sets_ The \(\boldsymbol{\gamma}\) used in Table III (the input of the network) is \(\boldsymbol{\gamma}:=\left[\begin{array}{cc}\alpha_{\text{v}}&\alpha_{\text {a}}&\alpha_{\text{j}}\end{array}\mathbf{p}_{f}^{T}\right]^{T}\), which contains the nonnegative weights \(\{\alpha_{\text{v}},\alpha_{\text{a}},\alpha_{\text{j}}\}\) and the final position \(\mathbf{p}_{f}\). Letting \(j\in\{1,2\}\) denote the optimization problem, we use the following training, validation, and test sets: * **Training and Validation sets:**\(\left[\begin{array}{cc}\alpha_{\text{v}}&\alpha_{\text{a}}&\alpha_{\text{j}} \end{array}\right]^{T}\) is taken uniformly within the cube \([0.0,1.0]^{3}\), while \(\mathbf{p}_{f}\) is taken uniformly within \(\mathcal{P}_{n_{\text{polyh}}-1}\). * **Testing sets:* * \(\text{TE}_{j,\text{in}}\): Same distributions as above. * \(\text{TE}_{j,\text{out}}\): \(\left[\begin{array}{cc}\alpha_{\text{v}}&\alpha_{\text{a}}&\alpha_{\text{j}} \end{array}\right]^{T}\) is taken uniformly within the cube \([1.0,2.0]^{3}\), while \(\mathbf{p}_{f}\) is taken uniformly within \(\mathcal{P}_{n_{\text{polyh}}-1}\). \begin{table} \begin{tabular}{|c|c|} \hline **Symbol** & **Meaning** \\ \hline \hline \(\mathbf{p},\mathbf{v},\mathbf{a},\mathbf{j}\) & Position, velocity, acceleration, and jerk \\ \hline \(\mathbf{p}_{\text{o}},\mathbf{p}_{f}\) & Initial and final positions \\ \hline \(n_{\text{inter}}\) & Number of intervals of the B-Spline \\ \hline \(n_{\text{rep}}\) & Number of position control points of the B-Spline \\ \hline \(a_{\text{j}}\) & \(l\)-th acceleration control point of the B-Spline \\ \hline \(j_{\text{j}}\) & \(l\)-th jerk control point of the B-Spline \\ \hline \(j,j\) & \(j\) is the index of the interval of the trajectory, \\ \hline \(\mathcal{Q}_{j}^{\text{MV}},j_{j}^{\text{MV}}\) & \(\frac{\mathcal{Q}_{j}^{\text{MV}}}{\text{s}}\) is the set of position control points of the interval \\ \(j\) using the MINVO basis. Analogous definition for the velocity control points \(\mathcal{V}_{\text{MV}}^{\text{MV}}\) \\ \hline \(\mathcal{P}_{0},\ldots,\mathcal{P}_{n_{\text{polyh}}-1}\) & Sequence of overlapping polyhedra. They can be \\ \cline{1-1} & obtained using methods such as [47, 48, 49, 50, 51] \\ \hline \([a]\) & Floor function (i.e., rounding to the nearest integer \(\leq a\)) \\ \hline \end{tabular} \end{table} Table VI: Notation used in Appendix B. Figure 9: Trajectories generated by the trained network equipped with RAYEN. For each optimization \(j\in\{1,2\}\), each plot shows the trajectories obtained using 100 different \(\boldsymbol{\gamma}\) from the testing set \(\text{TE}_{j,\text{in}}\). \(\mathbf{p}_{0}\) is the initial condition, and \(\mathcal{P}_{i}\) denotes each polyhedron. The final position \(\mathbf{p}_{f}\) is taken randomly inside the last polyhedron. ## Acknowledgment The authors would like to thank Victor Klemm and Dr. Kasra Khosoussi for helpful insights and discussions. Research supported in part by the Air Force Office of Scientific Research MURI FA9550-19-1-0386.
2309.00588
Discrete Morphological Neural Networks
A classical approach to designing binary image operators is Mathematical Morphology (MM). We propose the Discrete Morphological Neural Networks (DMNN) for binary image analysis to represent W-operators and estimate them via machine learning. A DMNN architecture, which is represented by a Morphological Computational Graph, is designed as in the classical heuristic design of morphological operators, in which the designer should combine a set of MM operators and Boolean operations based on prior information and theoretical knowledge. Then, once the architecture is fixed, instead of adjusting its parameters (i.e., structural elements or maximal intervals) by hand, we propose a lattice descent algorithm (LDA) to train these parameters based on a sample of input and output images under the usual machine learning approach. We also propose a stochastic version of the LDA that is more efficient, is scalable and can obtain small error in practical problems. The class represented by a DMNN can be quite general or specialized according to expected properties of the target operator, i.e., prior information, and the semantic expressed by algebraic properties of classes of operators is a differential relative to other methods. The main contribution of this paper is the merger of the two main paradigms for designing morphological operators: classical heuristic design and automatic design via machine learning. As a proof-of-concept, we apply the DMNN to recognize the boundary of digits with noise, and we discuss many topics for future research.
Diego Marcondes, Junior Barrera
2023-09-01T17:04:48Z
http://arxiv.org/abs/2309.00588v2
# Discrete Morphological Neural Networks ###### Abstract. A classical approach to designing binary image operators is Mathematical Morphology (MM). We propose the Discrete Morphological Neural Networks (DMNN) for binary image analysis to represent W-operators and estimate them via machine learning. A DMNN architecture, which is represented by a Morphological Computational Graph, is designed as in the classical heuristic design of morphological operators, in which the designer should combine a set of MM operators and Boolean operations based on prior information and theoretical knowledge. Then, once the architecture is fixed, instead of adjusting its parameters (i.e., structural elements or maximal intervals) by hand, we propose a lattice gradient descent algorithm (LGDA) to train these parameters based on a sample of input and output images under the usual machine learning approach. We also propose a stochastic version of the LGDA that is more efficient, is scalable and can obtain small error in practical problems. The class represented by a DMNN can be quite general or specialized according to expected properties of the target operator, i.e., prior information, and the semantic expressed by algebraic properties of classes of operators is a differential relative to other methods. The main contribution of this paper is the merger of the two main paradigms for designing morphological operators: classical heuristic design and automatic design via machine learning. Thus, conciliating classical heuristic morphological operator design with machine learning. We apply the DMNN to recognize the boundary of digits with noise, and we discuss many topics for future research. ## 1. Introduction ### Mathematical Morphology and W-operators Mathematical Morphology (MM), a theory initiated in the sixties by George Matheron [30] and Jean Serra [42, 43] at the Fontainebleau campus of the Ecole Superieur des Mines de Paris (ESMP), has been important for the development of the field of image analysis. Lattices are the fundamental algebraic structure in MM, which studies mappings between complete lattices, and, from the sixties to the eighties, this theory evolved from Boolean to general lattice mappings [42]. These mappings are decomposed by lattice operations and two pairs of dual elementary operators: erosion and dilation, which commute, respectively, with infimum and supremum, as well as, anti-dilation and anti-erosion, which commute, respectively, with supremum-infimum and infimum-supremum. Based on these elementary operators, Banon and Barrera [4] proposed two dual minimal representations for any lattice operator: one in terms of supremum of sup-generating operators (i.e., infimum of an erosion and an anti-dilation) and another in terms of infimum of inf-generating operators (i.e., supremum of a dilation and an anti-erosion). A particular class of morphological operators for binary image analysis, very important in practical applications, are the W-operators [9]. Let a binary image \(X\) be a subset of the image domain \(E\) and let \((\mathcal{P}(E),\subseteq)\) be the Boolean lattice of the powerset of \(E\). A set operator \(\psi\) is a mapping from \(\mathcal{P}(E)\) to \(\mathcal{P}(E)\) that transforms image \(X\in\mathcal{P}(E)\) into image \(\psi(X)\). When \((E,+)\) is an _Abelian group_ with respect to a binary operation \(+\), a set operator \(\psi\) is a W-operator if, and only if, it is translation invariant and locally defined in a window \(W\in\mathcal{P}(E)\), i.e., \(\psi(X+h)=\psi(X)+h\) and \[h\in\psi(X)\iff f_{\psi}((X-h)\cap W)=1,\text{ for }h\in E,\] in which \(f_{\psi}:\mathcal{P}(W)\to\{0,1\}\) is the characteristic function of \(\psi\). In this case, the kernel of \(\psi\) is \(\mathcal{K}_{W}(\psi)=\{X\in\mathcal{P}(W):f_{\psi}(X)=1\}\) and the basis of \(\psi\), denoted by \(\boldsymbol{B}_{W}(\psi)\), is the collection of maximal intervals in \(\mathcal{K}_{W}(\psi)\). The sup-generating operators \[\lambda_{[A,B]}(X)=\{h\in E:A\subseteq(X-h)\cap W\subseteq B\},\qquad\ X\in \mathcal{P}(E),\] associated to intervals \([A,B]\subseteq\mathcal{P}(W)\) are the building blocks to represent any W-operator: \[\psi(X)=\bigcup\big{\{}\lambda_{[A,B]}(X):[A,B]\in\boldsymbol{B}_{W}(\psi) \big{\}}\qquad\qquad X\in E.\] This expression has also a dual form based on inf-generating operators. In fact, any W-operator can be represented in terms of unions, intersections, compositions, and complements of erosions, dilations, anti-erosions and anti-dilations, and have several equivalent representations, but all of them can be converted into a unique basis representation [4]. It is possible to compute incrementally the basis of any W-operator from any representation of it in terms of the elementary operators of mathematical morphology (i.e., erosion and dilation), the Boolean lattice operations, (i.e., intersection, union and complement), and the basis of the identity operator [9]. ### Design of set operators From several studies about mathematical morphology operators [42, 43], followed the proposal of many families of operators which can be combined heuristically to solve image analysis problems. Some classes of operators include the hit-or-miss operators [42], morphological filters [44], and watershed segmentation [11]. The research group at ESMP developed procedures to heuristically design operators, which require prior information about the problem at hand, knowledge of several classes of operators (the so-called MM toolbox), and the ability to combine them through composition and lattice operations. Once the combination of operators is performed, the designer should carefully adjust the parameters of the designed operator to obtain a solution that properly solves the practical problem. Specialized software, whose architectures were based on basic operators and operations (i.e., erosion, dilation, infimum, supremum, complement), from which more complex operators (i.e., skeletons, filters, etc) can be built, were implemented in the nineties. In special, the researchers and engineers of the Center for Mathematical Morphology of ESMP were the pioneers in developing software and hardware for morphological image processing, and the _mmach_ toolbox for the Khoros system [6], developed by researchers of USP, UNICAMP and INPE in Brazil, became popular at the end of the nineties. These software have had a considerable impact on the solution of a large class of image analysis problems. We refer to [6, 16, 46, 48] for more details on practical methods for the design of MM operators. Although the heuristic design of morphological operators had a great impact on image analysis, it is a time-consuming manual procedure which does not scale efficiently to more complex problems. Since combining basic morphological operators to form a complex image processing pipeline is not a trivial task, a natural idea is to develop methods to automatically design morphological operators. At the end of the eighties, M. Shimidt [41] proposed a design procedure based on artificial intelligence, which combined W-operators (represented by compositions of parameterized morphological operators) and adjusted their parameters. Since the late nineties, approaches for the automatic design of morphological operators based on machine learning have been proposed, mainly by the work of Ed. Dougherty, J. Barrera and their collaborators [10], and have been extensively applied in the literature with great success to solve specific problems [7, 12, 13, 15, 21, 22, 24, 25, 26, 27, 32, 33, 40]. Many of these approaches are also heuristics, which may consider prior information about the problem at hand. However, the parameters of the operators are more efficiently adjusted by learning from data and good practical results have been obtained. More details about MM in the context of machine learning may be found in [8, 23]. In the nineties [38], and then more recently, MM methods have been studied in connection with deep neural networks, by either combining convolutional neural networks (CNN) with a morphological operator [29], or by replacing the convolution operations of CNN with basic morphological operators, such as erosions and dilations, obtaining the so-called morphological neural networks (MNN) [19, 28, 31]. A MNN has the general framework of neural networks, and its specificity is on the fact that the layers realize morphological operations. Although it has been seen empirically that convolutional layers could be replaced by morphological layers [19], and MNN have shown a better performance than CNN in some tasks [28], MNN have lost the spirit of MM, that is a careful theoretical design of the operator based on prior information, followed by the adjustment or learning of its parameters implying a fully understanding of its properties. This detachment from classical MM made MNN opaque and as much a black-box as CNN, so no real gain in control and interpretability is obtained with MNN when compared to CNN. ### Main contributions In this context, we propose the Discrete Morphological Neural Networks (DMNN) to represent and automatically design W-operators via machine learning. The design of a DMNN architecture, which is represented by a Morphological Computational Graph, is equivalent to the first part of the classical heuristic design of operators, in which the designer should combine basic operators and operations based on prior information and theoretical knowledge of MM. When such a combination satisfies certain axioms, it is equivalent to an architecture of a canonical DMNN. Then, once the architecture is fixed, instead of adjusting its parameters by hand, we propose the lattice gradient descent algorithm (LGDA) to train these parameters based on a sample of input and output images under the usual machine learning approach for learning W-operators. Since the LGDA, that is based on the U-curve algorithms [3, 18, 36, 37], is a combinatorial algorithm whose complexity increases exponentially with the number of computational nodes in the architecture computational graph, we also propose a stochastic version of it that, even though is suboptimal, is much more efficient, is scalable and can obtain good results in practical problems. The main contribution of this paper is the merger of the two main paradigms for designing morphological operators: classical heuristic design and automatic design via machine learning. On the hand, a DMNN architecture is equivalent to the manual combination of basic operators performed in heuristic design based on prior information and known properties of MM. On the other hand, the training of an architecture, or equivalently the adjustment of the parameters of the heuristic combination, is performed based on data under a machine learning framework. The adjustment of the parameters scales to more complex problems if one considers the stochastic LGDA, and the learning via the LGDA is general and not problem specific as many of the automatic design methods based on machine learning, so the DMNN is a contribution to both design paradigms. This merger is a flexible and transparent approach for automatically designing W-operators in general settings via machine learning. ### Paper structure In Section 2, we present the main elements of Boolean lattices, in Section 3, we present the canonical decomposition of set operators, and in Section 4, we summarize the main results of [9] about the composition of operators in the canonical form. Sections 2 to 4 follow the presentation of [9]. In Section 5, we define the Morphological Computation Graph and the Discrete Morphological Neural Networks, and then show that DMNN are universal representers of translation invariant and locally defined set operators. In Section 6, we particularize to the canonical DMNN, and in Section 7, we propose the lattice gradient descent algorithm to train them. In Section 8, we illustrate the proposed method with an application, and in Section 9, we discuss the main contributions of this paper. ## 2. Elements of Boolean lattices Let \(E\) by a non-empty set, and let \(W\) be a finite subset of \(E\). We assume that \((E,+)\) is an _Abelian group_ with respect to a binary operation denoted by \(+\). We denote the zero element of \(E\) by \(o\). Let \(\mathcal{P}(W)\) be the collection of all subsets of \(W\) and let \(\subseteq\) be the usual inclusion relation on sets. The pair \((\mathcal{P}(W),\subseteq)\) is a complete Boolean lattice, with least and greatest element \(\emptyset\) and \(W\), respectively. The intersection and union of \(X_{1}\) and \(X_{2}\) in \(\mathcal{P}(W)\) are, respectively, \(X_{1}\cap X_{2}\) and \(X_{1}\cup X_{2}\). Given \(A,B\in\mathcal{P}(W)\), the sub-collection \([A,B]\) of \(\mathcal{P}(W)\) defined by \[[A,B]=\{X\in\mathcal{P}(W):A\subseteq X\subseteq B\}\] is called a closed interval, or simply interval. If \(A\subseteq B\), then \(A\) and \(B\) are called, respectively, the left and right extremities of \([A,B]\). For all pairs \((A,B)\) such that \(A\nsubseteq B\), \([A,B]\) represents the empty collection \(\emptyset\). We will denote sub-collections of \(\mathcal{P}(W)\) by uppercase script letters \(\mathcal{A},\mathcal{B},\ldots,\mathcal{X},\mathcal{Y},\mathcal{Z}\). The collections of closed intervals will be denoted by uppercase bold face letters \(\boldsymbol{A},\boldsymbol{B},\ldots,\boldsymbol{X}\), \(\boldsymbol{Y},\boldsymbol{Z}\). An element of a collection of closed intervals \(\boldsymbol{X}\) is called _maximal in_\(\boldsymbol{X}\) if no other element of \(\boldsymbol{X}\) properly contains it, that is, \(\forall[A,B]\in\boldsymbol{X}\), \[[A,B]\text{ is maximal in }\boldsymbol{X}\iff\forall[A^{\prime},B^{ \prime}]\in\boldsymbol{X},[A,B]\subseteq[A^{\prime},B^{\prime}]\implies[A,B] =[A^{\prime},B^{\prime}].\] The collection of maximal closed intervals in \(\boldsymbol{X}\) is denoted by \(\operatorname{Max}(\boldsymbol{X})\). Let \(\mathcal{X}\) be a sub-collection of \(\mathcal{P}(W)\). The collection of all maximal closed intervals contained in \(\mathcal{X}\) is denoted by \(\boldsymbol{M}(\mathcal{X})\) and is given by \[\boldsymbol{M}(\mathcal{X})=\operatorname{Max}\left(\{[A,B]\subseteq\mathcal{ P}(W):[A,B]\subseteq\mathcal{X}\}\right).\] Usually, we will denote a sub-collection and the set of maximal intervals contained in it by the same letter, for example \(\boldsymbol{X}=\boldsymbol{M}(\mathcal{X})\). We denote by \(\cup\boldsymbol{X}\) the collection of all elements of \(\mathcal{P}(W)\) that are elements of closed intervals in \(\boldsymbol{X}\), that is \[\cup\boldsymbol{X}=\{X\in\mathcal{P}(W):X\in[A,B],[A,B]\in\boldsymbol{X}\}.\] Note that, for any \(\mathcal{X}\subseteq\mathcal{P}(W),\;\cup\boldsymbol{X}=\mathcal{X}\). Since \(W\) is finite and \(\mathcal{X}\subseteq\mathcal{P}(W)\), for any \([A,B]\subseteq\mathcal{X}\), there exists \([A^{\prime},B^{\prime}]\in\boldsymbol{M}(\mathcal{X})\) such that \([A,B]\subseteq[A^{\prime},B^{\prime}]\), and hence any sub-collection \(\mathcal{X}\) can be represented by its maximal closed intervals. Let \(\mathcal{P}(\mathcal{P}(W))\) be the collection of all sub-collections of \(\mathcal{P}(W)\) and let \(\subseteq\) be the usual inclusion relation on sets. The pair \((\mathcal{P}(\mathcal{P}(W)),\subseteq)\) is a complete Boolean lattice. The least and the greatest element of \(\mathcal{P}(\mathcal{P}(W))\) are, respectively, \(\emptyset\) and \(\mathcal{P}(W)\). The intersection and the union of \(\mathcal{X}_{1}\) and \(\mathcal{X}_{2}\) in \(\mathcal{P}(\mathcal{P}(W))\) are, respectively, \(\mathcal{X}_{1}\cap\mathcal{X}_{2}\) and \(\mathcal{X}_{1}\cup\mathcal{X}_{2}\). The complementary collection of a sub-collection \(\mathcal{X}\) in \(\mathcal{P}(\mathcal{P}(W))\), with respect to \(\mathcal{P}(W)\), is defined as \(\mathcal{X}^{c}=\{X\in\mathcal{P}(W):X\notin\mathcal{X}\}\). Let \(\Pi_{W}\coloneqq\{\boldsymbol{M}(\mathcal{X}):\mathcal{X}\subseteq\mathcal{P} (W)\}\) be the collection of the sub-collections of maximal intervals of \(\mathcal{P}(W)\). We will define the partial order \(\leqslant\) on the elements of \(\Pi_{W}\) by setting, \(\forall\boldsymbol{X},\boldsymbol{Y}\in\Pi_{W}\), \[\boldsymbol{X}\leqslant\boldsymbol{Y}\iff\forall[A,B]\in\boldsymbol{X}, \exists[A^{\prime},B^{\prime}]\in\boldsymbol{Y}:[A,B]\subseteq[A^{\prime},B^{ \prime}].\] The poset \((\Pi_{W},\leqslant)\) constitutes a complete Boolean lattice, with infimum, supremum and complement operations given, respectively, by \[\boldsymbol{X}\cap\boldsymbol{Y}=\boldsymbol{M}(\mathcal{X}\cap\mathcal{Y}) \qquad\boldsymbol{X}\sqcup\boldsymbol{Y}=\boldsymbol{M}(\mathcal{X}\cup \mathcal{Y})\qquad\bar{\boldsymbol{X}}=\boldsymbol{M}(\mathcal{X}^{c})\] for all \(\boldsymbol{X},\boldsymbol{Y}\in\Pi_{W}\), in which \(\boldsymbol{X}=\boldsymbol{M}(\mathcal{X})\) and \(\boldsymbol{Y}=\boldsymbol{M}(\mathcal{Y})\). These expressions follow since the mapping \(\boldsymbol{M}(\cdot)\), defined from \(\mathcal{P}(\mathcal{P}(W))\) to \(\Pi_{W}\), is a lattice isomorphism. The inverse of the mapping \(\boldsymbol{M}(\cdot)\) is the mapping \(\cup(\cdot)\). In particular, the least and the greatest element of \((\Pi_{W},\leqslant)\) are, respectively, \(\boldsymbol{M}(\ \(\theta,\lambda,\mu,...\) and collections of set operators by uppercase Greek letters \(\Psi,\Theta,\Gamma,\Lambda,\Delta,\Phi,\Omega,\Sigma,...\). The set \(\Psi\) of all the operators from \(\mathcal{P}(E)\) to \(\mathcal{P}(E)\) inherits the complete lattice structure of \((\mathcal{P}(E),\subseteq)\) by setting, \(\forall\psi_{1},\psi_{2}\in\Psi\), \[\psi_{1}\leqslant\psi_{2}\iff\psi_{1}(X)\subseteq\psi_{2}(X),\forall X\in \mathcal{P}(E). \tag{3.1}\] The supremum and infimum of a subset \(\Theta\subseteq\Psi\) of the complete lattice \((\Psi,\leqslant)\) satisfy \[\left(\bigvee\Theta\right)(X)=\bigcup\{\theta(X):\theta\in\Theta\}\qquad \qquad X\in\mathcal{P}(E),\] and \[\left(\bigwedge\Theta\right)(X)=\bigcap\{\theta(X):\theta\in\Theta\}\qquad \qquad X\in\mathcal{P}(E),\] respectively. For any \(h\in E\) and \(X\in\mathcal{P}(E)\), the set \[X+h\coloneqq\{x\in E:x-h\in X\}\] is called the translation of \(X\) by \(h\). We may also denote \(X+h\) as \(X_{h}\) and, in special, \(X_{o}=X\) in which \(o\) is the origin of \(E\). Let \(X^{t}\) be the transpose of \(X\in\mathcal{P}(E)\) defined as \[X^{t}=\{y\in E:y=-x,x\in X\}.\] A set operator \(\psi\) is called _translation invariant_ (t.i) if, and only if, \(\forall h\in E\), \[\psi(X+h)=\psi(X)+h\qquad\qquad\qquad X\in\mathcal{P}(E).\] Let \(W\) be a finite subset of \(E\). A set operator \(\psi\) is called _locally defined within a window_\(W\) if, and only if, \(\forall h\in E\), \[h\in\psi(X)\iff h\in\psi(X\cap W_{h})\qquad\qquad\qquad X\in\mathcal{P}(E).\] Let \(\Psi_{W}\) denote the collection of t.i. operators locally defined within a window \(W\in\mathcal{P}(E)\) and let \[\Omega=\bigcup_{\begin{subarray}{c}W\in\mathcal{P}(E)\\ |W|<\infty\end{subarray}}\Psi_{W}\] be the subset of \(\Psi\) of all operators from \(\mathcal{P}(E)\) to \(\mathcal{P}(E)\) that are t.i. and locally defined within some finite window \(W\in\mathcal{P}(E)\). The elements of \(\Omega\) are called _\(W\)-operators_. For each \(W\in\mathcal{P}(E)\), the pair \((\Psi_{W},\leqslant)\) constitutes a finite sub-lattice of the lattice \((\Psi,\leqslant)\). The kernel \(\mathcal{K}_{W}(\psi)\) of a \(W\)-operator \(\psi\) is the sub-collection of \(\mathcal{P}(W)\) defined by \[\mathcal{K}_{W}(\psi)=\{X\in\mathcal{P}(W):o\in\psi(X)\} \psi\in\Psi_{W}. \tag{3.2}\] The mapping \(\mathcal{K}_{W}\) from \(\Psi_{W}\) to \(\mathcal{P}(\mathcal{P}(W))\) defined by (3.2) constitutes a lattice isomorphism between the lattices \((\Psi_{W},\leqslant)\) and \((\mathcal{P}(\mathcal{P}(W)),\subseteq)\). The inverse of the mapping \(\mathcal{K}_{W}\) is the mapping \(\mathcal{K}_{W}^{-1}\) defined by \[\mathcal{K}_{W}^{-1}(\mathcal{X})(X)=\{x\in E:X_{-x}\cap W\in \mathcal{X}\}\qquad\mathcal{X}\in\mathcal{P}(\mathcal{P}(W)),X\in\mathcal{P}( E).\] As a consequence of this isomorphism, we have that, \(\forall\psi_{1},\psi_{2}\in\Psi_{W}\), \[\mathcal{K}_{W}(\psi_{1}\wedge\psi_{2})=\mathcal{K}_{W}(\psi_{1})\cap\mathcal{ K}_{W}(\psi_{2})\quad\text{and}\quad\mathcal{K}_{W}(\psi_{1}\vee\psi_{2})=\mathcal{K}_{W }(\psi_{1})\cup\mathcal{K}_{W}(\psi_{2}).\] See [9, Proposition 4.1] for more details. Define by \(\nu\) and \(\iota\) the set operators \[\iota(X)=X \nu(X)=X^{c}\] for \(X\in\mathcal{P}(E)\), called, respectively, the identity and the complement operators, in which the complement of \(X\) is with respect to \(E\): \(X^{c}=\{x\in E:x\notin X\}\). For \(A,B\in\mathcal{P}(E)\), the operations \[A\oplus B=\bigcup_{b\in B}A_{b} \text{and} A\ominus B=\bigcap_{b\in B}A_{-b}\] are called, respectively, _Minkowski addition_ and _subtraction_. For \(B\in\mathcal{P}(W)\), the t.i. set operators \(\delta_{B}\) and \(\epsilon_{B}\) defined by \[\delta_{B}(X)=X\oplus B X\in\mathcal{P}(E)\] and \[\epsilon_{B}(X)=X\ominus B X\in\mathcal{P}(E)\] are called, respectively, _dilation_ and _erosion_ by \(B\). The set \(B\) is called structural element. Let \(A,B\in\mathcal{P}(W)\) be such that \(A\subseteq B\). The t.i. set operators \(\lambda_{[A,B]}^{W}\) and \(\mu_{[A,B]}^{W}\) defined by \[\lambda_{[A,B]}^{W}(X)=\{x\in E:A\subseteq X_{-x}\cap W\subseteq B\}\qquad \qquad X\in\mathcal{P}(E)\] and \[\mu_{[A,B]}^{W}(X)=\left\{x\in E:X_{-x}\cap A^{t}\neq\emptyset \text{ or }\left[X_{-x}\cap W^{t}\right]\cup B^{t}\neq W^{t}\right\}\quad X\in \mathcal{P}(E)\] are called, respectively, sup-generating and inf-generating operators. These operators are locally defined within, respectively, \(W\) and \(W^{t}\). The sup-generating and inf-generating operators can be decomposed in terms of erosions and dilations, respectively, by \[\lambda_{[A,B]}^{W}(X)=\epsilon_{A}(X)\cap\nu\delta_{B^{tc}}(X)\qquad\qquad X \in\mathcal{P}(E) \tag{3.3}\] and \[\mu_{[A,B]}^{W}(X)=\delta_{A}(X)\cup\nu\epsilon_{B^{ct}}(X)\qquad\qquad X\in \mathcal{P}(E) \tag{3.4}\] in which the complement of \(B\) is taken relative to \(W\). The operators \(\nu\delta_{B^{tc}}\) and \(\nu\epsilon_{B^{ct}}\) are called, respectively, anti-dilation and anti-erosion. The dual operator of \(\psi\), denoted by \(\psi^{\star}\), is defined as \[\psi^{\star}=\nu\psi\nu.\] The next result, due to a specialization of the results in [4] proved in [9], presents two decompositions of a \(W\)-operator called canonical sup-decomposition and canonical inf-decomposition. **Proposition 3.1**.: _Let \(\psi\) be a \(W\)-operator. Then \(\psi\) can be decomposed as_ \[\psi(X)=\bigcup\left\{\lambda_{[A,B]}^{W}(X):[A,B]\subset\mathcal{K}_{W}(\psi )\right\}\qquad\qquad X\in\mathcal{P}(E)\] _and_ \[\psi(X)=\bigcap\left\{\mu_{[A^{t},B^{t}]}^{W^{t}}(X):[A,B]\subset \mathcal{K}_{W}(\psi^{\star})\right\}\qquad\quad X\in\mathcal{P}(E),\] _called, respectively, canonical sup-decomposition and canonical inf-decomposition of \(\psi\)._ These decompositions are quite general, but there may exist a smaller family of sup-generating or inf-generating operators that represents a same operator. Indeed, let \[\boldsymbol{B}_{W}(\psi)\coloneqq\boldsymbol{M}\left(\mathcal{K}_{W}(\psi)\right) \psi\in\Psi_{W}\] be the collection of all maximal closed intervals contained in \(\mathcal{K}_{W}(\psi)\). We call \(\boldsymbol{B}_{W}(\psi)\) the _basis_ of \(\psi\) and obtain the following simplification of the decompositions in Proposition 3.1. **Corollary 3.2**.: _Let \(\psi\) be a \(W\)-operator. Then \(\psi\) can be decomposed as_ \[\psi(X)=\bigcup\left\{\lambda_{[A,B]}^{W}(X):[A,B]\in\boldsymbol{B}_{W}(\psi)\right\} \qquad\qquad X\in\mathcal{P}(E)\] _and_ \[\psi(X)=\bigcap\left\{\mu_{[A^{t},B^{t}]}^{W^{t}}(X):[A,B]\in \boldsymbol{B}_{W}(\psi^{\star})\right\}\qquad\quad X\in\mathcal{P}(E).\] From Proposition 3.1 and Corollary 3.2 follow that \(W\)-operators are uniquely determined, or parametrized, by their kernel or their basis. As a consequence of the isomorphisms in Figure 1, a \(W\)-operator can also be represented by a Boolean function, as follows. Let \(T\) be the mapping between \(\Psi_{W}\) and \(\mathfrak{B}_{W}\) defined by \[T(\psi)(X)=\begin{cases}1,&\text{ if }o\in\psi(X)\\ 0,&\text{ otherwise.}\end{cases}\qquad\qquad\psi\in\Psi_{W},X\in\mathcal{P}(W).\] The mapping \(T\) constitutes a lattice isomorphism between the complete lattices \((\Psi_{W},\leq)\) and \((\mathfrak{B}_{W},\leq)\), and its inverse \(T^{-1}\) is defined by \[T^{-1}(f)(X)=\{x\in E:f(X_{-x}\cap W)=1\}\qquad f\in\mathfrak{B}_{W},X\in \mathcal{P}(E).\] We note that underlying all these decomposition results are the isomorphisms between \((\Psi_{W},\leq),(\mathcal{P}(\mathcal{P}(W)),\leq),(\Pi_{W},\leq)\) and \((\mathfrak{B}_{W},\leq)\) depicted in Figure 1. ## 4. Composition of Operators in the Canonical Form The basic operations between set operators are supremum, infimum, and composition. In this section, we summarize the main results of [9] regarding the basis of set operators obtained via such operations. The first result are assertions about the window of the supremum, infimum, and composition of set operators. For any \(h\in E\) let \[\tau_{h}(X) =X+h X\in\mathcal{P}(E)\] be the _translation by \(h\) operator_. **Proposition 4.1**.: _Let \(\psi\in\Psi_{W},\psi_{1}\in\Psi_{W_{1}}\) and \(\psi_{2}\in\Psi_{W_{2}}\) be t.i. operators locally defined within windows \(W,W_{1},W_{2}\in\mathcal{P}(E)\), respectively. The following hold:_ 1. _The operator_ \(\psi\) _is locally defined within any window_ \(W^{\prime}\supseteq W\)_._ 2. _The operators_ \(\psi_{1}\vee\psi_{2}\) _and_ \(\psi_{1}\wedge\psi_{2}\) _are t.i. and locally defined within the window_ \(W_{1}\cup W_{2}\)_._ 3. _For any_ \(h\in E\)_,_ \(\tau_{h}\psi\) _is t.i. and locally defined within the window_ \(W-h\)_._ 4. _For_ \(B\in\mathcal{P}(E)\)_, the operators_ \(\delta_{B}\psi\) _and_ \(\epsilon_{B}\psi\) _are t.i. and locally defined, respectively, within windows_ \(W\oplus B^{t}\) _and_ \(W\oplus B\) Figure 1. The lattice isomorphisms between representations of W-operators. _ * _The operator_ \(\psi_{2}\psi_{1}\) _is t.i. and locally defined within the window_ \(W_{1}\oplus W_{2}\)_._ From Proposition 4.1 follows that the collection \(\Omega\) of all t.i. and locally defined set operators is closed under finite composition, infimum, and supremum. **Corollary 4.2**.: _The set \(\Omega\) of all translation invariant and locally defined set operators from \(\mathcal{P}(E)\) to \(\mathcal{P}(E)\) is closed under finite composition, infimum, and supremum._ The next result presents the basis of the supremum, infimum, and composition of set operators. See [9] for a proof. **Proposition 4.3**.: _Let \(\psi\in\Psi_{W},\psi_{1}\in\Psi_{W_{1}}\) and \(\psi_{2}\in\Psi_{W_{2}}\) be t.i. operators locally defined within windows \(W,W_{1},W_{2}\in\mathcal{P}(E)\), respectively. The following hold:_ * \(\boldsymbol{B}_{W_{1}\cup W_{2}}(\psi_{1}\wedge\psi_{2})=\boldsymbol{B}_{W_{1 }\cup W_{2}}(\psi_{1})\sqcap\boldsymbol{B}_{W_{1}\cup W_{2}}(\psi_{2})\)__ * \(\boldsymbol{B}_{W_{1}\cup W_{2}}(\psi_{1}\vee\psi_{2})=\boldsymbol{B}_{W_{1} \cup W_{2}}(\psi_{1})\sqcap\boldsymbol{B}_{W_{1}\cup W_{2}}(\psi_{2})\)__ * \(\boldsymbol{B}_{W}(\nu\psi)=\bar{\boldsymbol{B}}_{W}(\psi)\)__ * \(\boldsymbol{B}_{W-h}(\tau_{h}\psi)=\boldsymbol{B}_{W}(\psi)-h\)__ * _For_ \(B\in\mathcal{P}(E)\)_,_ \(\boldsymbol{B}_{W\oplus B^{t}}(\delta_{B}\psi)=\bigsqcup_{b\in B}\boldsymbol{B }_{W\oplus B^{t}}(\tau_{b}\psi)\)__ * _For_ \(B\in\mathcal{P}(E)\)_,_ \(\boldsymbol{B}_{W\oplus B}(\epsilon_{B}\psi)=\bigsqcup_{b\in B^{t}} \boldsymbol{B}_{W\oplus B}(\tau_{b}\psi)\)__ * _Denoting_ \(\boldsymbol{B}_{W_{2}}(\psi_{2})=\{[A_{i},B_{i}]:i\in\mathfrak{I}\}\)_, then_ \[\boldsymbol{B}_{W_{1}\oplus W_{2}}(\psi_{2}\psi_{1})=\bigsqcup\bigbig{\{} \boldsymbol{B}_{W_{1}\oplus W_{2}}(\epsilon_{A_{i}}\psi_{1})\sqcap\bar{ \boldsymbol{B}}_{W_{1}\oplus W_{2}}(\delta_{B_{i}^{ct}}\psi_{1}):i\in \mathfrak{I}\}\] ## 5. Discrete Morphological Neural Networks A Morphological Discrete Neural Network (DMNN) can be represented as a computational graph with vertices that compute either a \(W\)-operator, or one of the two basic supremum and infimum operations. A DMNN realizes the \(W\)-operator computed by its computational graph. We start by defining the Morphological Computational Graphs that represent DMNN. Then, we define a DMNN architecture and the space of \(W\)-operators realized by it, and show that any \(W\)-operator may be non-trivially represented by a DMNN. We end this section showing that DMNN are universal representers of t.i and locally defined set operators. ### Morphological Computational Graph Let \(\mathcal{G}=(\mathcal{V},\mathcal{E},\mathcal{C})\) be a _computational graph_, in which \(\mathcal{V}\) is a general set of vertices, \(\mathcal{E}\subset\{(\mathfrak{v}_{1},\mathfrak{v}_{2})\in\mathcal{V}\times \mathcal{V}:\mathfrak{v}_{1}\neq\mathfrak{v}_{2}\}\) is a set of directed edges, and \(\mathcal{C}:\mathcal{V}\rightarrow\Omega\cup\{\vee,\wedge\}\) is a mapping that associates each vertex \(\mathfrak{v}\in\mathcal{V}\) to a _computation_ given by either applying a t.i. and locally defined operator \(\psi\in\Omega\) or one of the two basic operations \(\{\vee,\wedge\}\). For each \(\mathfrak{v}\in\mathcal{V}\) we denote by \[\mathds{I}(\mathfrak{v})=\{\mathfrak{a}\in\mathcal{V}:(\mathfrak{a}, \mathfrak{v})\in\mathcal{E}\}\] the vertices in \(\mathcal{V}\) connected with \(\mathfrak{v}\) by an edge ending in \(\mathfrak{v}\) (input vertices of \(\mathfrak{v}\)), and \[\mathsf{O}(\mathfrak{v})=\{\mathfrak{a}\in\mathcal{V}:(\mathfrak{v}, \mathfrak{a})\in\mathcal{E}\}\] as the vertices in \(\mathcal{V}\) connected with \(\mathfrak{v}\) by an edge starting in \(\mathfrak{v}\) (output vertices of \(\mathfrak{v}\)). We say that \(\mathcal{G}\) is a Morphological Computational Graph (MCG) when the following conditions are satisfied. **Axioms of Morphological Computational Graphs** A computational graph \(\mathcal{G}=(\mathcal{V},\mathcal{E},\mathcal{C})\) is a Morphological Computational Graph if, and only if, all the following conditions hold: * **A1**: The directed graph \((\mathcal{V},\mathcal{E})\) is acyclic and the number of vertices is finite and greater than 2, i.e., \(2<|\mathcal{V}|<\infty\); * **A2**: There exists a unique \(\mathfrak{v}_{i}\in\mathcal{V}\) with \(|\mathds{I}(\mathfrak{v}_{i})|=0\) and it computes the identity operator, i.e., \(\mathcal{C}(\mathfrak{v}_{i})=\iota\); * **A3**: There exists a unique \(\mathfrak{v}_{o}\in\mathcal{V}\) with \(|\mathsf{O}(\mathfrak{v}_{o})|=0\) and it computes the identity operator, i.e., \(\mathcal{C}(\mathfrak{v}_{o})=\iota\); * **A4**: If \(\mathcal{C}(\mathfrak{v})\in\Omega\), then \(|\mathds{I}(\mathfrak{v})|=1\); * **A5**: If \(\mathcal{C}(\mathfrak{v})\in\{\vee,\wedge\}\), then \(|\mathds{I}(\mathfrak{v})|\geqslant 2\). * **A6**: For all \(\mathfrak{v}\in\mathcal{V},\mathfrak{v}\neq\mathfrak{v}_{o}\), \(|\mathsf{O}(\mathfrak{v})|\geqslant 1\). The computation of a vertex \(\mathfrak{v}\) in \(\mathcal{G}\) receives as input the output of the computation of the vertices in \(\mathds{I}(\mathfrak{v})\), and the output of its computation will be used as the input of the computation of the vertices in \(\mathds{O}(\mathfrak{v})\). We assume there is an input vertex \(\mathfrak{v}_{i}\), and an output vertex \(\mathfrak{v}_{o}\), that store the input, which is an element \(X\in\mathcal{P}(E)\), and output of the computational graph, respectively. These vertices cannot have, respectively, an edge ending and starting in them (**A2** and **A3**). The directed graph \((\mathcal{V},\mathcal{E})\) should be acyclic, so each computation is performed at most once in any path of \((\mathcal{V},\mathcal{E})\), and there should be at least three vertices in \(\mathcal{V}\) so it is not formed solely by the input and output vertices; there must be a finite number of vertices so the computation of \(\mathcal{G}\) is possible (**A1**). On the one hand, if \(\mathcal{C}(\mathfrak{v})\in\Omega\), then the computation of \(\mathfrak{v}\) is given by applying a t.i. and locally defined set operator which has only one input, so it must hold \(|\mathds{I}(\mathfrak{v})|=1\) (**A4**). On the other hand, if \(\mathcal{C}(\mathfrak{v})\in\{\vee,\wedge\}\), then the computation of \(\mathfrak{v}\) is given by taking the infimum or the supremum of the output of at least two preceding computations, so it must hold \(|\mathds{I}(\mathfrak{v})|\geq 2\) (**A5**). Apart from the output vertex \(\mathfrak{v}_{o}\), all other vertices should have at least one edge starting in them, so their computation is the input of at least one other vertex (**A6**). Table 5.1 summarizes the types of vertices of an MCG. Since the input of the vertex \(\mathfrak{v}_{i}\) is an element of \(\mathcal{P}(E)\), the output and the input of all computations performed by vertices in \(\mathcal{G}\) are elements of \(\mathcal{P}(E)\). Denoting by \(\psi_{\mathcal{G}}(X)\) the output of vertex \(\mathfrak{v}_{o}\) when the input of vertex \(\mathfrak{v}_{i}\) is \(X\in\mathcal{P}(E)\), we have that the MCG \(\mathcal{G}\) generates a set operator \(\psi_{\mathcal{G}}:\mathcal{P}(E)\to\mathcal{G}(E)\). \begin{table} \begin{tabular}{c c c c c c} \hline Symbol & Name & \(\mathcal{C}(\mathfrak{v})\) & \(|\mathds{I}(\mathfrak{v})|\) & \(|\mathds{O}(\mathfrak{v})|\) & Description \\ \hline \(X\) & Input vertex \(\mathfrak{v}_{i}\) & \(\iota\) & \(0\) & \(\geq 1\) & Receive and store the input \(X\in\mathcal{P}(E)\) of \(\mathcal{G}\) \\ \(\psi\) & Set operator vertex & \(\psi\in\Omega\) & \(1\) & \(\geq 1\) & Apply operator \(\psi=\mathcal{C}(\mathfrak{v})\in\Omega\) to its input \\ \(\psi\) & Supremum vertex & \(\vee\) & \(\geq 2\) & \(\geq 1\) & Take the supremum of its inputs \\ \(\psi\) & Infimum vertex & \(\wedge\) & \(\geq 2\) & \(\geq 1\) & Take the infimum of its inputs \\ \(\psi_{\mathcal{G}}\) & Output vertex \(\mathfrak{v}_{o}\) & \(\iota\) & \(1\) & \(0\) & Receive and store the output \(\psi_{\mathcal{G}}(X)\) of \(\mathcal{G}\) \\ \hline \hline \end{tabular} \end{table} Table 5.1. Types of vertices of a Morphological Computational Graph. \(\mathcal{P}(E)\). Actually, it follows from Corollary 4.2 that \(\psi_{\mathcal{G}}\) is actually t.i. and locally defined within a window \(W_{\mathcal{G}}\). **Proposition 5.1**.: _Let \(\mathcal{G}=(\mathcal{V},\mathcal{E},\mathcal{C})\) be a Morphological Computational Graph. Then \(\psi_{\mathcal{G}}\) is translation invariant and locally defined within a finite window \(W_{\mathcal{G}}\in\mathcal{P}(E)\)._ Proof.: Fix \(X\in\mathcal{P}(E)\) and let \[\Omega_{\mathcal{G}}=\{\psi\in\Omega:\exists\mathfrak{v}\in\mathcal{V}\text{ s.t. }\mathcal{C}(\mathfrak{v})=\psi\}\subseteq\Omega\] be the finite collection of t.i. and locally defined set operators applied by vertices in \(\mathcal{V}\). Since \(\psi_{\mathcal{G}}(X)\) is obtained by combining the set operators in \(\Omega_{\mathcal{G}}\) via the composition, supremum and infimum operations, and \(\Omega\) is closed under finite composition, infimum and supremum (cf. Corollary 4.2), it follows that \(\psi_{\mathcal{G}}\in\Omega\), and hence it is a t.i. and locally defined set operator. **Remark 5.2**.: _An algorithm to calculate a window \(W_{\mathcal{G}}\) of \(\psi_{\mathcal{G}}\) or its basis \(\boldsymbol{B}_{W_{\mathcal{G}}}(\psi_{\mathcal{G}})\) is a consequence of the results of [9] summarized in Propositions 4.1 and 4.3. The window or the basis may be computed via the computational graph \(\mathcal{G}\), but instead of applying the computations determined by \(\mathcal{C}\), one combines the windows or basis of the input vertices based on Propositions 4.1 and 4.3 to obtain the window or basis of the set operator defined as the output of each vertex. At the end of the computations, the window or basis stored in the output vertex will be that of \(\psi_{\mathcal{G}}\)._ We are in position to define the DMNN represented by an MCG. **Definition 5.3**.: _Let \(\mathcal{G}=(\mathcal{V},\mathcal{E},\mathcal{C})\) be a Morphological Computational Graph. We define the Morphological Discrete Neural Network represented by \(\mathcal{G}\) as the translation invariant and locally defined set operator \(\psi_{\mathcal{G}}\)._ We present four examples of MCG which, respectively, trivially represents a \(\psi\in\Omega\), represents \(\psi\) via its canonical sup-generating or inf-generating decomposition, represents an alternate-sequential filter, and represents the composition of an alternate-sequential filter and a W-operator. **Example 5.4** (Trivial DMNN).: Fix \(\psi\in\Omega\) and let \(\mathcal{G}\) be the MCG with \(\mathcal{V}=\{\mathfrak{v}_{i},\mathfrak{v},\mathfrak{v}_{o}\}\), \(\mathcal{E}=\{(\mathfrak{v}_{i},\mathfrak{v}),(\mathfrak{v},\mathfrak{v}_{o})\}\) and \(\mathcal{C}(\mathfrak{v})=\psi\). This MCG, depicted in Figure 2, is such that \(\psi=\psi_{\mathcal{G}}\) and illustrates that any \(\psi\in\Omega\) can be trivially represented by a DMNN. **Example 5.5** (Sup-generating and inf-generating DMNN).: Let \(\psi\in\Psi_{W}\). Due to the canonical inf and sup-generating decomposition of \(\psi\) (cf. Proposition 3.1), it can be represented by a DMNN with a vertex for each element in \(\boldsymbol{B}_{W}(\psi)\), that applies the respective inf or sup-generating operator to the input \(X\in\mathcal{P}(E)\), and an infimum or supremum vertex that combines their output, respectively. The inf and sup-generating DMNN are represented in Figure 3. This example illustrates that any t.i. and locally defined set operator can be non-trivially represented by a DMNN. **Example 5.6** (Alternate-sequential filters DMNN).: The DMNN are specially useful to represent operators that can be decomposed sequentially as the composition of set operators. A special class of such operators are the alternate-sequential filters (ASF) which are defined as the interleaved composition of openings and closings. Fixed a structural element \(B\in\mathcal{P}(E)\), the opening \(\gamma_{B}\) and the closing \(\phi_{B}\) are the set operators defined, respectively, as \[\gamma_{B}=\delta_{B}\epsilon_{B} \phi_{B}=\epsilon_{B}\delta_{B}, \tag{5.1}\] Figure 2. Trivial DMNN representation of \(\psi\in\Omega\). that are, respectively, an erosion followed by a dilation and a dilation followed by an erosion. Openings and closings are increasing and idempotent set operators. The openings are anti-extensive, i.e., \(\gamma_{B}(X)\subseteq X\), and the closings are extensive, i.e., \(X\subseteq\phi_{B}(X)\). See [43, Section 5.4] for more details. Let \(\gamma_{B_{1}},\phi_{B_{1}},\ldots,\gamma_{B_{n}},\phi_{B_{n}}\) be a sequence of \(n\) openings and \(n\) closings. The set operator \(\psi\) given by \[\psi=\phi_{B_{n}}\gamma_{B_{n}}\cdots\phi_{B_{1}}\gamma_{B_{1}}\] is called an alternate-sequential filter. Figure 4 presents three DMNN representations of \(\psi\) in which, respectively, the vertices are a composition of an opening and a closing, the vertices are openings or closings, and the vertices are erosions or dilations. **Example 5.7** (Composition of an ASF and a W-operator).: Figure 5 presents a DMNN representation of a composition of an ASF \(\phi_{A}\gamma_{A}\) and a \(\psi\in\Psi_{W}\) with three elements in its basis. This example illustrates how elements of sequential and sup-generating architectures may be combined to obtain more complex DMNN. The examples above illustrate the flexibility of a DMNN in representing any t.i. and locally defined set operator. Such a flexibility allows, for instance, the representation of \(\psi\) by a DMNN that is more efficiently computed via an MCG \(\mathcal{G}\) or that has fewer _parameters_. Another feature of this flexibility is the possibility of defining a class of set operators through restrictions on the set of all MCG. Indeed, since the mapping \(\psi_{\mathcal{G}}\), from the collection of all MCG to \(\Omega\), is surjective, restrictions on the MCG structure may generate restrictions on \(\Omega\). In the next section, we formalize the restricted classes of MCG, which are the architectures of DMNN. ### DMNN Architectures Let \(\mathcal{A}=(\mathcal{V},\mathcal{E},\mathcal{F})\) in which \(\mathcal{V}\) is a set of vertices, \(\mathcal{E}\subset\mathcal{V}\times\mathcal{V}\) is a set of ordered edges and \(\mathcal{F}\subseteq\left(\Omega\cup\left\{\vee,\wedge\right\}\right)^{ \mathcal{V}}\) is a collection of functions from \(\mathcal{V}\) to \(\Omega\cup\left\{\vee,\wedge\right\}\). We say that \(\mathcal{A}\) is the architecture of a DMNN if it satisfies the following condition. **Axiom of Morphological Discrete Neural Network Architectures** A triple \(\mathcal{A}=(\mathcal{V},\mathcal{E},\mathcal{F})\) is a Morphological Discrete Neural Network architecture if, and only if, \((\mathcal{V},\mathcal{E},\mathcal{C})\) is a Morphological Computational Graph for all \(\mathcal{C}\in\mathcal{F}\). A DMNN architecture is actually a collection of MCG with same graph \((\mathcal{V},\mathcal{E})\) and computation map \(\mathcal{C}\) in \(\mathcal{F}\). Since a DMNN architecture represents a collection of MCG, it actually represents a collection of t.i. and locally defined set operators (cf. Proposition 5.1). For an architecture \(\mathcal{A}=(\mathcal{V},\mathcal{E},\mathcal{F})\), let \[\mathbb{G}(\mathcal{A})=\left\{\mathcal{G}=(\mathcal{V},\mathcal{E},\mathcal{ C}):\mathcal{C}\in\mathcal{F}\right\}\] be the collection of MGC generated by \(\mathcal{A}\). We say that \(\mathcal{G}\in\mathbb{G}(\mathcal{A})\) is a realization of architecture \(\mathcal{A}\) and we define \[\mathcal{H}(\mathcal{A})=\{\psi\in\Omega:\psi=\psi_{\mathcal{G}},\mathcal{G}\in \mathbb{G}(\mathcal{A})\}\] as the collection of t.i. and locally defined set operators that can be realized by \(\mathcal{A}\). We present three examples of DMNN architectures. **Example 5.8** (Sup-generating DMNN architecture).: Figure 6 presents two examples of sup-generating architectures, which are characterized by the supremum of sup-generating set operators. In both examples, we consider the graph \((\mathcal{V},\mathcal{E})\) such that \(\mathcal{V}=\{\mathfrak{v}_{i},\mathfrak{v}_{1},\mathfrak{v}_{2},\mathfrak{v} _{3},\mathfrak{v}_{\vee},\mathfrak{v}_{o}\}\) and \[\mathcal{E}=\{(\mathfrak{v}_{i},\mathfrak{v}_{1}),(\mathfrak{v}_{i},\mathfrak{ v}_{2}),(\mathfrak{v}_{i},\mathfrak{v}_{3}),(\mathfrak{v}_{1},\mathfrak{v}_{ \vee}),(\mathfrak{v}_{2},\mathfrak{v}_{\vee}),(\mathfrak{v}_{3},\mathfrak{v }_{\vee}),(\mathfrak{v}_{\vee},\mathfrak{v}_{o})\}.\] The architecture \(\mathcal{A}_{1}=(\mathcal{V},\mathcal{E},\mathcal{F}_{1})\) is such that, for all \(\mathcal{C}\in\mathcal{F}\), \(\mathcal{C}(\mathfrak{v}_{i})=\mathcal{C}(\mathfrak{v}_{o})=\iota\), \(\mathcal{C}(\mathfrak{v}_{\vee})=\vee\) and \[\mathcal{C}(\mathfrak{v}_{j})=\lambda_{[A,B]}^{W}\text{ with }A,B\in\mathcal{P}(W),A \subseteq B\qquad\qquad j=1,2,3,\] which realizes the \(W\)-operators with at most three elements in their basis, that is, \[\mathcal{H}(\mathcal{A}_{1})=\{\psi\in\Psi_{W}:|\boldsymbol{B}_{W}(\psi)| \leq 3\}\,.\] Denoting \[\Lambda_{W}=\{\lambda_{[A,B]}^{W}:A,B\in\mathcal{P}(W),A\subseteq B\}\] as the sup-generating set operators locally defined within \(W\), it follows that \[\mathcal{F}_{1}=\{\iota\}\times\Lambda_{W}\times\Lambda_{W}\times\Lambda_{W} \times\{\vee\}\times\{\iota\},\] so \(\mathcal{F}_{1}\) is the Cartesian product of elements in \(\mathcal{P}(\Psi_{W})\cup\{\{\vee\},\{\wedge\}\}\). This means that, under this architecture, the computation of each vertex can be chosen independently of one another. Denoting \[\Sigma_{W}=\{\epsilon_{A}^{W}:A\in\mathcal{P}(W)\}\] as the erosions with structural elements in \(\mathcal{P}(W)\), the architecture \(\mathcal{A}_{2}\) is such that \[\mathcal{F}_{2}=\{\iota\}\times\Sigma_{W}\times\Sigma_{W}\times\Sigma_{W} \times\{\vee\}\times\{\iota\},\] so it realizes the more restricted class of increasing \(W\)-operators with at most three elements in their basis, that is, \[\mathcal{H}(\mathcal{A}_{2})=\left\{\psi\in\Psi_{W}:\psi\text{ is increasing},| \boldsymbol{B}_{W}(\psi)|\leq 3\right\},\] which can be represented by the supremum of three erosions. Even though \(\mathcal{A}_{1}\) and \(\mathcal{A}_{2}\) have the same graph, \(\mathcal{H}(\mathcal{A}_{2})\subseteq\mathcal{H}(\mathcal{A}_{1})\) so \(\mathcal{A}_{2}\) is a restriction of \(\mathcal{A}_{1}\). **Example 5.9** (Sequential DMNN architecture).: Figure 7 presents three examples of sequential DMNN architectures characterized by the absence of supremum and infimum vertices. The architectures \(\mathcal{A}_{1}\) and \(\mathcal{A}_{2}\) have the same graph \((\mathcal{V},\mathcal{E})\) with \(\mathcal{V}=\{\mathfrak{v}_{i},\mathfrak{v}_{1},\mathfrak{v}_{2},\mathfrak{v} _{3},\mathfrak{v}_{4},\mathfrak{v}_{o}\}\) and \(\mathcal{E}\) linking the vertices in sequence. For fixed windows \(W_{1},W_{2}\in\mathcal{P}(E)\), the architecture \(\mathcal{A}_{1}\) is such that \[\mathcal{F}_{1}=\{\iota\}\times\Psi_{W_{1}}\times\Psi_{W_{1}}\times\Psi_{W_{2 }}\times\Psi_{W_{2}}\times\{\iota\}\] Figure 6. Two DMNN architectures with the same graph that represent sup-generating decompositions. When we exchange a parameter by a dot, we mean that it is free, so \(\lambda^{W}\) represents any sup-generating operator locally defined within \(W\) and \(\epsilon^{W}\) represents any erosion locally defined within \(W\). Architecture \(\mathcal{A}_{1}\) realizes all \(\psi\in\Psi_{W}\) with at most 3 elements in the basis, i.e., \(|\boldsymbol{B}_{W}(\psi)|\leq 3\), while architecture \(\mathcal{A}_{2}\) realizes all \(\psi\in\Psi_{W}\) that can be written as the supremum of three erosions, which are actually the increasing operators in \(\Psi_{W}\) with at most three elements in their basis. See Figure 3 (a) for a realization of architecture \(\mathcal{A}_{1}\). so it realizes the operators in \(\Psi_{W}\), with \(W=W_{1}\oplus W_{1}\oplus W_{2}\oplus W_{2}\), that can be written as the composition of two operators in \(\Psi_{W_{1}}\) composed with two operators in \(\Psi_{W_{2}}\), that is, \[\mathcal{H}(\mathcal{A}_{1})=\left\{\psi\in\Psi_{W}:\psi=\psi^{\prime W_{2}} \psi^{\prime W_{1}}\psi^{W_{1}};\psi^{W_{i}},\psi^{\prime W_{i}}\in\Psi_{W_{i}},i=1,2\right\}.\] This is another example in which the computation of the vertices in the architecture can be chosen independently, since \(\mathcal{F}_{1}\) is a Cartesian product. In the architecture \(\mathcal{A}_{2}\), the functions \(\mathcal{C}\) in \(\mathcal{F}_{2}\) are such that \[\begin{cases}\mathcal{C}(\mathfrak{v}_{i})=\mathcal{C}(\mathfrak{v}_{o})= \iota\\ \mathcal{C}(\mathfrak{v}_{1})=\gamma_{A},\mathcal{C}(\mathfrak{v}_{2})=\phi_{ A},\text{ for a }A\in\mathcal{P}(W_{1})\\ \mathcal{C}(\mathfrak{v}_{3})=\gamma_{B},\mathcal{C}(\mathfrak{v}_{4})=\phi_{ B},\text{ for a }B\in\mathcal{P}(W_{2})\end{cases}\] so \(\mathcal{A}_{2}\) realizes the subclass of the ASF in \(\mathcal{H}(\mathcal{A}_{1})\), that is, \[\mathcal{H}(\mathcal{A}_{2})=\left\{\psi\in\mathcal{H}(\mathcal{A}_{1}):\psi \text{ is an alternate-sequential filter}\right\}.\] See Figure 4 for a realization of this architecture. In this example, \(\mathcal{F}_{2}\) is not a Cartesian product, so the computation of its vertices are not independent. Indeed, the structural element of the first and last pairs of opening and closing have the same structural element, so in this example the vertices share a parameter. However, this sub-collection of set operators could also be represented by the architecture \(\mathcal{A}_{3}\) in Figure 7 in which the interior vertices compute a composition of an opening and a closing with a same structuring element and the vertices do not share parameters. Even though \(\mathcal{H}(\mathcal{A}_{2})=\mathcal{H}(\mathcal{A}_{3})\), \(\mathcal{F}_{3}\) is a Cartesian product, so the computation of the vertices can be chosen independently. This is another example of architectures with the same graph, but such that \(\mathcal{H}(\mathcal{A}_{3})=\mathcal{H}(\mathcal{A}_{2})\subseteq\mathcal{H} (\mathcal{A}_{1})\), so \(\mathcal{A}_{2}\) is a restriction of \(\mathcal{A}_{1}\). This is also an example of a DMNN that can be represented by two equivalent architectures. **Example 5.10** (Sequential ASF and W-operator).: Figure 8 presents an example of an architecture which composes an ASF with a W-operator. This architecture has a graph \((\mathcal{V},\mathcal{E})\) such that \(\mathcal{V}=\{\mathfrak{v}_{i},\mathfrak{v}_{1},\mathfrak{v}_{2},\mathfrak{v}_ {3},\mathfrak{v}_{4},\mathfrak{v}_{\vee},\mathfrak{v}_{o}\}\) and \[\mathcal{E}=\{(\mathfrak{v}_{i},\mathfrak{v}_{1}),(\mathfrak{v}_{1},\mathfrak{ v}_{2}),(\mathfrak{v}_{1},\mathfrak{v}_{3}),(\mathfrak{v}_{1},\mathfrak{v}_{4}),( \mathfrak{v}_{2},\mathfrak{v}_{\vee}),(\mathfrak{v}_{3},\mathfrak{v}_{\vee}),(\mathfrak{v}_{4},\mathfrak{v}_{\vee}),(\mathfrak{v}_{\vee},\mathfrak{v}_{ o})\}.\] The architecture is such that, for all \(\mathcal{C}\in\mathcal{F}\), \(\mathcal{C}(\mathfrak{v}_{i})=\mathcal{C}(\mathfrak{v}_{o})=\iota\), \(\mathcal{C}(\mathfrak{v}_{\vee})=\vee\) and \[\mathcal{C}(\mathfrak{v}_{1})=\phi_{A}\gamma_{A}\text{ with }A\in\mathcal{P}(W)\] \[\mathcal{C}(\mathfrak{v}_{j})=\lambda_{[A_{j},B_{j}]}^{W}\text{ with }A_{j},B_{j}\in \mathcal{P}(W),A_{j}\subseteq B_{j}\qquad\quad j=2,3,4,\] which realizes the composition of a one layer ASF and a \(W\)-operator with at most three elements in its basis. Observe that, denoting \[\Gamma\Phi_{W}=\{\phi_{A}\gamma_{A}:A\in\mathcal{P}(W)\}\] as the one layer ASF with structuring element in \(W\), in this example we have \[\mathcal{F}=\{\iota\}\times\Gamma\Phi_{W}\times\Lambda_{W}\times\Lambda_{W} \times\Lambda_{W}\times\{\vee\}\times\{\iota\},\] so \(\mathcal{F}\) is the Cartesian product of elements in \(\mathcal{P}(\Psi_{W})\cup\{\{\vee\},\{\wedge\}\}\), and the computation of each vertex can be chosen independently. ### DMNN are universal representers The semantic expressiveness of DMNN allows to represent any collection of t.i. and locally defined set operators by a DMNN. This is the result of the next theorem. **Theorem 5.11**.: _Let \(W\in\mathcal{P}(E)\) be a finite set. For any \(\Theta\in\mathcal{P}(\Psi_{W})\), there exists a Morphological Discrete Neural Network architecture \(\mathcal{A}_{\Theta}\) such that_ \[\mathcal{H}(\mathcal{A}_{\Theta})=\Theta.\] Proof.: Fix a finite set \(W\in\mathcal{P}(E)\) and a sub-collection \(\Theta\in\mathcal{P}(\Psi_{W})\). We will present a sup-generating DMNN architecture that generates \(\Theta\). Consider the architecture \(\mathcal{A}_{\Theta}=(\mathcal{V},\mathcal{E},\mathcal{F}_{\Theta})\) with a graph \((\mathcal{V},\mathcal{E})\) such that \[\mathcal{V}=\{\mathfrak{v}_{i},\mathfrak{v}_{1},\ldots,\mathfrak{v}_{2^{|W|-1} },\mathfrak{v}_{\vee},\mathfrak{v}_{o}\}\] and \[\mathcal{E}=\left\{(\mathfrak{v}_{i},\mathfrak{v}_{j}):j=1,\ldots,2^{|W|-1} \right\}\bigcup\left\{(\mathfrak{v}_{j},\mathfrak{v}_{\vee}):j=1,\ldots,2^{|W |-1}\right\}\bigcup\{(\mathfrak{v}_{\vee},\mathfrak{v}_{o})\}.\] This graph is analogous to that of Figure 3 (a), but with \(2^{|W|-1}\) vertices computing sup-generating set operators instead of three. For each \(\psi\in\Theta\), denote the elements in its basis by \[\boldsymbol{B}_{W}(\psi)=\{\mathcal{I}_{1},\ldots,\mathcal{I}_{|\boldsymbol{B }_{W}(\psi)|}\}\] and observe that \(|\boldsymbol{B}_{W}(\psi)|\leq 2^{|W|-1}\). Consider the function \(\mathcal{C}_{\psi}:\mathcal{V}\to\Psi_{W}\cup\{\vee,\wedge\}\) given by \(\mathcal{C}_{\psi}(\mathfrak{v}_{i})=\mathcal{C}_{\psi}(\mathfrak{v}_{o})=\iota\), \(\mathcal{C}_{\psi}(\mathfrak{v}_{\vee})=\vee\) and \[\mathcal{C}_{\psi}(\mathfrak{v}_{j})=\begin{cases}\lambda_{j_{j}}^{W},&\text{ if }1\leq j\leq|\boldsymbol{B}_{W}(\psi)|\\ \emptyset,&\text{ if }j>|\boldsymbol{B}_{W}(\psi)|\end{cases}\] Figure 8. Example of a DMNN architecture which composes a one layer ASF and a W-operator with at most three intervals in its basis. for \(j=1,\ldots,2^{|W|-1}\), in which \(\emptyset\) stands for the constant set operator equal to \(\emptyset\). Observe that the MCG \(\mathcal{G}_{\psi}=(\mathcal{V},\mathcal{E},\mathcal{C}_{\psi})\) generates a W-operator \(\psi_{\mathcal{G}_{\psi}}\) satisfying \(\psi_{\mathcal{G}_{\psi}}=\psi\). Considering \[\mathcal{F}_{\Theta}=\{\mathcal{C}_{\psi}:\psi\in\Theta\}\] we have that \[\mathcal{H}(\mathcal{A}_{\Theta})=\left\{\psi_{\mathcal{G}_{\psi}}:\psi\in \Theta\right\}=\Theta\] as desired. **Remark 5.12**.: _We could readily obtain an inf-generating DMNN architecture that represents a given \(\Theta\in\mathcal{P}(\Psi_{W})\) following steps analogous to the proof of Theorem 5.11._ **Remark 5.13**.: _A sub-collection \(\Theta\in\mathcal{P}(\Psi_{W})\) may be represented by other DMNN architectures besides a sup-generating and an inf-generating architecture, as is the case of the sub-collections represented by the DMNN architectures in Examples 5.9 and 5.10. Theorem 5.11 established the existence of a DMNN architecture that represents \(\Theta\), but not its uniqueness, which clearly does not hold._ Although the sup-generating representation of a \(\Theta\in\mathcal{P}(\Psi_{W})\) via a DMNN derived on the proof of Theorem 5.11 is not in principle a new result, since it is a direct consequence of [4], the result of Theorem 5.11 is pragmatic since guarantees that any prior information about the set operator that best solves a given problem, which can be translated into a sub-collection \(\Theta\in\mathcal{P}(\Psi_{W})\) containing operators with properties believed to be satisfied by the best operator, may be expressed by a DMNN architecture. ## 6. Canonical Discrete Morphological Neural Networks Dilations and erosions are the canonical operators, and the supremum, infimum and complement are the canonical operations, of Mathematical Morphology. Indeed, any W-operator can be represented by combining the supremum, infimum, and complement of compositions of erosions and dilations. This fact is a consequence of Corollary 3.2 and the representation of sup-generating and inf-generating operators by (3.3) and (3.4), respectively. Furthermore, openings, closings and ASF can also be simply represented by the composition of dilations and erosions (cf. (5.1)). We define the Canonical Discrete Morphological Neural Networks (CDMNN) as those in which the computations are canonical operations or can be simply decomposed on canonical operators. For each finite subset \(W\in\mathcal{P}(E)\), denote \[\begin{array}{ll}\Delta_{W}=\{\delta_{A}:A\in\mathcal{P}(W)\}&\Sigma_{W}=\{ \epsilon_{A}:A\in\mathcal{P}(W)\}\\ \Gamma_{W}=\{\gamma_{A}:A\in\mathcal{P}(W)\}&\Phi_{W}=\{\phi_{A}:A\in\mathcal{ P}(W)\}\\ \Gamma\Phi_{W}=\{\phi_{A}\gamma_{A}:A\in\mathcal{P}(W)\}&\Lambda_{W}=\left\{ \lambda_{[A,B]}:[A,B]\subseteq\mathcal{P}(W),A\subseteq B\right\}\\ \mathcal{M}_{W}=\left\{\mu_{[A,B]}:[A,B]\subseteq\mathcal{P}(W),A\subseteq B \right\}&\mathfrak{N}=\{\nu\}\end{array} \tag{6.1}\] as the class of the dilations, erosions, openings, closings, one layer ASF, sup-generating, inf-generating and complement operators, respectively, with structuring elements in \(\mathcal{P}(W)\) or intervals in \(\mathcal{P}(\mathcal{P}(W))\). **Definition 6.1**.: _A Morphological Discrete Neural Network architecture \(\mathcal{A}=(\mathcal{V},\mathcal{E},\mathcal{F})\) is canonical if the following holds:_ * _There exist two subsets of edges_ \(\mathcal{V}_{\vee},\mathcal{V}_{\wedge}\subseteq\mathcal{V}\) _such that, for all_ \(\mathcal{C}\in\mathcal{F}\)_,_ \[\begin{cases}\mathcal{C}(\mathfrak{v})=\vee,\forall\mathfrak{v}\in\mathcal{V} _{\vee}\\ \mathcal{C}(\mathfrak{v})=\wedge,\forall\mathfrak{v}\in\mathcal{V}_{\wedge}\\ \mathcal{C}(\mathfrak{v})\in\Omega_{\mathfrak{v}}\subseteq\Omega,\forall \mathfrak{v}\in\mathcal{V}_{\Omega},\end{cases}\] _in which_ \(\Omega_{\mathfrak{v}}\) _is a class of t.i. and locally defined operators and_ \(\mathcal{V}_{\Omega}:=\mathcal{V}\backslash\left(\mathcal{V}_{\vee}\cup \mathcal{V}_{\wedge}\right)\)_._ * _For every_ \(\mathfrak{v}\in\mathcal{V}_{\Omega}\) _there exists a finite subset_ \(W_{\mathfrak{v}}\in\mathcal{P}(E)\) _such that_ \[\Omega_{\mathfrak{v}}\in\{\Delta_{W_{\mathfrak{v}}},\Sigma_{W_{\mathfrak{v}}}, \Gamma_{W_{\mathfrak{v}}},\Phi_{W_{\mathfrak{v}}},\Gamma\Phi_{W_{\mathfrak{v}} },\Lambda_{W_{\mathfrak{v}}},\mathcal{M}_{W_{\mathfrak{v}}},\mathfrak{N}\}.\] A special case of canonical DMNN is the unrestricted canonical DMNN, in which \(\mathcal{F}\) is a Cartesian product of \(\{\vee\},\{\wedge\}\) and the sets defined in (6.1). **Definition 6.2**.: _A canonical Morphological Discrete Neural Network architecture \(\mathcal{A}=(\mathcal{V},\mathcal{E},\)\(\mathcal{F})\) is unrestricted if_ \[\mathcal{F}=\prod_{\mathfrak{v}\in\mathcal{V}_{\vee}}\{\vee\}\bigtimes\prod_{ \mathfrak{v}\in\mathcal{V}_{\wedge}}\{\wedge\}\bigtimes\prod_{\mathfrak{v}\in \mathcal{V}_{\Omega}}\Omega_{\mathfrak{v}}\subseteq\left(\Omega\cup\{\vee, \wedge\}\right)^{\mathcal{V}}.\] The architectures in Figures 6 and 8, and the architectures \(\mathcal{A}_{2}\) and \(\mathcal{A}_{3}\) in Figure 7, are canonical since the vertices that compute the supremum are the same over all realizations of the architectures and the morphological operators computed by the remaining vertices are erosions, dilations, openings, closings, one layer ASF, sup-generating or inf-generating. Furthermore, these architectures, except \(\mathcal{A}_{2}\) in Figure 7, are unrestricted since the parameters of the operators, which are structural elements or intervals, are not shared among vertices. The architecture \(\mathcal{A}_{1}\) in Figure 7 is not canonical, since there are four vertices that compute general W-operators. Observe that all vertices of a CDMNN compute either a canonical operation (supremum, infimum, or complement), or an operator that can be decomposed as the supremum, infimum, and complement of erosions and dilations, what justifies the _canonical_ nomenclature. Furthermore, any CDMNN could be represented by an MCG in which the vertices compute only erosions, dilations, supremum, infimum or complement, but that may share parameters. This fact is illustrated in Figure 4 in which a realization of a sequential CDMNN can be represented by the composition of two ASF that do not share parameters, or by the composition of dilations and erosions that share parameters. We chose the representation of CDMNN by MCG satisfying **C1** and **C2** in Definition 6.1 since it is more concise than a representation via erosions, dilations, supremum, infimum, and complement only, and allows the definition of unrestricted CDMNN when there is no parameter sharing. ### The lattice associated to a CDMNN architecture Fix a canonical DMNN architecture \(\mathcal{A}=(\mathcal{V},\mathcal{E},\mathcal{F})\). We will consider a partial order \(\leq\) in \(\mathcal{F}\) based on the _parameters_ that represent the functions \(\mathcal{C}\in\mathcal{F}\). More precisely, each \(\mathcal{C}\in\mathcal{F}\) can be represented by a vector of sets and intervals that represent the structural elements of its vertices that compute erosions, dilations, openings, closings and one layer ASF, and the intervals of its vertices that compute inf-generating and sup-generating operators, and the collection \(\mathcal{F}\) inherits the partial order of the inclusion of sets and intervals. For example, if each \(\mathcal{C}\in\mathcal{F}\) is represented by a vector \((A_{1}^{\mathcal{C}},\ldots,A_{p}^{\mathcal{C}})\in\mathcal{P}(W)^{p},p\geq 1\), of sets, then \[\mathcal{C}_{1}\leq\mathcal{C}_{2}\iff A_{j}^{\mathcal{C}_{1}}\subseteq A_{j} ^{\mathcal{C}_{2}},\forall j=1,\ldots,p,\] and \(\mathcal{F}\) inherits the partial order of the inclusion of its parameters. ASF architectures (cf. \(\mathcal{A}_{2}\) and \(\mathcal{A}_{3}\) in Figure 7) and increasing sup-generating architectures (cf. \(\mathcal{A}_{2}\) in Figure 6) are examples in which the functions in may be parameterized by a vector of sets, which represent the structuring elements of erosions, openings, or closings. As another example, if each \(\mathcal{C}\in\mathcal{F}\) is represented by a vector \(([A_{1}^{\mathcal{C}},B_{1}^{\mathcal{C}}],\ldots,[A_{p}^{\mathcal{C}},B_{p}^{ \mathcal{C}}])\in\mathcal{P}(\mathcal{P}(W))^{p},p\geq 1\), of intervals, then \[\mathcal{C}_{1}\leq\mathcal{C}_{2}\iff[A_{j}^{\mathcal{C}_{1}},B_{j}^{ \mathcal{C}_{1}}]\subseteq[A_{j}^{\mathcal{C}_{2}},B_{j}^{\mathcal{C}_{2}}], \forall j=1,\ldots,p, \tag{6.2}\] and \(\mathcal{F}\) inherits the partial order of the inclusion of its parameters. Supergenerating architectures (cf. \(\mathcal{A}_{1}\) in Figure 6) are examples in which the functions in \(\mathcal{F}\) may be parameterized by a vector of intervals, which represent the intervals of the sup-generating operators. Finally, if each \(\mathcal{C}\in\mathcal{F}\) is represented by a vector \(([A_{1}^{\mathcal{C}},B_{1}^{\mathcal{C}}],\ldots,[A_{p_{I}}^{\mathcal{C}},B_ {p_{I}}^{\mathcal{C}}],C_{1}^{\mathcal{C}},\ldots,C_{p_{S}}^{\mathcal{C}})\in \mathcal{P}(\mathcal{P}(W))^{p_{I}}\times\mathcal{P}(W)^{p_{S}},p_{I},p_{S}\geq 1\), of intervals and sets, then \[\mathcal{C}_{1}\leq\mathcal{C}_{2}\iff\begin{cases}[A_{j}^{\mathcal{C}_{1}},B _{j}^{\mathcal{C}_{1}}]\subseteq[A_{j}^{\mathcal{C}_{2}},B_{j}^{\mathcal{C}_{2 }}],&\forall j=1,\ldots,p_{I}\\ C_{j}^{\mathcal{C}_{1}}\subseteq C_{j}^{\mathcal{C}_{2}},&\forall j=1,\ldots,p_ {S}.\end{cases}\] The architecture in Figure 8 is an example of this case, in which each \(\mathcal{C}\in\mathcal{F}\) is represented by \((A,\mathcal{I}_{1},\mathcal{I}_{2},\mathcal{I}_{3})\). The set \(A\) is the structuring element of the one layer ASF, and the intervals are the parameters of the three sup-generating operators. Therefore, for any CDMNN architecture, \(\mathcal{F}\) inherits a partial order \(\leq\) from that of the structuring elements (sets) of the openings, closings, dilations, erosions and ASF, and from that of the intervals of the sup-generating and inf-generating operators, that it computes. The poset \((\mathcal{F},\leq)\) is not, in general, isomorphic to \((\mathcal{H}(\mathcal{A}),\leq)\) since the mapping \(\psi_{\cdot}\), that maps each function \(\mathcal{C}\in\mathcal{F}\) to the operator \(\psi_{\mathcal{C}}\in\mathcal{H}(\mathcal{A})\) generated by the MCG \(\mathcal{G}=(\mathcal{V},\mathcal{E},\mathcal{C})\), is not injective when two realizations of the architecture \(\mathcal{A}\) generate the same set operator. This is the case, for example, of the architecture \(\mathcal{A}_{1}\) in Figure 6 in which an operator \(\psi\) is generated by all realizations of \(\mathcal{A}_{1}\) where the union of the intervals of the sup-generating operators is equal to its kernel \(\mathcal{K}_{W}(\psi)\) (cf. Proposition 3.1). Actually, \(\mathcal{F}\) is usually an overparametrization of \(\mathcal{H}(\mathcal{A})\). Although the representation of the operators in \(\mathcal{H}(\mathcal{A})\) by \(\mathcal{F}\) is not unique and \((\mathcal{F},\leq)\) is not isomorphic to \((\mathcal{H}(\mathcal{A}),\leq)\), it has the advantage that the elements and partial order of \(\mathcal{F}\) are completely known a priori, since \(\mathcal{F}\) is fixed and the partial order is that of inclusion of sets/intervals, while the elements of \(\mathcal{H}(\mathcal{A})\) and its partial order may need to be computed. Therefore, training the DMNN by minimizing an empirical loss in \((\mathcal{F},\leq)\) to obtain a set operator that _fits_ empirical data may be computationally cheaper than minimizing this loss in \(\mathcal{H}(\mathcal{A})\) directly, since its elements and partial order should be computed (see Remark 7.1 for more details.). This observation points to the fact that a DMNN is a tool, or a _computational machine_, to learn set operators in a fixed collection \(\Theta=\mathcal{H}(\mathcal{A})\) and not a learning model in itself. The suboptimal minimization of an empirical loss in \((\mathcal{F},\leq)\) could be performed via a greedy algorithm that runs through this poset by locally minimizing the loss. This algorithm depends on the definition of the neighborhoods of \((\mathcal{F},\leq)\). ### Neighborhoods of \((\mathcal{F},\leq)\) In view of the discussion above, we define the neighborhood of \(\mathcal{C}\in\mathcal{F}\) as the points in \(\mathcal{F}\) at a distance one from it. The poset \((\mathcal{F},\leq)\) generates a directed acyclic graph whose vertices are \(\mathcal{F}\) and the edges connect every pair of subsequent elements, which are such that \(\mathcal{C}_{1}\leq\mathcal{C}_{2}\) and if \(\mathcal{C}_{1}\leq\mathcal{C}\leq\mathcal{C}_{2},\mathcal{C}\in\mathcal{F}\), then either \(\mathcal{C}_{1}=\mathcal{C}\) or \(\mathcal{C}_{2}=\mathcal{C}\), with orientation from \(\mathcal{C}_{1}\) to \(\mathcal{C}_{2}\). In this setting, the distance between elements \(\mathcal{C}_{1},\mathcal{C}_{2}\in\mathcal{F}\), with \(\mathcal{C}_{1}\leq\mathcal{C}_{2}\), denoted by \(d(\mathcal{C}_{1},\mathcal{C}_{2})=d(\mathcal{C}_{2},\mathcal{C}_{1})\), is the length of the shortest path from \(\mathcal{C}_{1}\) to \(\mathcal{C}_{2}\). **Definition 6.3**.: _The neighborhood in \(\mathcal{F}\) of each \(\mathcal{C}\in\mathcal{F}\) is defined as_ \[N(\mathcal{C})=\left\{\mathcal{C}^{\prime}\in\mathcal{F}:d(\mathcal{C}, \mathcal{C}^{\prime})=1\right\}.\] We exemplify \(\mathcal{F}\) and its neighborhoods for an ASF architecture, a sup-generating architecture and the composition of an ASF and a W-operator. **Example 6.4**.: Let \(\mathcal{A}\) be the ASF architecture \(\mathcal{A}_{3}\) in Figure 7. In this example, \(\mathcal{F}\) is isomorphic to the Boolean lattice \(\mathcal{P}(W)^{2}\) and an element \((A,B)\in\mathcal{P}(W)^{2}\) realizes the ASF with two pairs of openings and closings in which the first has structuring element \(A\) and the second \(B\). Denote by \(\mathcal{C}_{A,B}\in\mathcal{F}\) the element of \(\mathcal{F}\) associated to \((A,B)\). We have that \[N(\mathcal{C}_{A,B})=\left\{\mathcal{C}_{C,B}\in\mathcal{F}:d(C,A)=1\right\} \cup\left\{\mathcal{C}_{A,C}\in\mathcal{F}:d(C,B)=1\right\},\] in which \(d(C,A)\) and \(d(C,B)\) are the respective distance in \(\mathcal{P}(W)\), so a neighbor of \(\mathcal{C}_{A,B}\) is obtained by adding or removing one point from \(A\) or \(B\). This is an example in which the poset \((\mathcal{F},\leq)\) is actually a Boolean lattice, which is partially depicted in Figure 9. **Example 6.5**.: Let \(\mathcal{A}\) be the sup-generating architecture \(\mathcal{A}_{1}\) in Figure 6. In this example, \(\mathcal{F}\) is isomorphic to a subset of the Boolean lattice \(\mathcal{P}(\mathcal{P}(W))^{3}\) and each element \((\mathcal{I}_{1},\mathcal{I}_{2},\mathcal{I}_{3})\) of this subset represents the sup-generating MCG given by the supremum of three sup-generating operators with intervals \((\mathcal{I}_{1},\mathcal{I}_{2},\mathcal{I}_{3})\). Denote by \(\mathcal{C}_{\mathcal{I}_{1},\mathcal{I}_{2},\mathcal{I}_{3}}\in\mathcal{F}\) the element of \(\mathcal{F}\) associated to \((\mathcal{I}_{1},\mathcal{I}_{2},\mathcal{I}_{3})\). We have that \[N(\mathcal{C}_{\mathcal{I}_{1},\mathcal{I}_{2},\mathcal{I}_{3}}) =\{\mathcal{C}_{\mathcal{I},\mathcal{I}_{2},\mathcal{I}_{3}}\in \mathcal{F}:d(\mathcal{I},\mathcal{I}_{1})=1\}\cup\{\mathcal{C}_{\mathcal{I}_{ 1},\mathcal{I},\mathcal{I}_{3}}\in\mathcal{F}:d(\mathcal{I},\mathcal{I}_{2})=1\}\] \[\quad\cup\left\{\mathcal{C}_{\mathcal{I}_{1},\mathcal{I}_{2}, \mathcal{I}}\in\mathcal{F}:d(\mathcal{I},\mathcal{I}_{3})=1\right\},\] in which \(d(\mathcal{I},\mathcal{I}_{j}),j=1,2,3\), is the respective distance in the poset of the intervals in \(\mathcal{P}(\mathcal{P}(W))\), so a neighbor of \(\mathcal{C}_{\mathcal{I}_{1},\mathcal{I}_{2},\mathcal{I}_{3}}\) is obtained by adding or removing a certain point from one extremity of one of its three intervals. \(\blacksquare\) **Example 6.6**.: Let \(\mathcal{A}\) be the architecture in Figure 8. In this example, \(\mathcal{F}\) is isomorphic to a subset of the Boolean lattice \(\mathcal{P}(W)\times\mathcal{P}(\mathcal{P}(W))^{3}\) and each element \((A,\mathcal{I}_{1},\mathcal{I}_{2},\mathcal{I}_{3})\) of this subset realizes the MCG given by the composition of a one layer ASF with structuring element \(A\) and the supremum of three sup-generating operators with intervals \((\mathcal{I}_{1},\mathcal{I}_{2},\mathcal{I}_{3})\). Denote by \(\mathcal{C}_{\mathcal{A},\mathcal{I}_{1},\mathcal{I}_{2},\mathcal{I}_{3}}\in \mathcal{F}\) the element of \(\mathcal{F}\) associated to \((A,\mathcal{I}_{1},\mathcal{I}_{2},\mathcal{I}_{3})\). We have that \[N(\mathcal{C}_{A,\mathcal{I}_{1},\mathcal{I}_{2},\mathcal{I}_{3 }})= \{\mathcal{C}_{B,\mathcal{I}_{1},\mathcal{I}_{2},\mathcal{I}_{3}} \in\mathcal{F}:d(A,B)=1\}\cup\left\{\mathcal{C}_{\mathcal{A},\mathcal{I}, \mathcal{I}_{2},\mathcal{I}_{3}}\in\mathcal{F}:d(\mathcal{I},\mathcal{I}_{1})=1\right\}\] \[\quad\cup\left\{\mathcal{C}_{\mathcal{A},\mathcal{I}_{1},\mathcal{ I},\mathcal{I}_{3}}\in\mathcal{F}:d(\mathcal{I},\mathcal{I}_{2})=1\right\}\cup \left\{\mathcal{C}_{\mathcal{A},\mathcal{I}_{1},\mathcal{I}_{2},\mathcal{I}} \in\mathcal{F}:d(\mathcal{I},\mathcal{I}_{3})=1\right\},\] in which the distances are on the respective posets of sets and intervals, so a neighbor of \(\mathcal{C}_{A,\mathcal{I}_{1},\mathcal{I}_{2},\mathcal{I}_{3}}\) is obtained by adding or removing one point from the structuring element \(A\) or from one extremity of one of its three intervals. \(\blacksquare\) ## 7. Training Canonical Discrete Morphological Neural Networks A training algorithm for a CDMNN should receive an architecture and a sample of pairs of input and target sets, and return a realization of the architecture that well _approximates_ the set operation applied to the input sets to obtain the respective target set. For a \(N\geq 1\), let \[\mathcal{D}_{N}=\{(X_{1},Y_{1}),\ldots,(X_{N},Y_{N})\}\] be a sample of \(N\) input sets \(X\) and target sets \(Y\). We assume there exists a finite set \(F\in\mathcal{P}(E)\) such that \(X_{j},Y_{j}\subseteq F,j=1,\ldots,N\). For example, if \(E=\mathbb{Z}^{2}\) and \(X,Y\) represent binary images with \(d\times d\) pixels, then we could consider \(F=\{-d/2,\ldots,d/2\}^{2}\). It is assumed that each \(Y\) is, apart from a random noise, obtained from \(X\) by applying a set operator \(\psi^{\star}\in\Omega\). Fixed a DMNN architecture \(\mathcal{A}\), the main objective of the learning is to estimate \(\psi^{\star}\) by a \(\hat{\psi}\in\mathcal{H}(\mathcal{A})\) which, we hope, is such that \(\hat{\psi}\approx\psi^{\star}\). The main paradigm of learning is empirical risk minimization [47], in which \(\hat{\psi}\) is obtained by minimizing the empirical loss incurred when \(\hat{\psi}(X)\) is employed to approximate \(Y\) in sample \(\mathcal{D}_{N}\). Common losses in this setting are the absolute loss and the intersection of union loss. The absolute loss is defined as \[\ell_{a}(X,Y;\psi)=\frac{|\{x\in F:x\in(Y^{c}\cap\psi(X))\cup(Y\cap[\psi(X)]^{c })\}|}{|F|}, \tag{7.1}\] that is the proportion of the points in \(F\) which are in \(Y\) but not in \(\psi(X)\) or that are in \(\psi(X)\) but not in \(Y\). The intersection of union (IoU) loss is defined as \[\ell_{IoU}(X,Y;\psi)=1-\frac{|Y\cap\psi(X)|}{|Y\cup\psi(X)|},\] that is the proportion of points in \(Y\cup\psi(X)\) that are not in \(Y\cap\psi(X)\). The IoU loss is more suitable for form or object detection tasks, while the absolute loss is suitable for general image transformation tasks. When the loss function is not of importance, we denote it simply by \(\ell\). Fix an architecture \(\mathcal{A}=(\mathcal{V},\mathcal{E},\mathcal{F})\) and, for each \(\mathcal{C}\in\mathcal{F}\), denote by \(\psi_{\mathcal{C}}:=\psi_{\mathcal{G}}\) as the set operator generated by MCG \(\mathcal{G}=(\mathcal{V},\mathcal{E},\mathcal{C})\). We define the mean empirical loss of each realization \(\mathcal{C}\in\mathcal{F}\) of the DMNN architecture \(\mathcal{A}\) as \[L_{\mathcal{D}_{N}}(\mathcal{C})=\frac{1}{N}\sum_{j=1}^{N}\ell(X_{j},Y_{j}; \psi_{\mathcal{C}}).\] The optimal minimization of \(L_{\mathcal{D}_{N}}\) in \(\mathcal{F}\) is a highly combinatorial problem whose complexity is exponential on the number \(|\mathcal{V}|\) of computational vertices, specially when \(\mathcal{F}\) is the Cartesian product of subsets of Boolean lattices, as is the case of unrestricted CDMNN. To circumvent the computational complexity, we propose an iterative algorithm that performs a greedy search of \(\mathcal{F}\) and returns a _local minimum_ of \(L_{\mathcal{D}_{N}}\) in \(\mathcal{F}\) that, although it may not be a minimizer of \(L_{\mathcal{D}_{N}}\), may be suitable for the application at hand. The proposed algorithm is the instantiation of a U-curve algorithm, that was initially proposed to minimize U-shaped functions in Boolean lattices [3, 18, 36, 37]. The proposed algorithm is a lattice version of the gradient descent algorithm (GDA) [39], and we call it the _lattice gradient descent algorithm_ (LGDA). As in the GDA, we may add stochasticity to meaningfully decrease the problem complexity and do not get stuck on bad local minimums. In the following sections, we present the details of the LGDA and its stochastic version (SLGDA). ### Lattice Gradient Descent Algorithm for training CDMNN The LGDA performs an iterative greedy search of \(\mathcal{F}\), at each step jumping to the point in the neighborhood of the current point with the least mean empirical loss, and stopping after a predefined number of steps (epochs). This algorithm is analogous to the gradient descent algorithm to minimize differentiable functions in \(\mathbb{R}^{p},p\geq 1\), since both algorithms go, at each time, to the direction with the least function value. In the gradient descent algorithm, this direction is opposed to the function gradient, while in the LGDA this direction is a chain of \((\mathcal{F},\leq)\) that passes through the current point that contains its neighbor with least mean empirical loss. The LGDA algorithm is formalized in Algorithm 1. It is initialized at a point \(\mathcal{C}\in\mathcal{F}\) and a predetermined number of training epochs is fixed. The initial point is stored as the point with minimum empirical loss visited so far. For each epoch, \(\mathcal{C}\) is updated to a point in its neighborhood with the least empirical loss. If this point has an empirical loss lesser than that of the point with minimum loss visited so far, the current point is stored as the minimum. After all epochs, the algorithm returns the visited point with minimum empirical loss. ``` 1:\(\mathcal{C}\in\mathcal{F}\), Epochs 2:\(L_{min}\gets L_{\mathcal{D}_{N}}(\mathcal{C})\) 3:\(\widehat{C}\leftarrow\mathcal{C}\) 4:for run \(\in\{1,\ldots,\text{Epochs}\}\)do 5:\(\mathcal{C}\leftarrow\mathcal{C}^{\prime}\) s.t. \(\mathcal{C}^{\prime}\in N(\mathcal{C})\) and \(L_{\mathcal{D}_{N}}(\mathcal{C}^{\prime})=\min\{L_{\mathcal{D}_{N}}(\mathcal{ C}^{\prime\prime}):\mathcal{C}^{\prime\prime}\in N(\mathcal{C})\}\) 6:if\(L_{\mathcal{D}_{N}}(\mathcal{C})<L_{min}\)then 7:\(L_{min}\gets L_{\mathcal{D}_{N}}(\mathcal{C})\) 8:\(\widehat{C}\leftarrow\mathcal{C}\) 9:return\(\widehat{\mathcal{C}}\) ``` **Algorithm 1** Lattice Gradient Descent Algorithm for training a CDMNN. **Remark 7.1**.: _On the one hand, since the poset \((\mathcal{F},\leq)\) is known a priori, for any \(\mathcal{C}\in\mathcal{F}\) the set \(N(\mathcal{C})\) is known so the complexity of minimizing \(L_{\mathcal{D}_{N}}\) in \(N(\mathcal{C})\) should be \(|N(\mathcal{C})|\mathcal{O}(L_{\mathcal{D}_{N}})\), in which \(\mathcal{O}(L_{\mathcal{D}_{N}})\) is the computational complexity of \(L_{\mathcal{D}_{N}}\). On the other hand, if the LGDA algorithm were applied directly on poset \((\mathcal{H}(\mathcal{A}),\leq)\), fixed a \(\psi\in\mathcal{H}(\mathcal{A})\), the computation of its neighborhood in \((\mathcal{H}(\mathcal{A}),\leq)\) would be problem-specific and could have a complexity that is not linear on the number of neighbors. Therefore, sub-optimally minimizing the empirical loss in \(\mathcal{F}\) via the LGDA should be less computationally complex than doing so in \(\mathcal{H}(\mathcal{A})\)._ Although the returned DMNN parameter \(\widehat{\mathcal{C}}\) may not be a minimizer of \(L_{\mathcal{D}_{N}}\) in \(\mathcal{F}\), it may have a low enough mean empirical loss and well approximate the actual minimizer. Furthermore, Algorithm 1 may be run starting from many initial points \(\mathcal{C}\) and lead to distinct local minimums \(\widehat{\mathcal{C}}\), with mean empirical loss tending to that of the minimizer as more initial points are considered. We illustrate the LGDA algorithm in a sequential architecture. **Example 7.2** (Training an ASF architecture).: Consider the ASF architecture \(\mathcal{A}_{3}\) in Figure 7 for which \(\mathcal{F}\) is isomorphic to the Boolean lattice \(\mathcal{P}(W)^{2}\) (cf. Example 6.4). In Figure 9 we present selected elements of this Boolean lattice when \(E=\mathbb{Z}^{2}\) and \(W=\{-1,0,1\}^{2}\) is the three by three square centered at the origin of \(E\). The number on top of the elements in Figure 9 is the mean empirical loss in a sample \(\mathcal{D}_{N}\) of the set operator generated by the respective realization of the architecture. The colored edges represent the path of the LGDA starting from the empty sets after three epochs. The edges of paths that remove points from the structuring elements were omitted for a better visualization. In this example, each element in \(\mathcal{F}\) has 18 neighbors, which are obtained by adding or removing a point from one of its two sets, so the complexity of each step of the LGDA is at most eighteen times the complexity of applying the realized set operator to each input point in sample \(\mathcal{D}_{N}\) and comparing the result with the respective target set to compute the mean empirical loss. \(\blacksquare\) Even though the LGDA does not perform an exhaustive search of \(\mathcal{F}\), Algorithm 1 may be too complex and may not be feasible to solve practical problems. Furthermore, it may get stuck in local minimums or realize a periodical path, visiting the same points multiple times. Indeed, since at each step it jumps to the neighbor with the least empirical loss, it may jump back to the previous point if it is the neighbor with the least empirical loss, and keep jumping between these two points during the remaining epochs. Inspired by the success of stochastic gradient descent algorithms, we propose the Stochastic Lattice Gradient Descent Algorithm (SLGDA) to decrease the computational complexity of the LGDA and mitigate the risk of getting stuck at local minimums. Figure 9. Selected elements in the lattice \((\mathcal{F},\leq)\) of the ASF architecture \(\mathcal{A}_{3}\) in Figure 7 when \(E=\mathbb{Z}^{2}\) and \(W=\{-1,0,1\}^{2}\). The number on top of the elements is the mean empirical loss of the set operator realized by them, and the colored edges represent the path of the LGDA starting from the empty sets after three epochs. The edges pointing to sets obtained by removing a point from a set were omitted for a better visualization. The returned element \(\hat{\mathcal{C}}\) is outlined in green. ### Stochastic Lattice Gradient Descent Algorithm for training CDMNN The LGDA has two computational bottlenecks: the cost of calculating \(L_{\mathcal{D}_{N}}(\mathcal{C})\) and the number of neighbors in \(N(\mathcal{C})\). In order to calculate \(L_{\mathcal{D}_{N}}(\mathcal{C})\) it is necessary to compute the graph \((\mathcal{V},\mathcal{E},\mathcal{C})\) for all the \(N\) inputs \(\{X_{1},\ldots,X_{N}\}\). Since it may be expensive to compute this graph, specially if the dimensionality of \(X\) is too great1, the calculation of \(L_{\mathcal{D}_{N}}\) may be an impeditive of Algorithm 1 for great values of \(N\). Moreover, if the number of neighbors of each point \(\mathcal{C}\in\mathcal{F}\) is too great, then Algorithm 1 may not be computable since at each step it should calculate the mean empirical loss of every point in a neighborhood. We propose the SLGDA to circumvent these bottlenecks by considering sample batches to calculate the empirical loss and by sampling neighbors of a point at each batch. We also expect with this algorithm to avoid periodical paths and getting stuck at local minimums. Footnote 1: We define the dimensionality of \(X\) as the size \(|F|\) of \(F\). The SLGDA is formalized in Algorithm 2. The initial point \(\mathcal{C}\in\mathcal{F}\), a batch size2\(b\), the number \(n\) of neighbors to be sampled at each step, and the number of training epochs is fixed. The initial point is stored as the point with minimum empirical loss visited so far. For each epoch, the sample \(\mathcal{D}_{N}\) is randomly partitioned in \(N/b\) batches \(\{\tilde{\mathcal{D}}_{b}^{(1)},\ldots,\tilde{\mathcal{D}}_{b}^{(N/b)}\}\). For each batch \(\tilde{\mathcal{D}}_{b}^{(j)}\), \(n\) neighbors of \(\mathcal{C}\) are sampled and \(\mathcal{C}\) is updated to the sampled neighbor with the least empirical loss \(L_{\tilde{\mathcal{D}}_{b}^{(j)}}\), that is calculated on the sample batch \(\tilde{\mathcal{D}}_{b}^{(j)}\). Observe that \(\mathcal{C}\) is updated at each batch, so during an epoch, it is updated \(N/b\) times. At the end of each epoch, the empirical loss \(L_{\mathcal{D}_{N}}(\mathcal{C})\) of \(\mathcal{C}\) on the whole sample \(\mathcal{D}_{N}\) is compared with the loss of the point with the least empirical loss visited so far at the end of an epoch, and it is stored as this point if its empirical loss is lesser. After the predetermined number of epochs, the algorithm returns the point with the least empirical loss on the whole sample \(\mathcal{D}_{N}\) visited at the end of an epoch. Footnote 2: We assume that \(N/b\) is an integer to easy notation. If this is not the case, the last batch will contain less than \(b\) points. The computational complexity of each epoch of Algorithm 2 is of order \(N/b\left[n\mathcal{O}(L_{\tilde{\mathcal{D}}_{b}^{(j)}})\right]\) \(+\)\(\mathcal{O}(L_{\mathcal{D}_{N}})\) so it is controlled by the batch size \(b\) and the number of sampled neighbors \(n\). The SLGDA could be applied to find an initial point for the LGDA, or when the LGDA gets stuck at a local minimum or on a periodical path. Moreover, the LGDA and SLGDA may be combined by, for example, taking sample batches, but considering all neighbors of a point without sampling. In the next section, we illustrate the algorithms on an applied example. ## 8. Boundary recognition of digits with noise In this section, we apply the SLGDA and LGDA to train CDMNN to recognize the boundary of noised digits. The algorithms were implemented in \(\mathbf{R}\)[35] and are available as a _package_ at [https://github.com/dmarcondes/DMNN](https://github.com/dmarcondes/DMNN). The basic morphological operators are calculated by the functions in the **mmand** package [14]. The training was performed on a personal computer with processor 13th Gen Intel Core i7-1355U x 12 and 16 GB of ram. The calculation of the empirical loss of the neighbors in \(N(\mathcal{C})\) or \(\tilde{N}(\mathcal{C})\) was parallelized in 12 cores. The training sample is composed of ten pairs of \(56\times 56\) images, one of each digit from 0 to 9, and the validation sample is composed of another ten pairs of \(56\times 56\) images, one of each digit from 0 to 9. The input images are black and white digits with pepper and salt noise, and the output images are the boundary of the input digit. The input and output images in the validation sample are presented in Figure 13. We trained ten CDMNN architectures, which we denote by the operators computed in their layers. We use the notation \(kSGd\) to mean a layer that computes the supremum of \(k\) sup-generating operators locally defined within \(W_{d}\coloneqq\{-(d-1)/2,\ldots,(d-1)/2\}^{2}\) and we denote by \(ASFd\) a layer that calculates an ASF with structuring element in \(\mathcal{P}(W_{d})\). For example, we denote by \(16SG3\) the architecture given by the supremum of \(16\) sup-generating operators locally defined within \(W_{3}=\{-1,0,1\}^{2}\) and by \(ASF3-16SG3\) the architecture whose output is the supremum of \(16\) sup-generating operators locally defined in \(W_{3}\) applied to the output of an ASF with structuring element in \(\mathcal{P}(W_{3})\). The ten considered architectures are presented in Table 8.2 and illustrated in Figure 10. In the figure, we omitted the operators parameters and the orientation of the graph, that is always from vertex \(X\) to vertex \(\psi\), for a better visualization. The ten architectures were trained for \(1,000\) epochs with the SLGDA sampling \(10\) neighbors and considering batch sizes of \(1,5\) and \(10\) (whole sample). We considered the IoU loss function and the parameters were initialized so each vertex compute an operator given by a random perturbation of the identity operator. We considered the same initial point of each architecture for the SLGDA with batch sizes of \(1,5\) and \(10\). Finally, when more than one sampled neighbor had a same least empirical loss in a step of the algorithm, the next point of the algorithm was uniformly sampled from these neighbors. The results are presented in Table 8.2. First, we observe that the architectures with higher mean IoU loss on the validation sample are those in which there are operators locally defined within \(W_{5}\). In these cases, the class of operators generated by the architecture is more complex and the respective poset \((\mathcal{F},\leq)\) has more points, so more samples and more epochs should be necessary to properly train these more complex architectures. It is also interesting to note that, for example, even though the architectures ASF3-16SG3-16SG3 and ASF3-16SG5 generate W-operators locally defined within a same window, the performance of ASF3-16SG3-16SG3 was significantly better, since it had a lesser validation loss. This can be explained by the fact that the collection of W-operators generated by ASF3-16SG3-16SG3 is more restricted than that generated by ASF3-16SG5, so fewer epochs and samples are necessary to properly train it. Figure 11 presents, for each architecture and batch size, the mean empirical IoU at each epoch. We see in this figure and in Table 8.2 that there were cases in which the minimum was visited in later epochs and others in which it was visited in early epochs. On the one hand, when the batch size equals 5 or 10, the empirical IoU usually decreases abruptly from time to time until it reaches the minimum visited and, once a low value of the empirical loss is attained, it does not vary significantly in later epochs. On the other hand, when the batch size is 1, the empirical IoU decreases quickly in the early epochs and is highly unstable during later epochs, coming back to high values and not significantly decreasing the empirical loss. Indeed, apart from the architecture ASF3-8SG5, the minimum when the batch size is 5 or 10 was achieved, with few exceptions, between epochs \(700\) and \(1,000\), while the other epochs are still when the batch size was 1 the minimum was achieved at as early as the epoch 133. The lowest validation loss was obtained when training with a batch size of 1 for two architectures, and with a batch size of 5 and 10 for four architectures each, and the lowest validation loss overall was obtained for the architecture ASF3-16SG3-16SG3 trained with a batch size of 1. The \(1,000\) training epochs took from around 7 to 27 minutes, and training with a batch size of 1 took longer in all cases. The trained CDMNN that obtained the lesser validation loss (ASF3-16SG3-16SG3 with \(b=1\)) was fine trained via the LGDA for another 100 epochs with batch sizes of 1, 5 and 10 (whole sample). Considering the CDMNN trained via the SLGDA as the initial point, the LGDA took around 21 minutes to fine train this architecture during 100 epochs, but achieved a lesser training and validation losses for all batch sizes, as presented in Table 8.3. The lowest validation loss was achieved with the whole sample as a batch, that is the LGDA described in Algorithm 1, and the total training time Figure 11. Mean empirical IoU at each epoch of the SLGDA for each architecture and batch size. of this architecture was around 48 minutes. We see in Figure 12 a behavior analogous to that of Figure 11, since the empirical loss with batch sizes of 5 and 10 decreased abruptly during the training, while that of a sample batch size of 1 was highly unstable during training. We also retrained the ASF3-16SG3-16SG3 architecture from scratch via the LGDA with batch sizes of \(1,5\) and \(10\) during \(1,000\) epochs and obtained \begin{table} \begin{tabular}{l r r r r r r} \hline Arch & b & \(L_{\mathcal{D}_{N}}(\widehat{\mathcal{C}})\) & Val. loss & Total time (m) & Time to min (m) & Epochs to min \\ \hline [MISSING_PAGE_POST] \hline **asf3\_16sg3\_16sg3** & **1** & **0.052** & **0.066** & **26.649** & **26.571** & **997** \\ asf3\_16sg3\_16sg3 & 5 & 0.082 & 0.099 & 17.961 & 9.579 & 533 \\ asf3\_16sg3\_16sg3 & 10 & 0.086 & 0.097 & 17.045 & 13.765 & 807 \\ \hline asf3\_16sg5 & 1 & 0.259 & 0.261 & 27.297 & 21.517 & 792 \\ asf3\_16sg5 & 5 & 0.130 & 0.141 & 17.423 & 14.271 & 823 \\ asf3\_16sg5 & 10 & 0.169 & 0.175 & 16.945 & 15.193 & 899 \\ \hline asf3\_8sg3\_8sg3 & 1 & 0.108 & 0.115 & 20.514 & 12.466 & 609 \\ asf3\_8sg3\_8sg3 & 5 & 0.144 & 0.157 & 11.784 & 8.525 & 726 \\ asf3\_8sg3\_8sg3 & 10 & 0.053 & 0.070 & 11.076 & 8.969 & 815 \\ \hline asf3\_8sg5 & 1 & 0.406 & 0.409 & 20.920 & 17.521 & 840 \\ asf3\_8sg5 & 5 & 0.400 & 0.404 & 12.189 & 1.872 & 162 \\ asf3\_8sg5 & 10 & 0.279 & 0.283 & 11.513 & 8.322 & 727 \\ \hline \end{tabular} \end{table} Table 8.2. Results of the training of ten CDMNN architectures to recognize the boundary of digits with noise by the SLGDA sampling 10 neighbors and considering sample batches of size \(b=1,b=5\) and \(b=10\), and the IoU loss. For each architecture and batch size, we present the minimum empirical loss, the empirical loss on the validation sample of the trained CDMNN, the total training time, the time it took to visit the minimum and the epochs it took to visit the minimum. the results in Table 8.3. The training epochs took at least 3 hours to complete, and both the training and validation loss of the trained DMNN were higher than that obtained via the SLGDA and by refining the SLGDA result via the LGDA. In this example, there was no gain in training via the LGDA and the best result was attained by refining via the LGDA the CDMNN trained via the SLGDA. The image predicted by the fine trained CDMNN ASF3-16SG3-16SG3 with a batch size of 10 for each input image in the validation sample is presented in Figure 13. As expected from prior information about the problem at hand, an architecture that applies an ASF at the first layer should have a better performance than architectures that do not, since an ASF has the property of removing noise. We see in Figure 13 that the first layer of the trained CDMNN is indeed removing the noise. After this noise removal, the second layer, given by a W-operator represented by the supremum of 16 sup-generating operators, is crudely recognizing the boundary. The third layer, also given by a W-operator represented by the supremum of 16 sup-generating operators, is refining the boundary of the digit roughly recognized by the first W-operator, obtaining a good visual result. \begin{table} \begin{tabular}{l c c c c c c c} \hline \hline Type & b & \(L_{\mathcal{D}_{N}}(\mathcal{\bar{C}})\) & Val. loss & Epochs & Total time (m) & Time to min (m) & Epochs to min \\ \hline Refine & 1 & 0.046 & 0.052 & 100 & 22.618 & 10.999 & 49 \\ Refine & 5 & 0.041 & 0.051 & 100 & 20.942 & 12.780 & 61 \\ **Refine** & **10** & **0.040** & **0.049** & **100** & **21.057** & **19.562** & **93** \\ \hline Retrain & 1 & 0.073 & 0.084 & 1000 & 229.884 & 218.805 & 952 \\ Retrain & 5 & 0.076 & 0.089 & 1000 & 236.037 & 180.437 & 820 \\ Retrain & 10 & 0.251 & 0.265 & 1000 & 206.915 & 184.376 & 895 \\ \hline \hline \end{tabular} \end{table} Table 8.3. Results of the fine training of the CDMNN architecture ASF3-16SG3-16SG3 via 100 epochs of the LGDA starting from the parameters trained by the SLGDA with batch size of 1 and of retraining the CDMNN architecture ASF3-16SG3-16SG3 from scratch via \(1,000\) epochs of the LGDA starting from a random perturbation of the identity operator. The fine training and retraining were performed considering sample batches of size \(b=1,b=5\) and \(b=10\), and the IoU loss. For each training type and batch size, we present the minimum empirical loss, the empirical loss on the validation sample of the trained CDMNN, the number of training epochs, the total training time, the time it took to visit the minimum and the epochs it took to visit the minimum. ## 9. Discussion ### Main contributions The method proposed in this paper merges the classical heuristic design of morphological operators with the estimation of parameters via machine learning. The method proposes the definition of a class of W-operators through a DMNN architecture and the training of its parameters through a discrete stochastic combinatorial optimization algorithm analogous to the stochastic gradient descent algorithm. An important characteristic of this approach is that the class of W-operators can be quite general (e.g., all W-operators with at most \(k\) elements in the basis) or specialized (e.g., filters and granulometric filters) according to expected properties of the target operator, i.e., prior information. The semantic expressed by algebraic properties of classes of operators is a differential relative to other methods, such as deep neural networks. Some benefits of the proposed approach are: smaller sample complexity, interpretation of the designed operator and smaller computational complexity (due to constraints on the class of operators and the stochasticity of the training algorithm). The semantics of the designed operator being comprehensible open doors for further research in the context of DMNN. Figure 12. Mean empirical IoU at each epoch of the LGDA when fine training and retraining the architecture ASF3-16SG3-16SG3 for each batch size. More specifically, this paper formalizes the DMNN and proposes lattice gradient descent algorithms to train CDMNN. Although CDMNN are a special case of classical designs of set operators, that combine erosions and dilations via composition, infimum, supremum and complement, its formalization enabled a general algorithm to learn W-operators from data via a greedy search of a lattice. Furthermore, the CDMNN are transparent by design and fully interpretable, since the basis of the operators realized by them can be computed and from it their properties can be deduced. Finally, prior information about the problem at hand can be inserted into a CDMNN architecture to obtain better results and to account for features of the domain of application. ### Algorithmic and application perspectives We have not exhausted the study of DMNN for binary image analysis, but rather presented its main features, and we leave many important questions for future research. First, Figure 13. Input and output images in the validation sample, images predicted by the fine trained ASF3-16SG3-16SG3 architecture, image obtained after applying the ASF3 layer of this architecture and image obtained after applying the ASF3-16SG3 layers of this architecture. the LGDA and SLGDA are not exclusive to train CDMNN and can be readily generalized to any DMNN that is parameterized by a vector of sets and intervals, or any other object contained in a lattice or a poset. Nevertheless, the complexity of the algorithm may increase when \((\mathcal{F},\leqslant)\) does not have a lattice structure, as can be the case of restricted CDMNN, since the computation of the neighborhoods \(N(\mathcal{C})\) may be costly. An interesting topic for future research is, based on prior information and domain knowledge, to design specific DMNN to solve problems of interest and implement efficient algorithms based on the LGDA for their training. An efficient implementation of the general LGDA and SLGDA in Algorithms 1 and 2 to train CDMNN is also a topic for future research. The implementation of an algorithm to calculate the window and the basis of an MCG, as discussed in Remark 5.2, is also necessary. Once an efficient implementation is available, it would be interesting to further study empirical features illustrated in the application. For instance, it is necessary to better understand the effect of the architecture complexity and the batch size on the generalization quality of the trained CDMNN in order to build optimized architectures and properly select hyperparameters such as the number of epochs and batch size. ### Possible extensions We believe the DMNN could be extended to represent a broader class of morphological operators in more general complete lattices. For instance, the canonical decomposition results of [4] were extended by [5] for general complete lattices and could in theory be the foundation of a DMNN architecture. In this instance, it may be necessary to combine the LGDA with a continuous optimization algorithm since the operators may not be represented by parameters in a lattice, but rather by a set of parameters that can be decomposed into a lattice of subsets of parameters. For example, for gray-scale images, the parameters of a vertex may be the window on which its operator is locally defined and the function representing the structural element whose domain is the window. The LGDA could be applied to select the window, while another algorithm would have to learn the structural element. The extension of DMNN to gray-scale images is a promising line of research which we pretend to follow. The main bottlenecks to extending DMNN to solve more general image processing problems are the definition of a lattice algebra under which the problem can be solved via a lattice operator and the development of practical algorithms to train DMNN under this lattice algebra. For example, if one could develop a lattice algebra for RGB images (see [2, 34, 45] for examples of possible algebras) and design image transformation operators as lattice operators, then the results of [5] could be applied to define the architectures of a DMNN, and if one could develop algorithms to train them, then they could be applied to solve state-of-the-art problems. Such an extension seems a giant leap now, but having a controllable and interpretable analogue of deep learning for general image transformation tasks would be a major advance and even if MM methods cannot attain this degree of generalization, some insights and important results may be achieved along the way. Such a possibility is a motive in itself to further study MM and DMNN extensions. ### Prior information and Neural Architecture Search The quality of a DMNN is associated with the correct design of its architecture, in the sense of it representing operators that approximate a target operator, and with the efficiency of its training from both a computational and sample complexity perspective. Therefore, from an algebraic perspective, it is necessary to better understand how desired classes of operators can be efficiently represented by unrestricted CDMNN architectures since they can be more efficiently trained. Furthermore, it is necessary to properly insert prior information into the architecture, so it represents a collection of operators _compatible_ with the problem being solved, on which it is statistically possible, in the sense of statistical learning theory [47], to learn with the available sample size. However, when strong prior information is not available, it may not be possible to properly design a DMNN architecture, and should be learned from data. A state-of-the-art topic in deep learning is architecture selection, or Neural Architecture Search (NAS) [17], whose methods are mainly based on computation demanding procedures to optimize the architecture based on data within an automatic machine learning (AutoML) paradigm [20]. Such an automatic approach would be incompatible with MM, since it does not take into account prior information and the properties of morphological operators. A true MM method for architecture selection should, based on prior information about the problem at hand, consider a set of candidate DMNN architectures and then select one of them based on data. In some instances, the available prior information may not be enough to properly build one architecture, but may suffice to design a collection of candidate architectures that should be evaluated on data to select the _best_ one. These architectures should generate collections of operators with increasing complexity, and selecting them should also be a mean of avoiding over-fitting and controlling the generalization quality of the learned architecture. If these candidate architectures could be themselves organized in a lattice, then they could be selected by a LGDA algorithm. The study of lattice-based architecture selection methods is an important line of research to control the complexity of the architecture relative to the sample size and obtain better practical results when strong prior information is absent. This is a line of research we are currently following. ### Impact to Mathematical Morphology Mathematical Morphology is a classical paradigm for representing non-linear lattice transformations and had been a state-of-the-art method for image analysis, from the 1960s until recently, when it was overshadowed by the success of deep learning techniques. However, even though established MM methods cannot compete with deep learning from a performance point-of-view, MM has the great advantage of being a mathematically grounded image processing theory from which one can build methods that are completely controllable and interpretable, characteristics that deep learning lacks in general. Therefore, we argue, resonating the arguments of [1], that one should not disregard deep learning techniques, that are extremely useful and have many qualities, and expect to obtain state-of-the-art methods based solely on classical MM methods, but should rather rethink MM in view of modern learning techniques. The method proposed in this paper follows this research agenda. We believe that the DMNN is a _true_ MM method since it retains the control over the design and interpretability of results of classical MM methods, which is an advantage over CNN. For instance, even though CNN can easily solve virtually any problem of binary image analysis, they cannot, in general, be controlled to represent a restricted class of operators based on prior information or be interpreted to understand the properties of the learned operator. Both these tasks are natural to DMNN, since its architecture can be specified via the MM toolbox to represent any class of operators, and, once it is trained, the basis of the operator can be computed and its properties can be fully known. Therefore, the DMNN are better than CNN from a semantic point of view. Since, from an algorithmic perspective, the SLGDA makes the training of DMNN scalable, they are a viable mathematically grounded practical method which ought to be further explored. Besides providing a path to bring MM to the deep learning era, this paper also merges two, sometimes competing, paradigms of MM: heuristic design and automatic design via machine learning. The advocates of the heuristic approach have argued that the machine learning approach did not take into account strong prior information and did not have as much control over the operator design, while the advocates of the machine learning paradigm have argued that machine learning methods were necessary to scale MM applications and obtain good practical results via a less time-consuming approach. In hindsight, we believe that both arguments are valid and hope with the DMNN approach to unite these paradigms and help to regain the relevance of MM in the deep learning era. ## Acknowledgments D. Marcondes was funded by grants #22/06211-2 and #23/00256-7, Sao Paulo Research Foundation (FAPESP), and J. Barrera was funded by grants #14/50937-1 and #2020/06950-4, Sao Paulo Research Foundation (FAPESP).
2307.14045
Physics-Informed Neural Networks for Parametric Compressible Euler Equations
The numerical approximation of solutions to the compressible Euler and Navier-Stokes equations is a crucial but challenging task with relevance in various fields of science and engineering. Recently, methods from deep learning have been successfully employed for solving partial differential equations by incorporating the equations into a loss function that is minimized during the training of a neural network. This approach yields a so-called physics-informed neural network. It is not based upon classical discretizations, such as finite-volume or finite-element schemes, and can even address parametric problems in a straightforward manner. This has raised the question, whether physics-informed neural networks may be a viable alternative to conventional methods for computational fluid dynamics. In this article we introduce an adaptive artificial viscosity reduction procedure for physics-informed neural networks enabling approximate parametric solutions for forward problems governed by the stationary two-dimensional Euler equations in sub- and supersonic conditions. To the best of our knowledge, this is the first time that the concept of artificial viscosity in physics-informed neural networks is successfully applied to a complex system of conservation laws in more than one dimension. Moreover, we highlight the unique ability of this method to solve forward problems in a continuous parameter space. The presented methodology takes the next step of bringing physics-informed neural networks closer towards realistic compressible flow applications.
Simon Wassing, Stefan Langer, Philipp Bekemeyer
2023-07-26T08:53:38Z
http://arxiv.org/abs/2307.14045v2
# Physics-Informed Neural Networks for Parametric Compressible Euler Equations ###### Abstract The numerical approximation of solutions to the compressible Euler and Navier-Stokes equations is a crucial but challenging task with relevance in various fields of science and engineering. Recently, methods from deep learning have been successfully employed for solving partial differential equations by incorporating the equations into a loss function that is minimized during the training of a neural network. This approach yields a so-called physics-informed neural network. It is not based upon classical discretizations, such as finite-volume or finite-element schemes, and can even address parametric problems in a straightforward manner. This has raised the question, whether physics-informed neural networks may be a viable alternative to conventional methods for computational fluid dynamics. In this article we introduce an adaptive artificial viscosity reduction procedure for physics-informed neural networks enabling approximate parametric solutions for forward problems governed by the stationary two-dimensional Euler equations in sub- and supersonic conditions. To the best of our knowledge, this is the first time that the concept of artificial viscosity in physics-informed neural networks is successfully applied to a complex system of conservation laws in more than one dimension. Moreover, we highlight the unique ability of this method to solve forward problems in a continuous parameter space. The presented methodology takes the next step of bringing physics-informed neural networks closer towards realistic compressible flow applications. keywords: Physics-Informed, Partial Differential Equation, Deep Learning ###### Abstract We consider the problem of finding a solution to boundary value problem for the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of finding a solution to the problem of the problem of finding a \begin{tabular}{l l} \(M_{\infty}\) & Mach number at far field \\ \(M\) & local Mach number \\ \(\eta\) & artificial viscosity \\ \(\nu\) & artificial viscosity factor \\ \(\tilde{\nu}\) & prescribed artificial viscosity factor \\ \(M_{\rm red}\) & number of reduction epochs \\ \(k\) & order of reduction function \\ \(\alpha\) & weighting factor for initial condition loss \\ \(\beta\) & weighting factor for boundary condition loss \\ \(\gamma\) & weighting factor for viscosity penalty loss \\ \(a\) & semi-major axis of ellipse \\ \(b\) & semi-minor axis of ellipse \\ \(e\) & eccentricity of ellipse \\ \(lr\) & learning rate \\ \(\theta\) & deflection angle for oblique shock \\ \(\delta\) & angle between shock and wall \\ \(C_{p}\) & coefficient of pressure \\ \(r\) & radius of cylinder \\ \(N_{\rm batch}\) & number of point per mini-batch \\ \end{tabular} _Abbreviations_ \begin{tabular}{l l} PINN & physics-informed neural network \\ LBFGS & Limited-memory Broyden-Fletcher-Goldfarb-Shanno algorithm \\ ADAM & adaptive momentum estimation optimization algorithm \\ PDE & partial differential equation \\ AD & automatic differentiation \\ CFD & computation fluid dynamics \\ \end{tabular} ## 1 Introduction The motion of compressible fluids gives rise to nonlinear partial differential equations (PDEs) such as the Euler and Navier-Stokes equations. The numerical solution of these equations is for example essential for the development of future aircraft configurations. State of the art solvers typically rely on finite volume or finite element algorithms [1; 2; 3; 4]. These algorithms have been developed and refined for decades and they are in regular use for industrial problems such as aircraft design. These classical algorithms discretize the domain and thus require the construction of carefully crafted computational grids, so-called meshes. Superficially speaking, a finer mesh will result in a more accurate result but will also increase the computational cost needed. Despite a non-negligible progress in efficiency in recent years, long term prospects for further acceleration of these codes seem limited. Especially, transferring these methods to potentially advantageous hardware like graphic processing units has shown to be challenging. Besides, classical algorithms solve a problem for one specific instance of boundary conditions and/or initial conditions. Therefore, for certain tasks, such as design optimization, multiple evaluations of the solver are necessary. The cumulative computational effort of multiple solver evaluations can be significant and is therefore a possibly limiting factor for the usage for commercially relevant problems. Our interest is to investigate numerical methods which have the potential to be applied on future hardware promising an acceleration of orders of magnitude. In particular, some initial works indicate that one may be able to transfer deep learning based approaches to quantum computers [5], even though the potential for acceleration on this hardware is currently still unclear. In addition, to successfully implement such an approach, it is necessary to explore the methodological basis that is required for successful algorithmic implementation. With the rising popularity of machine learning methods and especially deep neural networks, alternative approaches for the solution of differential equations, based on methods from this rapidly advancing field have become a popular alternative to classical solvers One of these techniques are Physics-Informed Neural Networks (PINNs). The fundamental idea of PINNs is to use a neural network as a parametric ansatz function for the approximation of the PDE solution and to optimize the networks parameters by minimizing a loss functional which directly incorporates the differential equations as well as the initial and boundary con ditions. During the training of the network, the loss functional is evaluated at random points inside of the domain. PINNs are fundamentally different to classical algorithms because they do not rely on a spatial or temporal discretization in a classical sense. Instead a continuous parametric ansatz-function (a neural network) is evaluated and optimized at (oftentimes randomly distributed) points in the domain. Hence, the task of mesh-generation is replaced by the task to find a point distribution in space and time and an appropriate network dimension (i.e. number and width of layers) which, when combined, result in a fast convergence and satisfactory final accuracy. Compared to classical methods, PINNs can directly tackle parametric problems. A single network can be trained in a continuous parameter space and yield approximate solutions for a whole range of parameter combinations of interest. This ability may have implications for aforementioned use cases like design optimization. Similar approaches for approximating PDE solutions via neural networks have been proposed decades ago in works of Lagaris et al. [6] and Dissanayake et al. [7]. Even though the idea seems natural due to the ability of universal function approximation of neural networks [8], the method has only recently gained popularity. Nowadays, the networks can be trained more efficiently due to the availability of high performance graphics cards. Moreover, the implementation of such algorithms has become straightforward with software libraries for deep learning, such as Tensorflow [9] and PyTorch [10]. The term PINN has been introduced by Raissi et al. [11] who demonstrated the use of this approach on a number of nonlinear PDEs for forward and inverse problems. Subsequently, PINNs have shown to be applicable for solving stochastic PDEs [12], inverse problems [13] and parametric problems [14]. Various alterations of the vanilla PINN formulation have been proposed and improvements for the implementation of boundary conditions [15; 16; 17], training facilitation [18; 19] and training point selection [20; 21] have been developed. Among many other domains, the flow simulation community has readily adapted PINNs for various cases such as blood flow [16; 22], turbulent convection [23] and aerodynamics of airfoils [24]. An important property of PINNs is the fact they allow for a straightforward integration of additional available data from various sources such as experiments or higher fidelity simulations into the training process. Raissi et al. [25] demonstrate how noisy concentration data of a passive flow agent can compensate for incomplete boundary conditions. Even for compressible flows, there has been some success to employ PINNs for simple forward and especially inverse prob lems which exhibit discontinuities [26; 27; 27]. Again, the introduction of additional solution data into the loss is used to compensate for incomplete boundary conditions. For a more extensive overview on the usage of PINNs for fluid dynamics the interested reader is referred to [28]. Fuks and Tchelepi [29] have identified the need for additional dissipation when solving one dimensional hyperbolic conservation laws with PINNs once shocks are present. They pointed out the similarity to classical methods, which use artificial dissipation to approximately solve conservation laws. Recently, Coutinho et al. [30] have proposed multiple methods to locally or globally choose artificial viscosity values and demontrate the efficacy of their method on different one dimensional systems. Here we take this idea to more complex problems by solving the stationary compressible Euler equations in two spatial dimensions. The compressible Euler equations are a system of conservation laws with four dependent variables (typically density, the velocity components and the energy) that describe the behavior of inviscid compressible fluids. We also observe that additional dissipative terms are able to facilitate convergence which is the case for supersonic but also for subsonic problems without shocks as shown in A. To avoid highly dissipative solutions, we introduce two novel ideas. On the one hand we predict the locally necessary dissipation strength by letting the network predict the local viscosity alongside the primitive variables. On the other hand, we use a penalty loss term to control dissipation levels during the training. By initially training with high viscosity and then reducing the dissipation later, we obtain non dissipative solutions while ensuring convergence during training. We do, however, not only solve these equations for one instance of boundary conditions, but rather use the ability of PINNs to approximate parametric solutions, essentially extending the dimension of the problems by one or two parameter dimensions. We choose to restrict this analysis to classical forward problems, meaning that no additional data is incorporated into the loss function, besides the information that is available in the form of fully provided boundary conditions. So far, the investigation PINNs for complex problems governed by the Euler equations has oftentimes been restricted to inverse problems where some form of data of the solution is already provided [26; 31]. While the ability of incorporating this data is clearly an advantage and possibly one of the most important use cases of PINNs, we believe that a solid understanding of the forward problem is necessary for reliably tackling more complex problems (e.g. higher dimensional). In Sec. 2 we give a general introduction to the standard PINN approach for solving (parametric) initial and boundary value problems. In Sec. 2.2 we discuss the application of the approach to the compressible Euler equations and explain how the incorporation of artificial dissipation during the training can facilitate convergence when looking at the aerodynamic problem of calculating the flow around solid obstacles. In Sec. 3 we solve the subsonic flow around an ellipse with a parametric boundary shape and and variable Mach numbers. In Sec. 4 we solve the supersonic oblique shock problem with variable Mach number. Consider also Sec. A, where non-parametric solutions to the problems are shown and how PINNs struggle to obtain accurate predictions without artificial viscosity. Finally, in Sec. 5 the presented results are evaluated in a more general context and future implications as well as newly arising questions are discussed. The novelties of the paper are twofold. To the best of our knowledge for the first time, we solve parametric problems, governed by the two dimensional compressible Euler equations with PINNs. In addition we introduce a novel adaptive viscosity training procedure which improves prediction accuracy of PINNs on supersonic problems significantly, compared to previously published results. Preliminary results of the presented ideas have been presented at the 8th European Congress on Computational Methods in Applied Sciences and Engineering [32]. ## 2 Methods ### Physics-Informed Neural Networks Physics-informed neural networks are deep neural networks, which are employed to approximate solutions to differential equations. A general initial-boundary value problem for the unknown function \(\mathbf{u}\) on the spatial domain \(\Omega\subset\mathbb{R}^{d}\) and in the time interval \((0,T)\subset\mathbb{R}\) can be defined as: \[\begin{split}\mathcal{D}(\mathbf{u}(\mathbf{x},t),\mathbf{x},t)=0& (\mathbf{x},t)\in(\Omega\times(0,T))\\ \mathcal{B}(\mathbf{u}(\mathbf{x},t),\mathbf{x},t)=0&(\mathbf{x}, t)\in(\partial\Omega\times(0,T))\\ \mathcal{I}(\mathbf{u}(\mathbf{x},0),\mathbf{x})=0&\mathbf{x}\in \Omega,\end{split} \tag{1}\] where \(\mathcal{D}\) is a general differential operator and \(\mathcal{I}\) and \(\mathcal{B}\) are the initial and boundary condition, respectively. The operator \(\mathcal{D}\) may include multiple non-linear differential terms of different order. A neural network \(\mathbf{\hat{u}}(\mathbf{\theta},\mathbf{x},t)\) is now Figure 1: Schematic representation of the physics-informed neural network approach for solving the 2D stationary Euler equations. A fully connected neural network predicts the primitive variables \(\rho,u,v,E\) and the local viscosity factor \(\nu\) at a point \((x,y)\) in the physical domain and for optional parameters of the problem \((\tau_{0},\tau_{1},\dots)\). The loss is calculated as the sum of squares of the residual of the PDE, the boundary condition and an additional viscosity penalty term. Partial derivatives of the primitive variables with respect to \(x\) or \(y\) are required for the loss and can be calculated using automatic differentiation. used to approximate the unknown solution \(\hat{\mathbf{u}}(\mathbf{\theta},\mathbf{x},t)\approx\mathbf{u}(\mathbf{x},t)\). The vector \(\mathbf{\theta}\) includes neural networks parameters (weights and biases) which have to be adjusted during an optimization/training process to find an accurate approximation of the solution. For this, an objective or loss functional \(\mathcal{L}\) is defined. If \(\hat{\mathbf{u}}(\mathbf{\theta},\mathbf{x},t)\) is a solution to Eqs. 1, the left hand side of Eqs. (1) vanishes on the entire domain \(x\in\Omega\) and for all times \(t\in(0,T)\). Therefore, a simple loss functional is \[\mathcal{L}(\hat{\mathbf{u}}(\mathbf{\theta})) = \int_{0}^{T}\int_{\Omega}\mathcal{D}(\hat{\mathbf{u}}(\mathbf{\theta}, \mathbf{x},t))^{2}\ \,\mathrm{d}\mathbf{x}\ \mathrm{d}t\,+\alpha\int_{\Omega}\mathcal{I}(\hat{\mathbf{u}}(\mathbf{ \theta},\mathbf{x},0),\mathbf{x})^{2}\ \,\mathrm{d}\mathbf{x} \tag{2}\] \[+ \beta\int_{0}^{T}\int_{\partial\Omega}\mathcal{B}(\hat{\mathbf{u}}( \mathbf{\theta},\mathbf{x},t),\mathbf{x},t)^{2}\ \,\mathrm{d}s(\mathbf{x})\ \mathrm{d}t\] which is \(0\) and thus minimal if \(\hat{\mathbf{u}}(\mathbf{\theta},\mathbf{x},t)\) is a solution to Eqs. 1. The coefficients \(\alpha\) and \(\beta\) scale the importance of the boundary and initial loss term with respect to the residual term. Since the network \(\hat{\mathbf{u}}(\mathbf{\theta},\mathbf{x},t)\) can only be evaluated at discrete input values, the loss is instead calculated by taking the sum over a representative point distribution inside of the spatial and temporal domain \[\mathcal{L}(\hat{\mathbf{u}}(\mathbf{\theta},\mathbf{x},t))=\mathcal{L}_{ \mathrm{Res}}\ +\ \mathcal{L}_{\mathrm{I}}\ +\ \mathcal{L}_{\mathrm{B}} \tag{3}\] \[\mathcal{L}_{\mathrm{Res}}=\frac{1}{N}\sum_{i=1}^{N}\mathcal{D}( \hat{\mathbf{u}}(\mathbf{\theta},\mathbf{x}_{i},t_{i}))^{2}\qquad\quad\mathbf{x}_{i}\in \Omega\ ;t_{i}\in(0,T)\] \[\mathcal{L}_{\mathrm{I}}=\alpha\frac{1}{N_{\mathrm{I}}}\sum_{i=1 }^{N_{\mathrm{I}}}\mathcal{I}(\hat{\mathbf{u}}(\mathbf{\theta},\mathbf{x}_{i},0))^{2} \qquad\quad\mathbf{x}_{i}\in\Omega\] \[\mathcal{L}_{\mathrm{B}}=\beta\frac{1}{N_{\mathrm{B}}}\sum_{i=1}^ {N_{\mathrm{B}}}\mathcal{B}(\hat{\mathbf{u}}(\mathbf{\theta},\mathbf{x}_{i},t_{i}))^{2} \qquad\quad\mathbf{x}_{i}\in\partial\Omega\ ;t_{i}\in(0,T)\] where \(N_{\mathrm{Res}}\), \(N_{\mathrm{I}}\) and \(N_{\mathrm{B}}\) are the number of points that evaluate the residual, the initial condition and the boundary condition, respectively. Since for a well defined problem, the bounds of the domain are known, the generation of these training points can be achieved with quasi-random low discrepancy sequences such as Sobol [33] or Halton [34] or with other methods like Latin Hypercube sampling [35] at little additional cost. For a uniform point distribution, the calculation of the loss functional can be interpreted as a Monte-Carlo integration of Eq. (2) where the normalization by the volume has been dropped. As highlighted in various publications [21; 20; 26], a non uniform distribution of training points or an adaptive training point selection, based on the local residual may accelerate training and improve the final accuracy for certain problems. The partial derivatives in \(\mathcal{D}(\boldsymbol{\hat{u}}(\boldsymbol{\theta},\boldsymbol{x}_{i},t_{i}))\) are calculated, using automatic differentiation (AD). The network parameters are then tuned using an iterative optimization algorithm. The most popular algorithms are variants of stochastic gradient descend such as Adam [36]. During the optimization, the gradient of the loss with respect to the network parameters \(\nabla_{\boldsymbol{\theta}}\mathcal{L}(\boldsymbol{\hat{u}}(\boldsymbol{ \theta},\boldsymbol{x}_{i},t_{i}))\) has to be calculated. This can again be achieved, using automatic differentiation and the backpropagation algorithm [37]. As usual for neural networks, the optimization problem is generally non-convex and the optimizer can therefore converge to local minima or regions of vanishing gradients. Furthermore, for partial differential equations such as the compressible Euler equations which may not have a unique solution, a minimum of the loss may not always correspond to a physically reasonable solution. #### 2.1.1 Parametric Problems One prospect of physics-informed neural networks is the possibility to solve parametric problems. Let \(\tau\) be a general parameter of the initial and boundary value problem. A PINN approximation \(\boldsymbol{\hat{u}}(\boldsymbol{\theta},\boldsymbol{x},t,\tau)\) of the unknown solution \(u(\boldsymbol{x},t,\tau)\) simply receives \(\tau\) as an additional input to the neural network alongside \(\boldsymbol{x}\) and \(t\). The parameter adds an additional dimension to the input space and thus the training points. The training points are now sampled in a \(d+2\)-dimensional domain \((\boldsymbol{x},t,\tau)\in\Omega\times(0,T)\times(\tau_{\min},\tau_{\max})\). The parameter \(\tau\) can then be incorporated into the calculation of any of the loss terms in Eq. (3). Similarly, this approach can be extended to more than one parameter. ### Approximation of Stationary Compressible Flows with PINNs The inviscid flow of compressible fluids is governed by the Euler equations which describe the conservation of mass, momentum and energy in a continuous fluid. The two-dimensional Euler equations in their differential conservative form are given by \[\begin{split}\frac{\partial\mathbf{W}}{\partial t}+\frac{\partial\mathbf{F}_ {x}}{\partial x}+\frac{\partial\mathbf{F}_{y}}{\partial y}=0,\\ \mathbf{W}=\begin{pmatrix}\rho\\ \rho u\\ \rho v\\ \rho E\end{pmatrix},\,\mathbf{F}_{x}=\begin{pmatrix}\rho u\\ \rho u^{2}+p\\ \rho uv\\ \rho Hu\\ \end{pmatrix},\,\mathbf{F}_{y}=\begin{pmatrix}\rho v\\ \rho uv\\ \rho v^{2}+p\\ \rho Hv\end{pmatrix}\end{split} \tag{4}\] where \(\mathbf{W}\) is the vector of the conservative variables with the density \(\rho\), the local fluid velocity \(\mathbf{q}=(u,v)\), and the total specific energy \(E\). The total enthalpy \(H\) is defined as \(H=E+\frac{p}{\rho}\). This system of partial differential equations can be closed by the equations of state of ideal gases, which yield \(p=\rho(\kappa-1)(E-\rho\mathbf{q}^{2}/2)\), with \(\kappa\) being the ratio of specific heats (\(\kappa=1.4\) for air). The Mach number \(M=\|\mathbf{q}\|_{2}/a\) is the ration between the velocity and the speed of sound \(a=\sqrt{\kappa p/\rho}\). For aerodynamic problems one is oftentimes interested in the steady-state solution. Therefore, the time derivative in Eq. (1) is omitted. When solving this system of equations with a physics-informed neural network, the network outputs can be chosen to approximate the primitive variables \(\mathbf{\hat{u}}(\mathbf{\theta},\mathbf{x})\approx(\rho(\mathbf{x}),u(\mathbf{x}),v(\mathbf{x}),E(\bm {x}))\). The residual loss term becomes \[\mathcal{L}_{\text{Res}}=\frac{1}{N}\sum_{i=1}^{N}\left(\frac{\partial\mathbf{F}_ {x}(\mathbf{\hat{u}}(\mathbf{\theta},\mathbf{x}_{i}))}{\partial x}+\frac{\partial\mathbf{F}_{ y}(\mathbf{\hat{u}}(\mathbf{\theta},\mathbf{x}_{i}))}{\partial y}\right)^{2}. \tag{5}\] The partial derivatives are calculated using automatic differentiation. In the following, we focus on the calculation of flows around solid obstacles and alongside walls. In particular, we use Dirichlet boundary conditions for the inflow/far-field and wall boundaries for the obstacles. For the Dirichlet boundary conditions the conserved variables approach \(\mathbf{W}_{\infty}=(\rho_{\infty},\rho_{\infty}u_{\infty},\rho_{\infty}v_{\infty },\rho_{\infty}E_{\infty})\) which is in the context of aerodynamics typically determined by the Mach number \(M_{\infty}\). Also, the flow should be tangential to the obstacles surface. This results in a boundary loss term of \[\begin{split}\mathcal{L}_{\text{B}}=\beta\bigg{(}\frac{1}{N_{ \infty}}\sum_{i=1}^{N_{\infty}}\left[\mathbf{W}(\mathbf{\hat{u}}(\mathbf{\theta},\mathbf{x}_{ i}))-\mathbf{W}_{\infty}\right]^{2}+\\ \frac{1}{N_{\text{ob}}}\sum_{j=1}^{N_{\text{ob}}}\left[\mathbf{q}( \mathbf{\hat{u}}(\mathbf{\theta},\mathbf{x}_{j}))\cdot\mathbf{n}_{j}\right]^{2}\bigg{)}\end{split} \tag{6}\] with \(N_{\infty}\) points \(\mathbf{x}_{i}\) on the boundary of the physical domain and \(N_{\rm ob}\) points \(\mathbf{x}_{j}\) on the boundary of the obstacle. The surface normals at positions \(\mathbf{x}_{j}\) are given by \(\mathbf{n}_{j}\). #### 2.2.1 Adaptive Artificial Dissipation A fundamental challenge for PINNs in the search of solutions to the compressible Euler equations lies in finding a physically reasonable minimum of the loss (i.e. an entropy solution). By definition of the loss function (3), any weak solution of Eqs. (4) that fulfills a given set of boundary conditions is a (global) minimum of the loss and thus a possible final state of the network to converge to. Furthermore, the optimizer can always converge to local minima, which correspond to unphysical solutions. In classical computational methods for the solution of compressible flows, artificial dissipation is introduced in the form of upwind schemes or through a combination of central schemes and explicit dissipative terms [1]. The dissipation smears out discontinuities and has a stabilizing effect. For PINNs, the necessity of additional dissipative terms for successfully solving scalar conservation laws has also been observed by Fuks et al. [29]. More complex systems of conservation laws, such as the compressible Euler Figure 2: Schematic representation of boundary conditions and boundary training points for the cylinder and the oblique shock test case. The Dirichlet boundary conditions for a Mach number of \(M_{\infty}\) are applied at the points \(\mathbf{x}_{i}\) with \(i=1\dots N_{\infty}\). The wall boundary conditions at the obstacle surfaces are enforced at the points \(\mathbf{x}_{j}\) with \(j=1\dots N_{\rm ob}\). Note that for the parametric problems, one additional sampling dimension per parameter is appended to the euclidean spatial coordinates. equations require advanced methods for locally determining reasonable dissipation levels while also minimizing the dissipative effects on the solution. Here we propose a novel training procedure for flexibly and reliably solving the compressible Euler equations which uses artificial dissipation. The novelty of this procedure is twofold. Firstly, the PINN locally predicts an appropriate value of viscosity which is necessary to stabilize the training. Secondly, the strength of dissipation is reduced during the training process which minimizes errors that are introduced by the dissipation. The dissipation is introduced as an additional term in Eqs. (4): \[\frac{\partial\mathbf{W}}{\partial t}+\frac{\partial\mathbf{F}_{x}}{\partial x}+\frac{ \partial\mathbf{F}_{y}}{\partial y}=\eta\Delta\mathbf{W} \tag{7}\] where \(\Delta=(\partial_{x}^{2}+\partial_{y}^{2})\) is the Laplacian and \(\eta\) can be interpreted as an artificial viscosity. From an optimization point of view, the dissipation acts as a regularization of the optimization/training problem. Similarly to classical scalar dissipation schemes like the JST-scheme [38], we scale the dissipation locally, based on the spectral radius of the flux jacobians \[\eta=\nu(a+|\mathbf{q}|) \tag{8}\] where \(\nu\) is a viscosity factor for which adequate values have to be selected. The linear scaling of the viscosity \(\eta\) with the wave speed \(a+|\mathbf{q}|\) results in higher viscosity values in regions with higher Mach numbers. Furthermore, when considering parametric problems with variable inflow velocities, the viscosity is adjusted according to the resulting variable wave speed. However, additional local upscaling of the viscosity may be required to deal with certain highly nonlinear or unstable regions in the domain, such as shocks. Instead of deriving an analytical sensor function, we leverage the ability of the neural network to adjust the viscosity. To do so, the network predicts the viscosity factor \(\nu\) alongside the primitive variables \(\mathbf{\hat{u}}(\mathbf{\theta},\mathbf{x})\approx(\rho(\mathbf{x}),u(\mathbf{x}),v(\mathbf{x}),E(\bm {x}),\nu(\mathbf{x}))\). To enforce positivity of the viscosity and to allow for a flexible prediction of values close to 0, the exponential function is used as an activation for \(\nu\) in the last layer of the network. In addition, since we are interested in the inviscid solution, an additional loss term \(\mathcal{L}_{\nu}\) is introduced which penalized high viscosity values : \[\mathcal{L}_{\nu}=\gamma|\nu-\tilde{\nu}|. \tag{9}\] The prescribed viscosity value \(\tilde{\nu}\) can now be used to control the strength of the dissipative term, while still allowing the network to locally choose \(\nu(\mathbf{x})\neq\tilde{\nu}\) when necessary. We use the modulus to enforce positivity of the term instead of the square because local outliers should not be penalized. We want to stress that \(\tilde{\nu}\) is not related to a turbulent eddy viscosity for which this symbol is oftentimes used in turbulence models. The addition of dissipation changes the physical problem and the resulting solution will disagree with the fully inviscid solution. Essentially, one is no longer solving for an inviscid solution and therefore the fluid is decelerated by shear stresses. In classical methods, scalar dissipation schemes employ fourth order differences in smooth flow regions which only dampens higher frequency modes of the flow, limiting the effect of the artificial viscosity on the solution. Second order differences are only used near discontinuities, where a scheme of first order accuracy is required due to Godunov's theorem. An additional fourth order differential term could theoretically be added to Eq. (7). This would however introduce fourth order derivatives which would require additional expensive evaluations of the computational graph. Instead, we follow a different approach and adjust the viscosity during the training process, to limit the dissipative effect on the final solution. Therefore, we propose a 3 phase training routine: Phase 1: Train with ADAM at a constant viscosity \(\tilde{\nu}=\nu_{0}\) until no significant changes in the residual loss are observed. Phase 2: Train with ADAM and reduce the prescribed viscosity \(\tilde{\nu}\) until \(\tilde{\nu}=0\). Continue at \(\tilde{\nu}=0\) until no significant changes in the residual loss are observed. Phase 3: Train with LBFGS and \(\tilde{\nu}=0\) until convergence. The idea of this procedure is to guide the network towards a physical solution (the entropy solution) during the initial training phase. Once the network has converged to a state that resembles a physical but viscous solution, the viscosity can be reduced, since, from this point on, the network should be in a state near the entropy solution. In phase 2, \(\tilde{\nu}\) is reduced to 0, to decrease the dissipative effect on the prediction. However, the network can still predict viscosity factors \(\nu(\mathbf{x})>0\) where necessary, keeping the penalty term in balance with the residual and other loss terms. We reduce the prescribed viscosity factor \(\tilde{\nu}\) as follows: \[\tilde{\nu}_{i}=\begin{cases}\nu_{0}\bigg{(}1-\left(\frac{i}{M_{\rm red}}\right)^ {k}\bigg{)}&\text{if}\ \ 0\leq i\leq M_{\rm red}\\ 0&\text{if}\ \ M_{\rm red}<i\end{cases} \tag{10}\] Where \(i\in\mathbb{N}\) is the epoch counter starting at phase 2 and \(M_{\rm red}\) is the epoch at which \(\tilde{\nu}=0\) is reached. The exponent \(k\in\mathbb{N}^{+}\) can be used to modify the shape of the reduction curve. For \(k=1\) the reduction is linear and for \(k>1\) it is accelerating. For the first two phases, Adam [36] is used as the optimizer. A final training period with the quasi-Newton LBFGS optimizer [39] has shown to be effective for convergence of PINNs in general and has been crucial to achieve high levels of accuracy with the proposed training procedure. A schematic representation of the described PINN approach is shown in Fig. 1 and a schematic view of the boundary points for the later discussed test cases is shown in Fig. 2. ## 3 Parametric Flow around Ellipse As the first parametric problem we consider the flow around an ellipse with a parametric inflow boundary condition and a parametric ellipse boundary. We position the two-dimensional ellipsoid at the center of the domain \(\Omega=(-1,1)\times(-1,1)\). The semi-major axis \(a\in(0.1,0.2)\) is variable whereas the semi minor axis \(b=0.1\) is constant. Therefore at a value of \(a=0.1\), we have a cylinder of radius \(r=0.1\) which corresponds to an eccentricity of \(e=\sqrt{1-b^{2}/a^{2}}=0\). For the maximal major axis of \(a=0.2\) the eccentricity is \(e=3/4\). As a second varying parameter we consider the Mach number \(M_{\infty}\in(0.2,0.4)\). The neural network receives both parameters as additional inputs. The training points are therefore sampled in a four-dimensional domain. The upper limit of the Mach number of \(M_{\infty}=0.4\) is slightly below the critical Mach number of the cylinder, at which the velocity locally exceeds the speed of sound. An initial prescribed artificial viscosity factor of \(\nu=7.5\cdot 10^{-4}\) is used based on the previous investigations. We have observed that this value is typically a reasonable value and can be used both for subsonic and supersonic problems. Since the actual artificial viscosity in Eq. (8) is scaled with the local wave speed, the strength of the dissipation naturally increases at higher Mach numbers. We choose a fully connected neural network of constant layer width with hyperbolic tangent activation functions. Adaptive activation functions (see e.g. [40]) have been reported to improve prediction accuracy and to speed up convergence in PINNs. For the analyzed problems we could observe improved convergence early during the training, when using layer-wise adaptive activations. However, when using the LBFGS optimizer during the final training phase, they have performed inconsistently (i.e. on some runs similarly to \(\tanh\) and on others very poorly). Therefore, we continue to use standard hyperbolic tangent activations. The loss weighting factors are set to \(\beta=1\) and \(\gamma=5\). As shown in various publications, such as [41; 18; 19], the (dynamic) weighting of loss terms is an effective technique to accelerate the convergence and improve the accuracy because it can compensate imbalances in the gradients between the different loss terms. However, we have observed that for certain problems, adaptive loss term weighting may lead to instabilities during the early stages of the training. For the presented problems we do not see significant imbalances during the training and are able to achieve satisfying results with a constant weighting factor. Therefore, dynamic loss term weighting is not considered herein. A summary of all hyperparameters is shown in Tab. 2. This includes the utilized optimizer, the learning rate \(lr\) the batchsize \(N_{\text{batch}}\) and the prescribed viscosity factor \(\tilde{\nu}\). To cover the four-dimensional input space, the number of residual training points is comparatively high (\(N=100000\)). However, since a mini-batch routine is used for the first two training phases, this has typically no negative effect on the training speed. Only during the last training phase 3, memory may be a limiting factor because the LBFGS optimizer is incompatible with mini-batch training. Therefore, we use a reduced number of training points during the last training phase (\(N=30000\)). A non-uniform point distribution is used. Half of the points are distributed uniformly across the entire physical domain \(\Omega=(-1,1)\times(-1,1)\) using the Halton sequence [34]. For the other half of the points, the y-coordinate is sampled using a normal distribution with a variance of \(\sigma=0.07\) and with a uniform distribution for the x-coordinate. A projection of the resulting point distribution to the physical domain is shown in Fig. 4. For both point sets, the same number of points is used to represent the boundary of the physical domain and the cylinder (\(N=N_{\infty}=N_{\text{ob}}\)). No additional data of the solution is incorporated into the loss, besides the boundary conditions. We are thus approximating the solution of a fully determined (but not over determined) forward problem. The resulting predictions for the velocity field for three cases are shown in Fig. 5 in comparison to reference finite volume simulations. For additional information on the calculation of reference finite volume results, see Sec. C. One can see that for the cylindrical shape (\(a=0.1\)) even at \(M_{\infty}=0.4\), close to the critical Mach number, the results are visually indistinguishable to the reference solution. The plot of the absolute error reveals that the inaccuracies are fairly uniform. For the other two parameter sets with ellipsoidal shapes, a similar quality of the results can be observed. The bottom row of Fig 5 depicts the artificial viscosity \(\eta\). The viscosity is relatively uniform (see the scale of the color bars) for all three Mach number. Up and downstream of the ellipse, the viscosity is however slightly reduced. For certain problems it can be observed that PINNs can perform inconsistently, depending on the random initialization of network parameters at the start of the training. To ensure the consistency of our proposed method we analyze the accuracy over 12 training runs with different random initialization seeds. Fig. 6 (a) shows the mean error in the density field during training. The best and worst prediction accuracy over the 12 runs (i.e. the spread of the predictions) is also indicated. While differences occur between different initializations during early training phases, all models converge to a similar final accuracy. Fig. 6 (b) shows the prescribed viscosity factor \(\tilde{\nu}\) as well as the predicted mean viscosity \(\nu\) during training. Besides a spike in the first few epochs, the prescribed and predicted viscosity are identical during the first phase. In phase 2 we see that the viscosity is comparatively quickly reduced. After about 2500 epochs, it remains at a constant value around \(\nu=10^{-6}\). This indicates that this lower viscosity is sufficient for stabilizing the training and that \(\nu\) can be reduced relatively fast during phase 2 without causing any instabilities. This is to be expected for this relatively stable subsonic problem. However, as shown in A.1, the initial viscosity in phase 1 is still required to converge to reasonable predictions which is even apparent for the non-parametric version of the problem. For a quantitative assessment of the errors, we consider the pressure coefficient \(C_{\rm p}\), the local Mach number \(M\) and the density \(\rho\) for 100 quasi-random parameter values in the parameter space. For each parameter set, the mean absolute difference to the reference solution was calculated for a small square that contains the cylinder (\(-0.5<x<0.5;-0.5<y<0.5\)). Fig. 3 shows the resulting absolute errors for the density. These errors are then normalized with the range of values of the reference solution for each individual quantity. The final relative errors in Tab. 1 are the mean over all datasets and all 12 runs. For a detailed explanation of the error calculation see Sec. Appendix C. The hyperparameters are not optimized and higher accuracies may be possible when employing hyperparameter optimization e.g. on the network shape and learning rate. For all presented results, the Python package SMARTy [42] was used, which is a toolbox for surrogate modeling and other data driven tasks. SMARTy supports Tensorflow and PyTorch as backends for the creation and training of neural network models. With the tensorflow backend the model is trained in 24 hours on a single NVIDIA A100 graphics card. All the presented models were using double precision for the floating point numbers. Once trained, the evaluation of the model is fast. The prediction of the model at 300.000 points takes about 0.5 s. ## 4 Parametric Oblique Shock As a supersonic test case we consider the Oblique Shock problem with a variable inflow Mach number of \(M\in(2,3)\). The test case describes a scenario where a supersonic inflow is deflected by a wedge with deflection angle \(\theta=10^{\circ}\). The resulting attached shock originates from the corner of Figure 3: Mean absolute errors on subsonic test case between parametric PINN and reference finite volume result for the density field, for different parameter sets. the wedge. We define the shock angle with respect to the surface of the wedge as \(\delta\). The shock angle is a unique function of the deflection angle and the incoming Mach number \(M_{1}=M_{\infty}\) as stated by the \(\theta\)-\(\beta\)-\(M\) relation. The field variables after the shock can be calculated analytically from \(M_{1}\) and \(\theta\)[43]. This problem has been solved with PINNs in a non-parametric version with \(M=2\) in [26] and [27]. For a comparison of the non-parametric results with and without adaptive viscosity, see A. To the best of our knowledge this is the only other forward supersonic test case which has been solved with PINNs for the two-dimensional compressible Euler equations. PINNs have however been applied to other inverse supersonic problems [31] where shock locations are already given by solution data that is provided inside of the physical domain. Here, we solve the forward problem in the continuous parameter space for \(M_{\infty}=(2,3)\). We use a total of 100000 points for the evaluation of the residual and the viscosity penalty loss. 80000 of these points are uniformly sampled in the three-dimensional input space \((x,y,M_{\infty})\in\Omega\times(2,3)=(0,1)\times(0,1)\times(2,3)\). An additional 10.000 points are uniformly sampled on the upper \((x,y,M_{\infty})\in\Omega\times\{3\}\) and lower bound \((x,y,M_{\infty})\in\Omega\times\{2\}\) of the Figure 4: Projection of point distribution of four-dimensional parametric space onto physical domain for subsonic ellipse problem. Note the variation in the axis \(a\) in the boundary points. Figure 5: Comparison of parametric PINN solution with a reference finite volume result for different Mach numbers and ellipse eccentricities. The absolute errors between the reference and the PINN solution are shown in Figs. (c), (g) and (k). Figs. (d), (h) and (l), show the artificial viscosity \(\eta\). Figure 6: Error, prescribed and predicted viscosity during training for flow around ellipse. Fig (a) also shows the spread of prediction accuracy for 12 random initializations of the network. parameter space to enhance the accuracy towards the borders. The Halton sequence [34] is used for generating all three point sets. Note that, in contrast to previous works, we do not require clustered training points [26] or domain decomposition [27] for accurate predictions. This is advantageous, because no previous knowledge of the solution is required for the point generation or for the decomposition. Dirichlet boundary conditions are applied at the top and left surface. No-flux wall boundary conditions are used for the bottom boundary. Since the shock originates from the bottom left corner, we increase the boundary point density for \(x\in(0,0.1)\) and \(y\in(0,0.1)\) as sketched in Fig. 2. As before, an initial prescribed viscosity factor of \(\tilde{\nu}=7.5\cdot 10^{-4}\) is used. The network consists of 7 layers with layers of 30 neurons and \(\tanh\) activations. The loss term weights are \(\beta=1\) and \(\gamma=5\). A detailed overview of training parameters is shown in B.3. Again, no additional data of the solution is incorporated into the loss, besides the boundary conditions and we are solving strictly the forward problem. Fig. 7 provides an overview of the result for three different Mach numbers in comparison to the analytical solution. The field values before and after the shock are accurately predicted and the shock is well resolved. Slight inaccuracies in the shock angle are visible. The bottom row shows the artificial viscosity. Due to the local adaptivity, the dissipation is increased close to the shock. This shows that the proposed method is able to locally identify regions which require additional viscosity for stabilization. In this sense, the network is able to take over the role of so called pressure sensors, which are used in classical CFD methods to switch to first-order schemes near shock locations. Since PINNs can perform inconsistently, depending on the random initialization of network parameters at the start of the training, we analyze the accuracy over 12 training runs with different random initialization seeds. The following plots highlight the mean prediction over those 12 runs and the largest and smallest values (i.e. the spread of the predictions). The usual quantities like standard deviation and quantiles are not calculated due to the limited number of 12 training runs. As an integral indicator of prediction accuracy we consider the shock angle \(\delta\) (see Fig. 2). Fig. 8 shows an overview of predicted shock angles for the entire parameter space. Overall the error of the shock angle is lower than one degree. The errors are larger at the lower bound of the parameter space towards \(M_{\infty}=2\). The spread of the predictions over the 4 training runs indicates that the results are generally within a one degree neighborhood of the analytical solution. Fig. 9 (a) shows how the error for the angle delta changes during the training. We see that the error in the angle does not improve significantly after phase 1 and that the spread of predicted angles in fact increases. However, Fig. 10 shows that during the second and third training phase, the shock becomes much sharper and thus approximates the expected analytical result better. This is also confirmed by the decrease in the relative density errors (see Fig. 9 (b)). Note that the final training phase 3 with LBFGS is crucial to obtain good accuracy. Fig. 9 (c) shows the prescribed viscosity value \(\tilde{\nu}\) and the mean (over the domain) predicted viscosity \(\nu\) during the training. Contrary to the subsonic test case we can clearly see the adaptivity of viscosity and how it is only loosely coupled to the prescribed value. Early in the training we can see an adaptive increase beyond the prescribed value which is accompanied by a fast convergence during the first few thousand epochs. Then, during phase 2, the predicted viscosity is again reduced less steeply than the prescribed value which indicates that more viscosity is necessary than prescribed, to stabilize the training during the reduction phase. During phase 3 the predicted viscosity decreases more steeply. The final values are between \(\nu=10^{-5}\) and \(\nu=2\cdot 10^{-6}\) and thus higher than for the subsonic test case. The necessity for more viscosity during the training is to be expected since we are dealing with a supersonic flow that involves a shock. Compared to the previous subsonic test case, this problem should be more unstable and require more dissipation. For a quantitative comparison of relative errors with the subsonic problem, we again consider the pressure coefficient \(C_{\rm p}\), the local Mach number \(M\) and the density \(\rho\) for 20 linearly distributed Mach number values with \(M\in[2,3]\). For each parameter, the mean absolute difference to the reference solution was calculated for the entire domain. This difference was then normalized with the range of values of the reference solution for each individual quantity. The calculation of errors and uncertainties is described in more detail in Sec. C. The hyperparameters are not optimized and higher accuracies may be possible when employing hyperparameter optimization e.g. on the network shape and learning rate. Compared to the subsonic problem 3, we see slightly increased errors but within the same order of magnitude. The bounds of the error are higher, mainly due to the fact that accuracies are worse close to the lower Mach number \(M=2\), while the errors of the subsonic problem are consistently low for the entire parameter space (c.f. Sec. C). Again, the models are implemented with SMARTy [42] using the tensorflow backend and the total training time for one run on a NVIDIA A100 graphics card is about 23 hours. The prediction at 300000 points takes about 0.5 s. ## 5 Conclusion To summarize, we propose a novel physics-informed neural network training procedure to approximate parametric solutions to the stationary compressible Euler equations. Parameters are considered as additional input dimensions of the network. Furthermore, we add a dissipative term to the equations to stabilize the training process. Our proposed method locally predicts the necessary viscosity. An additional penalty loss term is used to control and reduce the viscosity during the training so that the resulting solution is non-dissipative. We obtain accurate results on a subsonic test case with a parametric Mach number and boundary shape as well as a supersonic test case with parametric Mach number. The proposed method is easy to implement and outperforms vanilla PINNs without viscosity (c.f. Appendix A) which have so far rarely been applied successfully, for more than one-dimensional forward problems governed by the Euler equations without requiring previous solution knowledge (e.g. for data, clustered points or domain decomposition based the solution). Thus, the presented method may open up new possibilities for the use of PINNs for similar inviscid problems, which were previously unsolvable, using vanilla PINNs. Compared to finite volume reference simulations, we achieve errors on the order of less than 2% for the pressure, velocity and density field, for both test-cases while using no additional data besides boundary conditions. The proposed implementation of artificial viscosity is simplistic and one can think of many ways to improve this approach. Similarly to artificial matrix-valued artificial viscosity schemes in classical CFD methods [44; 45; 46; 47], a yet to be developed matrix-valued viscosity model for \(\eta\) might reduce the influence of the dissipative term during training, while maintaining its stabilizing properties. Also, an alternative regularization scheme based on \begin{table} \begin{tabular}{l c c} \hline \hline \begin{tabular}{c} **Sec.** \\ **around Ellipse** \\ \end{tabular} & \begin{tabular}{c} **3. Parametric Flow** \\ **Shock** \\ \end{tabular} \\ \hline \(C_{\mathrm{p}}\) & \((0.23\pm 0.06)\%\) & \((0.7\pm 0.7)\%\) \\ \hline \(M\) & \((1.0\pm 0.1)\%\) & \((1.3\pm 0.9)\%\) \\ \hline \(\rho\) & \((0.33\pm 0.06)\%\) & \((0.62\pm 0.62)\%\) \\ \end{tabular} \end{table} Table 1: Comparison of relative errors for different field variables. Figure 7: Comparison of parametric PINN solution for oblique shock test case with the analytical reference solution for different Mach numbers. The absolute errors between the reference and the PINN solution are shown in Figs. (c), (g) and (k). Figs. (d), (h) and (l), show the artificial viscosity \(\eta\). an entropy criteria has been proposed for solving hyperbolic problems with PINNs which might be an additional measure to avoid unphysical results, when solving the compressible Euler equations, especially at higher Mach numbers [48; 31]. However, our initial tests indicate that this methodology is not sufficient to stabilize our analyzed problems on its own. The presented approach of parametric boundary conditions can, in theory, be extended to multiple parameters (e.g. with variable Mach number, shape and angle of attack for airfoils). Therefore, it could be applicable for tasks such as design optimization which traditionally require many solver evaluations. Whether a sufficient level of accuracy can be reached for more complex multi-parameter problems remains to be seen. An aspect of PINNs that has not been considered in this work is that higher fidelity solution data can be incorporated into the objective function as an additional loss term. This opens the possibility to directly combine PINNs with classical solvers or to even incorporate experimental data into the loss. For parametric problems, such a hybrid-data-driven approach may improve accuracy and even speed up the convergence during training. This flexibility may open up new possibilities for physics-informed reduced order modeling for higher dimensional parametric flows. An additional point of future interest is the behavior of the presented approach in the transsonic regime, where velocities exceed the speed of sound only locally. Figure 8: Mean and spread of predicted shock angles. The blue curves show the angle \(\delta\) (for the definition see Fig. 2). The green curve shows the absolute error which is the absolute difference between the two blue curves. Figure 9: Error history and artificial viscosity factor \(\nu\) during training of PINN for parametric oblique shock problem. The three phases of the applied training procedure are highlighted. ## Acknowledgements This work was supported by the Helmholtz Association's Initiative and Networking Fund on the HAICORE@FZJ partition. Figure 10: Exemplary cross-section through density field at \(M_{\infty}=2.25\) shows how shock becomes less dissipative after reducing the viscosity during the training. ## Appendix A Non-Parametric Problems To highlight the necessity and the efficacy of artificial viscosity, we consider non-parametric versions of the previously analyzed problems and compare the results with and without adaptive artificial viscosity. ### Flow around Cylinder First, we investigate the flow around a cylinder at a constant Mach number of \(M=0.2\). Again, the center of the cylinder is positioned at the origin inside the domain \(\mathbf{x}=(x,y)\in\Omega=(-1,1)\times(-1,1)\) with a radius of \(r=0.1\). Fig. 11 (c) show a numerical reference solution of the problem for a Mach number of M = 0.2. The solution was obtained using the CFD solver CODA [4]. For additional information on the calculation of reference finite volume results, see C. Similarly to before, no-flux boundary conditions are used for the cylinder wall and Dirichlet boundary conditions are enforced using Eq. (6) for the external domain boundary. A summary of the parameters within each training phase is shown in Tab. 2. For the PINN without viscosity, we train for the same number of epochs with the ADAM and LBFGS optimizer as for the model with adaptive viscosity. The learning rate for ADAM is however set to \(lr=10^{3}\) for the entirety of the ADAM training. All other hyper parameters and the training points are identical The training points for the residual loss are randomly sampled in the entire domain, using the quasi-random Halton sequence [34]. For both point sets, the same number of points are used to represent the boundary of the physical domain and the cylinder (\(N=N_{\infty}=N_{\rm ob}\)). Figs. 11 (a)-(b) show the resulting velocity fields given by the local Mach number. The training parameters correspond to phase 1 in Tab. 2. The results without adaptive viscosity shows elongated, unphysical regions of low velocity before and after the cylinder. In comparison, the model with adaptive viscosity agrees well with the reference simulation. The training with SMARTy [42] and the tensorflow backend on a single NVIDIA A100 graphics cars takes about 6 hours without viscosity and about 11 hours for the model with viscosity, due to the increased effort for calculating the loss function. ### Oblique Shock We consider the oblique shock at a incoming Mach number of \(M_{\infty}=2\). The training points for the residual loss are generated similarly to Sec. 4 with the Halton sequence inside ob the physical domain \((x,y)\in\Omega=(0,1)\times(0,1)\). Dirichlet boundary conditions are used for the left and upper boundary and no-flux wall conditions are used for the bottom boundary. No boundary condition is used on the right boundary. This exact forward problem has been solved with PINNs in [26] and cPINNs in [27]. Hence, to demonstrate the efficacy of artificial viscosity, we try to reproduce the reported results of [26] by selecting similar hyper parameters for the neural network shape (7 layers with 20 neurons) and a similar number of uniformly distributed points (5000 for the residual loss) and compare the predictions with and without the adaptive viscosity for these exact hyper parameters. Note that we use uniformly distributed and no clustered training points because we do not want to assume any previous knowledge about the solution and the shock angle. We do however increase the boundary point density in the bottom left corner at the shock origin as schematically depicted in Fig. 2. Also the number of points on the boundaries overall increased to 2000, compared to 300 points in [26]. Again, both PINN models with and without adaptive viscosity are trained for the same number of ADAM epochs (phase 1 and 2 combined for the viscous PINN) and LBFGS epochs. Fig. A.12 shows the resulting density fields. We are unable to obtain similar results for the inviscid PINN as shown in [26] even though the number of boundary points and the number of ADAM epochs have been increased. We have also searched for better hyper parameters and even employed adaptive activation functions and dynamic loss term Figure A.11: Comparison of PINN predictions for the local Mach number \(M\) with and without artificial viscosity and the reference finite volume simulation. weighting but were still unable to obtain qualitatively improved results. Nevertheless, even when compared to the shown results in [26], we obtain highly improved results using the proposed adaptive viscosity during training. The shock is much sharper and less dissipative, even without clustered training points. Figure A.12: Comparison of results for the non-parametric oblique shock problem at \(M_{\infty}=2\). The local Mach number \(M\) is shown for training runs with (Fig. (b)) and without (Fig. (a)) adaptive artificial viscosity in comparison to the reference finite volume result (c). The hyper parameters used for (a) and (b) are the same. A search for better hyper parameters for (a) has not lead to significant improvements even when employing dynamic loss term weighting [18; 19; 41] or adaptive activation functions [40]. ## Appendix B Training Parameters \begin{table} \begin{tabular}{l c c} \hline **Sec.** & **Appendix A.2** & **4. Parametric** \\ & **Oblique Shock** & **Oblique Shock** \\ \hline hidden layers & 7 & 7 \\ \hline neurons/layer & 20 & 30 \\ \hline activation & tanh & tanh \\ \hline loss weights & \(\beta=1\) & \(\beta=1\) \\ & \(\gamma=5\) & \(\gamma=5\) \\ \hline phase 1 & Adam & Adam \\ & \(\tilde{\nu}=7.5\cdot 10^{-4}\) & \(\tilde{\nu}=7.5\cdot 10^{-4}\) \\ & \(N=5000\) & \(N=100000\) \\ & \(N_{\text{batch}}=N\) & \(N_{\text{batch}}=10000\) \\ & 12000 epochs w. \(lr=10^{-3}\) & 7500 epochs w. \(lr=5\cdot 10^{-4}\) \\ & 18000 epochs w. \(lr=10^{-4}\) & 7500 epochs w. \(lr=10^{-4}\) \\ & & 15000 epochs w. \(lr=2\cdot 10^{-5}\) \\ \hline & Adam & Adam \\ & reduce \(\tilde{\nu}=7.5\cdot 10^{-4}\) to \(\nu_{0}=0\) & reduce \(\tilde{\nu}=7.5\cdot 10^{-4}\) to \(\nu_{0}=0\) \\ & \(N=5000\) & \(N=100000\) \\ phase 2 & \(N_{\text{batch}}=N\) & \(N_{\text{batch}}=10000\) \\ & \(M_{\text{red}}=5000\) & \(M_{\text{red}}=10000\) \\ & \(k=1\) & \(k=4\) \\ & 20000 epochs w. \(lr=2\cdot 10^{-5}\) & 17500 epochs w. \(lr=2\cdot 10^{-5}\) \\ \hline & LBFGS & LBFGS \\ & \(\tilde{\nu}=0\) & \(\tilde{\nu}=0\) \\ phase 3 & \(N=5000\) & \(N=20000\) \\ & 10000 epochs & 30000 epochs \\ \hline \end{tabular} \end{table} Table B.3: Summary of PINN parameters for oblique shock problem. ## Appendix C Details on Reference Simulations, Calculation of Errors and Shock Angles ### Parametric Flow around Ellipse All reference simulations for the ellipse were calculated using CODA [4; 49]. CODA is the computational fluid dynamics (CFD) software being developed as part of a collaboration between the French Aerospace Lab ONERA, the German Aerospace Center (DLR), Airbus, and their European research partners. CODA is jointly owned by ONERA, DLR and Airbus. We use a structured O-type grid with 200 surface nodes and 13200 cells. The residuals are converged to an order of \(10^{-12}\). For a quantitative evaluation of the accuracy of the parametric PINN in Sec. 3, we compare the solutions to 100 reference finite volume simulations in the parameter space \((M,a)\in(0.2,0.4)\times(0.1,0.2)\). The parameter sets sampled using the Halton sequence [34]. Fig. 3 shows the parameter values and the absolute errors for the density field. For each parameter set, the errors are calculated for each field variable separately, by taking the mean of the absolute difference over a small rectangle \((x,y)\in(-0.5,0.5)\times(-0.5,0.5)\) near the ellipse. The figure then depicts the mean error over all training runs. Overall the errors are all on the same order of magnitude and we see no significant outliers in the entire parameter space. The results are less accurate towards the bounds of the parameter space. For the calculation of the relative errors in Tab. 1 and Fig. 6 the previously calculated absolute errors are normalized with the range of the respective field variable, taken from the reference simulations. Then the mean over the parameter sets is taken. For Tab. 1 all 100 parameter sets and for Fig. 6 a subset of 10 parameter sets is used. Finally, the mean over all 12 training runs is taken. The uncertainties in 1 take the variance in accuracy at different locations in the domain, different parameter sets and the confidence with respect to the different simulation runs into account. locations in the domain, different parameter sets and the confidence with respect to the different simulation runs into account. The predicted shock angles in Fig. 8 and Fig. 9 are determined with a root finding algorithm which looks for the mean reference value of the density before and after the shock (\((\rho_{1}+\rho_{2})/2\)). This value is searched in the PINN prediction field on a vertical line at \(x=0.95\). This method has worked sufficiently fast and accurate for our analysis with errors \(\ll 1^{\circ}\). The shock location is very consistent between the different field variables. Therefore, it is sufficient to only calculate the angle based on the density prediction.
2304.09975
Solving the Kidney-Exchange Problem via Graph Neural Networks with No Supervision
This paper introduces a new learning-based approach for approximately solving the Kidney-Exchange Problem (KEP), an NP-hard problem on graphs. The problem consists of, given a pool of kidney donors and patients waiting for kidney donations, optimally selecting a set of donations to optimize the quantity and quality of transplants performed while respecting a set of constraints about the arrangement of these donations. The proposed technique consists of two main steps: the first is a Graph Neural Network (GNN) trained without supervision; the second is a deterministic non-learned search heuristic that uses the output of the GNN to find paths and cycles. To allow for comparisons, we also implemented and tested an exact solution method using integer programming, two greedy search heuristics without the machine learning module, and the GNN alone without a heuristic. We analyze and compare the methods and conclude that the learning-based two-stage approach is the best solution quality, outputting approximate solutions on average 1.1 times more valuable than the ones from the deterministic heuristic alone.
Pedro Foletto Pimenta, Pedro H. C. Avelar, Luis C. Lamb
2023-04-19T21:25:34Z
http://arxiv.org/abs/2304.09975v1
# Solving the Kidney-Exchange Problem via Graph Neural Networks with No Supervision ###### Abstract This paper introduces a new learning-based approach for approximately solving the Kidney-Exchange Problem (KEP), an NP-hard problem on graphs. The problem consists of, given a pool of kidney donors and patients waiting for kidney donations, optimally selecting a set of donations to optimize the quantity and quality of transplants performed while respecting a set of constraints about the arrangement of these donations. The proposed technique consists of two main steps: the first is a Graph Neural Network (GNN) trained without supervision; the second is a deterministic non-learned search heuristic that uses the output of the GNN to find a valid solution. To allow for comparisons, we also implemented and tested an exact solution method using integer programming, two greedy search heuristics without the machine learning module, and the GNN alone without a heuristic. We analyze and compare the methods and conclude that the learning-based two-stage approach is the best solution quality, outputting approximate solutions on average 1.1 times more valuable than the ones from the deterministic heuristic alone. Kidney Exchange Problem; Graph Neural Networks; Optimization, Machine Learning, Deep Learning, Graph Theory. ## I Introduction This study addresses machine learning approaches for the approximate solving of the Kidney Exchange Problem (KEP), an NP-Hard problem on graphs [1, 2]. This problem consists of, given a pool of kidney donors and patients waiting for kidney donations, optimally selecting a set of donations to optimize the quantity and quality of transplants performed while still respecting a set of constraints about the arrangement of these donations. Thus, this work's main objective is to answer the following question: **Can the Kidney Exchange problem be better approximately solved with the help of machine learning?** If positive, we want to evaluate the feasibility of utilizing such an approach in terms of the quality of the solutions it provides. Further, we are also interested in assessing how viable would such a method be in terms of computational time. Additionally, one hopes that, by answering these questions, we may also better understand the limitations of the employed machine learning methods for this problem and the potential future research directions for solving the KEP and other optimization problems in graphs. ### _On Kidney Exchanges_ Kidney disease affects millions of people worldwide, and the two available treatment options for end-stage kidney disease are dialysis and kidney transplantation [3]. Transplantation is the preferred treatment for the most severe forms of kidney disease [1] because it is cheaper and offers a better quality of life and better life expectancy [4]. The source of the kidney can be either a cadaver or a live donor, as the human body has two kidneys, and often only one suffices. The compatibility of a transplant between a donor and a recipient is determined by a number of different factors, such as the blood-group compatibility, tissue-type compatibility, the ages and general health of the donor and the recipient, the size of the donor's kidney, and many others [3]. The lower the compatibility between a donor and a patient, the lower the chance of kidney transplant success between them. In the last decades, there have started to be _paired kidney exchanges_, which are cycles involving donor-patient pairs such that each donor cannot give a kidney to their intended recipient because of some incompatibility. However, each patient can receive a kidney from a donor from another pair [1]. These cycles were first performed with only two donor-patient pair nodes, but later longer cycles of kidney exchanges were performed. Another possibility of an exchange scheme is to create exchange chains that begin with a donation of an altruistic or cadaveric kidney donor, followed by chained donations of patient-donor pairs, and then finish with a donation either to a patient with or without an associated donor. In this study, the donation chains are also referred to as _paths_, a term often used for describing sequences of connected nodes in graph problems. To find the best possible allocation, i.e., the optimal solution to the problem, considering a set of donors, patients, and patient-donor pairs, a mix of both cycles and chains can be selected as long as the cycles and paths do not intersect with each other. These cycles and chains could have unlimited size. In real life, however, there is a practical limit to the size of the paired kidney exchange cycles and chains: The kidney donation surgeries in a chain often must be done simultaneously to ensure every patient receives a kidney before her associated donor donates her kidney. However, organizing many simultaneous surgeries is logistically complex and sometimes impractical or even impossible. Even if they do not have to be done simultaneously, it is generally required at least that every patient-donor pair receive a kidney before they give a kidney. Furthermore, numerous other logistical difficulties arise when dealing with longer cycles and chains, which makes it highly desirable or sometimes even necessary that these donation cycles and chains have limited size. The longest kidney transplant chain successfully performed had a size of 35 and happened between 6 January and 17 June 2015 in the USA [5], although, in most situations, the maximum reasonable size is considerably smaller. ### _The Kidney Exchange Problem_ The Kidney Exchange Problem (KEP) was first mathematically formalized by Roth et al. in [1], then slightly updated in various ways in subsequent works. A summary of the variations found in the literature and models and techniques currently employed to solve them can be found at [6]. In the formalization used in the study, each instance of the KEP is represented by a directed weighted graph \(G=\{V,E\}\). Each patient, donor, and patient-donor pair is mapped to a graph node; they will be referred to as patient (P) nodes, non-directed (or altruistic) donor (NDD) nodes, and patient-donor pair (PDP) nodes. The set of nodes \(V\) is thus accordingly partitioned into sets \(P\), \(NDD\) and \(PDP\). The graph's edges represent donation compatibility: an edge from node A to node B represents that a kidney donation in this direction is possible; the edge weight encodes the donor's compatibility with the recipient. Solving a KEP instance means optimally selecting a set of cycles and chains to optimize the transplants performed. This optimally includes maximizing the quantity and quality of the transplants, which is encoded in the edge weights. The solution must also respect a set of constraints. Each node may participate at most in one transplant as a donor and another as a receiver. Also, PDP nodes can only donate a kidney if they receive one, although they can receive it without donating. Nodes of type P can only receive donations, and NDD nodes can only donate. The problem is then described as follows: "_Given a list of kidney needing patients, kidney donors, and patient-donor pairs, and a compatibility index between each possible donor and receiver, what is the best possible selection of donations that can be performed so that the total quantity of transplants, weighted by the compatibility indexes, is maximized, while still respecting a given size limit to the kidney exchange cycles and chains in the solution?_" Our KEP formalization is represented in the set of equations below, inspired on the so-called Recursive Algorithm formulation described by [2]. We use a binary variable \(y_{e}\) for each edge \(e\in E\), that indicates if the edge is part of the solution or not, as well as auxiliary variables flow in \(f_{v}^{i}\) and flow out \(f_{v}^{o}\) for each node \(v\in V\), which represents the node's number of incoming and outcoming edges contained in the solution, and are defined at Equations 9 and 10. \(\mathcal{C}\) represents the set of existing cycles and paths in graph, where \(C\in\mathcal{C}\) is a collection of edges, i.e. \(C\subset E\). \(\mathcal{C}_{k}\) is a subset of \(\mathcal{C}\) (i.e. \(\mathcal{C}_{k}\subset\mathcal{C}\)) containing the cycles and paths that use \(k\) or fewer edges. \[\max\sum_{e\in E}w_{e}y_{e} \tag{1}\] \[\mathrm{s.\,t.}\quad\sum_{e\in\mathcal{N}_{in}(v)}y_{e}=f_{v}^{i}\quad\ v\in V \tag{2}\] \[\sum_{e\in\mathcal{N}_{in}(v)}y_{e}=f_{v}^{o}\quad\ v\in V \tag{3}\] \[f_{v}^{o}\leq f_{v}^{i}\leq 1\quad\ v\in PDP \tag{4}\] \[f_{v}^{o}\leq 1\quad\ v\in NDD \tag{5}\] \[f_{v}^{i}\leq 1\quad\ v\in P \tag{6}\] \[\sum_{e\in C}y_{e}\leq|C|-1\quad\ C\in\mathcal{C}\setminus\mathcal{C}_{k} \tag{7}\] \[y_{e}\in\{0,1\}\quad\ e\in E \tag{8}\] \[f_{v}^{i}=\sum_{e\in\mathcal{N}_{in}(v)}y_{e}\quad\ v\in V \tag{9}\] \[f_{v}^{o}=\sum_{e\in\mathcal{N}_{out}(v)}y_{e}\quad\ v\in V \tag{10}\] \[\mathcal{N}_{in}(v)=\{e\forall e\in E,e=(v^{\prime},v)\}\] \[\mathcal{N}_{out}(v)=\{e\forall e\in E,e=(v,v^{\prime})\}\] The constraints ensure the result is a valid solution for KEP: the first two (Eq. 2 and Eq. 3) are necessary for the use of the flow in and flow out variables, the third one (Eq. 4) controls the flow in and flow out of the PDP nodes, the fourth and fifth ones (Eq. 5 and Eq. 6) do the same but for NDD nodes and P nodes, respectively, the sixth one (Eq. 7) prohibits cycles or paths with length longer than a given limit \(k\), and the seventh one (Eq. 8) defines the domain of the \(\mathbf{y}\) variable. The objective (defined at Expression 1) is to maximize the number of edges in the solution \(y\), weighted by the associated edge weights \(w\), while still respecting the KEP constraints (Equations 4, 5, 6, 7, and 8). It has been proven that this problem is NP-Hard [7], although it can become polynomial-time solvable if some of the constraints are relaxed, such as limiting the exchange cycles and chains length to 2, or removing the length restriction entirely. ## II Machine Learning Methods for Optimization Problems in Graphs In the last few years, many machine learning-based approaches that effectively solve several different optimization problems in graphs have been proposed, although none of them designed for solving KEP. Graph optimization problems already solved with the help of machine learning include the Set Covering Problem [8], Graph Colouring [9, 10], Minimum Vertex Cover [11, 12], Maximum Cut [13], Graph Partitioning [14], Maximum Independent Set [15], Maximum Common Subgraph [16], and the Travelling Salesperson Problem (also called the travelling salesman problem or TSP), one of the most famous NP-hard problems, often used to represent the class, and some variants of it [17, 18, 19, 20, 21, 22]. In 2015, the authors of [20] presented a new type of neural network called Pointer Networks, designed to learn how to reorder the elements of an input sequence; they validated the method by using it to solve 3 problems, including the TSP. In 2016, researchers presented in [23] a framework for combinatorial optimization problems using neural networks and reinforcement learning; the work focused on the TSP, which is a graph problem, but the approach was designed to work with any combinatorial optimization problem. In 2017, the authors of [13] proposed the utilization of a combination of graph representation learning and reinforcement learning to solve graph optimization problems; they showed that their proposed approach effectively learns to solve at least three of those problems: Minimum Vertex Cover, Maximum Cut, and TSP. In 2018, the decision variant of the TSP, called Decision Traveling Salesman Problem (DTSP), which is to decide if a given TSP instance admits a Hamiltonian route with a cost no greater than a given threshold C, and is also NP-Hard, was solved in [19] with a GNN. In 2019, the authors of [17] tried to solve the TSP using a two stage technique that is very similar to the one presented in this study (described at section IV-C2 and illustrated at Figure 1): firstly, a GNN processes the input graph and create scores for each edge of the graph; then, a non-learned search heuristic, which in this case was beam search, uses these scores to construct a solution. There have been other approaches that use similar techniques: in [24] the authors review graph learning methods for solving CO problems, with a focus on two-stage techniques, where the first is based on graph representation learning, which embeds the input graph into low-dimension vectors, and the second uses the embeddings learned in the first stage; [25] surveys the use of GNNs as a model of neural-symbolic computing and their applications, which includes combinatorial optimization problems; [18] unifies and refines several of such two stage techniques for neural combinatorial optimization, and test it on the TSP. ## III Dataset Deep learning methods such as GNNs require lots of data; usually, many thousands of instances, or even millions, depending on the problem and the size of the model, are necessary for the models to converge to a decent behaviour. With insufficient data, the model is very prone to overfitting, or sometimes may not even learn anything at all. Medical data, however, is very scarse, and rarely available at this quantity. This happens for two main reasons. Firstly, a major problem with healthcare data is its sensitivity: as a lot of it is confidential information about the patients, it is usually highly protected and as a rule cannot be used without special consent, be it from the patients or at least from the health institute that owns the data. Furthermore, there are a limited number of medical cases of each given situation registered; although it would be useful to have a KEP dataset with millions of instances, this situation has not happened that many times, and not necessarily all of them have been registered digitally. Due to the scarcity of the data, and considering that to train a machine learning model it usually takes at least tens of thousands of examples, the datasets were generated artificially. Three separate datasets were generated: the _train dataset_, with 10 thousand instances for the training of the model; the _validation dataset_ with 100 instances, used for validation step during the training; and the _test dataset_, with 10 thousand instances, used to evaluate the performance of each one of the employed methods. This number of instances for the validation dataset was chosen because it was sufficiently big so that still kept roughly the same properties as the train and test datasets, but small enough that the validation does not slow down the training too much. To generate each instance, first 300 separated nodes are created, and then 5500 edges are added sequentially linking random nodes, while still guaranteeing that no two edges connect the same two nodes in the same direction. The weight value of each edge is sampled from an uniform distribution of values between 0 and 1. To choose the number of nodes and edges of the KEP generated instances, the instances used for benchmarking in [2] were used as reference. Considering the 25 instances presented in the Table S3, which they call "difficult" real-data instances, the average number of nodes on a KEP instance is 265.84, and the average number of edges is 5695.92. Thus, the values for the number of nodes and number of edges chosen were 300 and 5500, respectively. The proportion of the types of nodes was also chosen to be similar to the instances: roughly 90% of the nodes are PDP nodes, 5% are NDD nodes, and 5% are P nodes. To keep track of the instances, an unique ID was assigned to each. For this, the Weisfeiler Lehman graph hash [26] was used, which guarantees that non-isomorphic graphs will get different hashes; it also considers node and edge features in its computation, thus differentiating even between graphs which have the same structure but different edge weight values. ## IV Methods We classified the methods for solving the KEP in 3 categories: integer programming methods, non-learnable heuristic methods, and learnable heuristic methods. All of them use the same input information, which is a KEP instance, and return the solution in the same format, which is a binary label for each edge, indicating if it is in the solution or not. All of them are evaluated on the test dataset, with the exception of the integer programming method, as later explained in Section V, but only the learned heuristics use the training dataset, during their training phase. ### _Integer Programming_ To obtain the analytical solution, i.e. the optimal solution, the formulation presented in Subsection I-B was implemented using the PyCSP3 Python library [27]. There are other integer programming formulations for KEP, including two presented in [2], as well as others in [28, 7] and [29]. This formulation was chosen because it is the most straightforward one. ### _Non-Learnable Heuristics_ To evaluate the implemented methods that use machine learning, we decided to compare them to non-learnable heuristics, i.e. heuristic methods that do not use learning techniques. This section aims to describe these non-learnable heuristic methods. To the best of our knowledge, however, there are no canonical heuristics for the KEP. For this reason, we implemented two search heuristics, which are described below. #### Iv-B1 Greedy Paths This algorithm greedily selects paths that start on NDD nodes and goes through PDP or P nodes one by one until there is no more nodes to be selected, or until a P node is reached. It starts by selecting the edge with the highest weight considering only the subset of edges that have an NDD node as source. Then, considering only the edges that come from the previous node, it follows by selecting always the next edge with the highest weight, until there are no more available edges left that would continue the path. After a path has been added to the solution, the edges connected to nodes of this path are masked, and Greedy Paths repeats the process until no more NDD nodes with valid outgoing edges are available. This algorithm is described at Algorithm 1. ``` procedureGreedy-Paths(\(G=(N,E),k\)) \(\mathrm{paths}\leftarrow[]\) while\(|\mathrm{GP}(G,k)|>0\)do \(\mathrm{paths}\leftarrow\mathrm{GP}(G,k)\) \(\mathrm{paths}\leftarrow\mathrm{paths}\oplus[\mathrm{path}]\) \(G\leftarrow(N\setminus\{n\ \forall\ n\in\mathrm{paths}\},E\setminus\{e\ \forall\ e\in E,src(e)=n\lor tgt(e)=n\})\) return paths procedureGP(\(G=(N,E),k\)) \(\triangleright\)Gets one Greedy Path \(E_{NDD}\leftarrow\{e\ \forall\ e\in E,src(e)\in NDD\}\) if\(|E_{NDD}|=0\)then return[] \(e_{c}\leftarrow\operatorname*{arg\,max}_{e\in E_{NDD}}w_{e}\) \(\mathrm{paths}\leftarrow[src(e_{c})]\) while\(|\mathrm{OE}(tgt(e_{c}))|>0\wedge|\mathrm{path}\,|<(k+1)\)do \(\mathrm{path}\leftarrow\mathrm{path}\oplus[tgt(e_{c})]\) \(e_{c}\leftarrow\operatorname*{arg\,max}_{e\in\mathrm{OE}(tgt(e_{c}))\setminus \bigcup_{n\in\mathrm{path}}\mathrm{IE}(n)}w_{e}\) return\(\mathrm{path}\) procedureOE(\(G=(N,E),n\)) \(\triangleright\)Outgoing Edges return\(\{e\ \forall\ e\in E,src(e)=n\}\) procedureIE(\(G=(N,E),n\)) \(\triangleright\)Incoming Edges return\(\{e\ \forall\ e\in E,tgt(e)=n\}\) ``` **Algorithm 1** Greedy-Paths #### Iv-B2 Greedy Cycles This algorithm greedily selects cycles of PDP nodes. It starts by selecting the edge with the highest weight considering only the subset of edges that have a PDP node as source and a PDP node as destination. Then, PDP nodes are greedly added to the solution in the same way as done by the Greedy Paths method until the cycle ends, or until it arrives at a node already added in the cycle, in which case the cycle is closed and the nodes before the current node are removed from the cycle. After a cycle is added to the solution, the Greedy Cycles algorithm applies a mask on the edges connected to nodes of this cycle, and then repeats the process until no more PDP nodes with valid outcoming edges are available. This algorithm is described at Algorithm 2. ``` procedureGreedy-Cycles(\(G=(N,E),k\)) \(\mathrm{cycles}\leftarrow[]\) while\(|\mathrm{GC}(G,k)|>0\)do \(\mathrm{cycle}\leftarrow\mathrm{GP}(G,k)\) \(\mathrm{cycles}\leftarrow\mathrm{cycles}\oplus[\mathrm{cycle}]\) \(G\leftarrow(N\setminus\{n\ \forall\ n\in\mathrm{cycles}\},E\setminus\{e\ \forall\ e\in E,src(e)=n\lor tgt(e)=n\})\) returncycles procedureGP(\(G=(N,E),k\)) \(\triangleright\)Gets one Greedy Cycle \(E_{PDP}\leftarrow\{e\ \forall\ e\in E,src(e)\in PDP,dst(e)\in PDP\}\) if\(|E_{PDP}|=0\)then return[] \(e_{c}\leftarrow\operatorname*{arg\,max}_{e\in E_{PDP}}w_{e}\) \(\mathrm{cycle}\leftarrow[src(e_{c})]\) while\(tgt(e_{c})\notin\mathrm{cycle}\)do if\(|\ \mathrm{OE}(tgt(e_{c}))|\leq 0\vee|\mathrm{cycle}\,|\geq k\)then return[] \(\triangleright\)Unable to close cycle (dead end) \(\mathrm{cycle}\leftarrow\operatorname*{cycle}\oplus[tgt(e_{c})]\) \(e_{c}\leftarrow\operatorname*{arg\,max}_{e\in\mathrm{OE}(tgt(e_{c}))\setminus \bigcup_{n\in\mathrm{cycle}}\mathrm{IE}(n)}w_{e}\) return\(\mathrm{cycle}\) procedureOE(\(G=(N,E),n\)) \(\triangleright\)Outgoing Edges return\(\{e\ \forall\ e\in E,src(e)=n\}\) procedureIE(\(G=(N,E),n\)) \(\triangleright\)Incoming Edges return\(\{e\ \forall\ e\in E,tgt(e)=n\}\) ``` **Algorithm 2** Greedy-Cycles ### _Learnable Heuristics_ As KEP instances are graphs, using GNNs to extract more detailed and abstract information can help in constructing an approximate solution. Therefore, GNN models were chosen as the main learning module for the machine learning methods. _GNN Architecture:_ The architecture of the GNN used in this work is the following: firstly, there is a message passing phase, where the original node features are passed through a PNA layer [30], and then through two consecutive GATv2 layers [31]; after each message passing layer, a ReLU activation function is applied, followed by a dropout regularization; next, the node features are passed through a fully connected feed forward neural network, followed by another ReLU activation function; then, the edge features are constructed by concatenating the original input edge features with the node features of the origin and destination nodes associated to each edge; these edge features are then passed through a fully connected feed forward neural network, which outputs a score for each edge; at this point, a skip connection adds the original edge weights to the edge scores; finally, a node-wise softmax operation, which is described below, is applied so as to normalize these scores in relation to the scores of other edges that share the same source node. In order to make information flow not only in the original direction of the original edges, each message passing layer is accompanied by an associated layer, which we call _counter edge layer_, that is exactly similar, but with different learned weights, and with the difference that the information is propagated in the opposite direction, i.e. flowing from the destination node to the origin node. Each time message layers are executed, the output of the original and of the counter edge layers is concatenated before being passed to the next layers. #### KEP Unsupervised Loss This loss function was designed to capture, without the need for the exact solution as a label or any other supervision, the essence of what we are trying to maximize: the sum of weights of edges that are in the predicted solution. It is defined as the log of the sum of weights of all edges of the input instance over the sum of weights of edges that are in the predicted solution, weighted by the scores predicted by the GNN. This loss function is presented in Formula 11, where \(w\) represents the vector of edge weights, \(pred\) represents the vector of predicted classes (which indicates if each edge is contained in the solution or not), and \(s\) represents the vector of scores attributed by the GNN for each edge. \[KEP\_Loss\left(w,pred,s\right)=\log\frac{\sum_{e\in E}w_{e}}{\sum_{e\in E}w_{e }pred_{e}s_{e}} \tag{11}\] #### Loss Constraint Regularization In order to integrate information about the KEP flow constraints (Eq. 4, Eq. 5 and Eq. 6) into the learning of the model, a loss regularization function was developed. It aims to model the restriction that each node must have at maximum one single outcoming edge and one incoming edge that are part of the solution. It is defined as the log of the division between the total quantity of edges in the solution and the number of unique nodes that appear in the solution as a origin/destination node. This makes it so that the regularization term value is proportional to the number of invalid edges in the solution, i.e. the total quantity in the graph of extra edges for each source/destination node. This function can then be added to the unsupervised loss (described in the subsection above) by summing their output values, weighted by coefficients, which become new hyper-parameters of the training. #### Node-wise Softmax The node-wise softmax operation is the application of an independent softmax operation for each group of edges that share the same source node, as one can see in Equation 12, where \(s_{e_{(n_{i},n_{j})}}\) represents the edge score of the edge connecting node \(i\) to node \(j\). In this way, for each node we will have a probability for each outgoing edge; in KEP, these values may represent a probability distribution for the donation options of the donor for each source node. Although in this work the operation was used grouping edges by source node, with a simple change of a parameter it can group edges by groups of common destination node as well. \[\text{node-wise-softmax}(s_{e_{(n_{i},n_{j})}})=\frac{e^{-s_{e_{(n_{i},n_{j}) }}}}{\sum_{n_{k}\in\mathcal{N}(n_{i})}e^{-s_{e_{(n_{i},n_{k})}}}} \tag{12}\] To the best of our knowledge, this is the first time this operation is proposed in the literature. It is potentially useful for any edge classification task on graphs, specially when the problem involves constraints in which only one edge may be chosen per node, be it destination or origin node. These constraints are very common in optimization problems in graphs; this is the case for KEP, for example: each donor or patient-donor pair may donate at most one kidney, and each patient or patient-donor pair may receive at most one kidney. #### Iv-B1 Unconstrained GNN Model This method, referred to from now on as _Unsupervised GNN_, consists of a GNN model which receives a KEP instance and outputs, for each edge of the input instance, a score and a binary prediction, which indicates if the edge is part of the predicted solution or not. The binary prediction is made independently for each edge, and consists of a simple decision threshold. This GNN model is trained using the unsupervised loss described at subsection IV-C with the loss regularization term described at subsection IV-C. Although there is no guarantee that the solutions given by this method will be valid, the loss regularization term is used with the goal of inducing it to respect the problem constraints. #### Iv-B2 Two Stage Method Inspired by the approach used in [17] and [18], this method follows a two steps structure: firstly, the learnable step, which is a GNN, takes the KEP graph instance as an input and outputs a score for each edge; then, the non-learnable step, which is one of the heuristic methods described above in the IV-B section is executed, but using the scores given by the GNN instead of the edge weights. This process is illustrated in the diagram on Figure 1. The intuition behind this idea is that the GNN model will learn to encode in the edge score contextual information that will change the decisions of the search heuristic so as to maximize the total score of the final output solution. This GNN model is trained without supervision using loss described at subsection IV-C. There is no need to use the loss regularization term described at subsection IV-C because the second step of the method ensures that the output will be a valid solution. Two versions of the two stage method were implemented for the experiments. Both use the GNN described in subsection IV-C for the first stage, but their second stage consist of different search heuristics. One uses the Greedy Paths search heuristic described at subsection IV-B1 and is referred to later on as _GNN+GreedyPaths_. The other uses the Greedy Cycles search heuristic described at subsection IV-B2 and is referred to later on as _GNN+GreedyCycles_. ## V Experiments The main goal of the experiments was to assess the machine learning methods, and compare them to the deterministic heuristics and to the exact solution, both in terms of the quality of the solutions as well as of their operational performance, i.e. the time it takes for a solution to be calculated. The integer programming method, however, could not be measured in the same dataset because it took to long to run the solver. The objective of the Kidney Exchange Problem is to maximize the number of donations weighted by their compatibility index, i.e. their associated edge weights in the graph. Therefore, this was the main metric used to quantify the quality of each solution and to compare the different methods, and is also referred to as **score** in this study. As the operational performance of the methods was also to be compared, the total time that each method took to run per instance was also measured. Ideally, the heuristics could be compared by using the optimality gap, which is defined as the distance between the heuristic solution score and the optimal solution score. However, as the randomly generated KEP instances of 300 nodes have shown to be intractable while using the PyCSP3 solver, i.e. impossible to solve optimally in a reasonable time, the optimality gap could not be measured. For the trainable heuristics, the total training time was also measured and compared. To monitor and guide the training process, the evolution of the loss function value over the training time was also collected. Additionally, the mean score of the current model in the validation dataset was measured at each validation phase. For a fair comparison between methods, all the measurements were made in the same test dataset, which is described in section III, with the exception of the exact solution method, as explained in Section V below. ### _Solver Execution Time Analysis_ To measure how much time it takes to solve a KEP instance in relation to the input size, the following experiment was designed: first, we randomly generate 100 instances of each graph size (i.e. number of nodes), starting from 5 nodes and up to 300 nodes; then, each one is solved optimally using the integer programming method described at section IV-A. The elapsed time of each solver execution is collected for later analysis. ### _Training of the ML Models_ The training of the ML models was separated in epochs. In each epoch, we iterate through the 10 thousand instances of the train dataset, predicting, calculating the loss, and updating the GNN weights according to it. At every 500 instances, a validation phase is run, where the model is evaluated on the validation dataset and a checkpoint is saved. The chosen batch size was 1, which means that the predictions were done on one instance at a time, because it empirically seemed to be the best for the learning process. There were two machine learning models that were trained in this study: the unconstrained unsupervised GNN and the two stage method, which are described at Section IV-C. For each training process, it was measured how the loss value evolved over time in the training and in the validation datasets. ### _Evaluation of KEP Solving Methods_ In order to do a fair comparison between the different heuristic methods, all of them were evaluated by predicting the solutions of all 10 thousand instances of the test dataset. We did not set the cycles and paths size limit (parameter \(k\) in constraint represented by Eq. 7), i.e. the cycles and paths could have any length, as long as they respect the KEP constraints. We intend to assess the performance of these methods with limited cycles and paths length soon. For each prediction, it was measured the solution score, the number of edges in the solution, and the relation between the solution score (which is the sum of the edge weights of the solution edges) and the total sum of edge weights of the graph. In addition, the validity of the predicted solution was evaluated; if invalid, we measure the number of invalid edges in the solution, i.e. the number of edges that disrespect the restrictions. Furthermore, we measured the time it took for each method to solve each instance using a CPU. Then, it was measured, for each model in relation to the whole test dataset, the mean, standard deviation, and distribution for the scores and the prediction elapsed times. ## VI Results ### _Solver Time Measurements_ Figure 2 shows a box plot of the time that the solver took to optimally solve KEP instances in relation to the instance size. For that, graphs of sizes 5 to 15 (i.e. number of nodes) were used; initially, graphs with up to 300 nodes were going to be included in the analysis, but as solving graphs with 16 nodes or more would take several days to compute, they were excluded. To solve a hundred instances with 15 nodes, for instance, it took 101.2 hours in total. As we can see, the experiment results show a pattern of exponential growth of computational time in relation to the input size. The mean time it took when the graph node number was beneath 10 was always below 1.5 seconds. For instances with 15 nodes, the mean time measured was 3569.33 seconds, i.e. roughly one hour. Fig. 1: Diagram representing an overview of the _two stage method_. The GNN takes the input KEP instance and computes a score for each edge of the graph; then, a greedy heuristic such as _GreedyCycles_ or _GreedyPaths_ uses these edge scores instead of the original edge weights to build an approximate solution, which is a binary label for each edge (_edge labels_), indicating if the edge is part of the approximate solution predicted or not. Source: Author. ### _Training of the ML Models_ Figures 3, 4, and 5 show the evolution of the loss value on the training and validation datasets for the two stage methods described at Subsection IV-C2, _GNN+GreedyPaths_ and _GNN+GreedyCycles_, and for the _Unsupervised GNN_ method described at Subsection IV-C1, respectively. Figures 6, 7, and 8 show the evolution of the the mean score value for _GNN+GreedyPaths_, _GNN+GreedyCycles_, and _Unsupervised GNN_, respectively. Figure 9 shows the evolution of the standard deviation of the scores predicted on the validation dataset. than the non-learnt heuristic achieving a mean score of 228.40 on the test dataset, while _GreedyPaths_ obtained 203.79; this shows an improvement of 12% of the mean solution score with the use of the GNN. We can also see that, although the best scores achieved by each of them are very similar, the score distribution is very different: while _GreedyPaths_ outputs approximate solutions with very large range of scores, _GNN+GreedyPaths_'s approximate solutions have much more consistent scores, obtaining a decent performance throughout all instances of the dataset. ### _Methods' Computational Time_ The box plot in Figure 11 shows the comparison between the time it took for each method to solve the KEP instances of the test dataset. As we can see, all of them took less then a second. Although the difference is not large, the two basic search heuristics took less time than the GNN based methods, and _GNN+GreedyPaths_ took, on average, the most time. ## VII Analysis of Experimental Results ### _Solver Time Analysis_ Because the Kidney Exchange problem is NP Hard, the time it takes to optimally solve each instance is expected to grow exponentially as the instance size grows. Regardless, considering that in [2] real life KEP instances could be optimally solved in a reasonable time, it was expected that we would also be able to optimally solve the ones used in this study, since they have been constructed to have similar sizes to the ones used in the article. However, as described in Subsection VI-A, instances of size as small as 15 already took in average 1 hour to solve. Considering that we would want Fig. 8: Evolution of the score measured in the validation dataset for the _Unsupervised GNN_ method. Fig. 6: Evolution of the score measured in the validation dataset for the _GNN+GreedyPaths_ method. Fig. 7: Evolution of the score measured in the validation dataset for the _GNN+GreedyCycles_ method. Fig. 9: Evolution of the standard deviation of score measured in the validation dataset for the _GNN+GreedyPaths_ method. to optimally solve all 10 thousand instances of the test set in order to fairly compare to the other methods and to measure their optimality gap, this process would take an unreasonable time, estimated to be around 10 thousand hours, i.e. roughly 1.14 years. This estimate is only if the KEP instances on the test dataset had 15 nodes; for instances with 300 nodes, it would surely take an unreasonably enormous amount of time. The number of nodes of the input instance is not, however, the sole factor that determines the time it takes to optimally solve it; in a set of instances with the same number of nodes, some are "harder" than others, i.e. take more time to solve. As the instance size increases, so does the variability of the time to solve it: the minimum and maximum times measured for instances with 15 nodes were 5.17 seconds and 29779.01 seconds (i.e. roughly 8 hours); for comparison, the minimum and maximum times for instances with 5 nodes were 0.8 and 1.3 seconds. Hence, it is possible that, while some real life instances are solvable in a reasonable time, a percentage of them would take too long to solve, thus becoming intractable. There can be several reasons why the authors of [2] could compute the optimal solution of their KEP instances in much less time. First of all, they probably used a solver tool that is much more efficient than PyCSP3. In addition, the computer used may be much more powerful than the one used in this study. Also, it is important to remember that the NP-Hardness of KEP guarantees that the computational time it takes to solve the worst case scenario grows exponentially, but in practice real life instances may often have specific properties which may cause them to be either harder or easier to solve. Hence, another plausible reason is that their instances may be much easier to solve. Furthermore, the authors used a constrain relaxation technique that speeds up significantly the solving process. These set of reasons alone may not explain totally why they were able to optimally solve their KEP instances much faster than we did on our data; this may be further investigated in future work. ### _Training of the GNN model_ As we can see in Figure 3, the training of the _GNN_+_GreedyPaths_ method was successful, seen as it managed to optimize the GNN by minimizing the loss function. The training of the _GNN_+_GreedyCycles_ and _Unsupervised GNN_ methods, however, were unsuccessful, as shown by the loss curves of Figures 4 and 5, which do not decrease over time. Although at first glance at Figure 8 the _Unsupervised GNN_ model seems to achieve great scores, unfortunately all its output solutions were invalid, i.e. they did not comply to the KEP constraints. It is clear that the loss constraint regularization (described at IV-C) added to the loss function was unsuccessful in helping the model learn to comply to the KEP constraints. This highlights the necessity of having a methods that guarantee with total certainty that all its output solutions are valid. However, even though there were many manual trials with different hyperparameter combinations, it is still possible that a variation of this technique could work with a different setting, i.e. another GNN architecture, other hyperparameters, and so on. Because of the skip connection that sums the original edge weights to the predicted edge scores at the end of the GNN, the predicted solutions start off very similar to the ones made by _GreedyPaths_. Then, the changing of the GNN weights disrupts these scores, which increases the loss, but goes on to improve them, eventually arriving at a performance that is better than _GreedyPaths_. After some point (around epoch 6 in Figure 6), the learning converges to a solution, and after a while the performance starts to slowly worsen. The final model was chosen from the checkpoint with the highest score measured on the validation dataset, which was in epoch 6, step 3500. As Fig. 11: Box plot comparing the time to compute a solution on each of the 10 thousand KEP instances of the test dataset, each one with 300 nodes. The evaluated methods were two non-learnt heuristics, _GreedyCycles_ and _GreedyPaths_, their 2 stage method versions, _GNN_+_GreedyCycles_ and _GNN_+_GreedyPaths_, and _UnsupervisedGNN_, which is a GNN trained and used without an heuristic. Fig. 10: Box plot comparing the approximate solution scores obtained when each of the evaluated methods was used in the test dataset. The evaluated methods were two non-learnt heuristics, _GreedyCycles_ and _GreedyPaths_, and their 2 stage method versions, _GNN_+_GreedyCycles_ and _GNN_+_GreedyPaths_. we can see on Figure 9, at this point the model's scores on the validation also presented the lowest standard deviation, which indicates that the model's predictions were more consistent, maintaining a decent performance throughout all instances. ### _Methods' Performances_ Ideally, we would want to evaluate and compare each method by measuring their optimality gap for each instance, i.e. how far the approximate solution is from the optimal one. However, as we do not have access to the optimal solution, this was not possible. We can nevertheless estimate it roughly by examining an upper bound: each instance has 300 nodes, and each node may donate and receive at most one kidney; thus, the solution with the most edges would be contain cycles that together comprehend all nodes. As each edge weight is a value between 0 and 1, the maximum score possible is equal to 300, when all edges in the cycle have a weight of 1. Hence, an upper bound for the score is the number of nodes, which in this case is 300. This is obviously extremely unrealistic, as it assumes that all nodes are PDPs, that there are a set of cycles that links all of them, and that the solution edge weights are equal to 1 (as the edge weights are values sampled from a uniform distribution between 0 and 1, their average value is 0.5). Considering the score upper bound of 300 as a very conservative estimate for the mean optimal solution value, we can estimate that the absolute and relative optimality gap for the _GreedyPaths_ method would be 96.28 and 32%; for _GreedyCycles_, these values would be 286.29 and 95.4%; for _GNN+GreedyPaths_, 71.59 and 23.8%; for _GNN+GreedyCycles_, 299.15 and 99.7%. Hence, the improvement on the optimality gap of the _GNN+GreedyPaths_ method in relation to _GreedyPaths_ would be at least 34.4% (96.28 to 71.59), which is already a very substantial improvement. It is clear that the two methods that searched for paths performed much better than the ones that searched for cycles. There are many possible explanations for this observed behaviour. Maybe the best cycles-only solution in a KEP instance is usually much worse than the best paths-only solution. This, however, can only be verified by making comparisons to the cycles-only and paths-only exact solutions, which are unavailable. Also, the _GreedyCycles_ method is probably less efficient because it discards the path it is constructing if it does not end up closing a cycle. It also shortens the constructed cycle if it closes before the node it had begun on, which may also lead to worse performance overall. The _GreedyPaths_ method does not have these issues, as it always keeps the edges it adds to each path it constructs. We can also observe that the while the GNN module in the _GNN+GreedyPaths_ improved the performance in relation to the basic non-learnable heuristic, in _GNN+GreedyCycles_ it only worsened it. It is possible that its GNN module in _GNN+GreedyCycles_ could not learn the needed context to know if a given edge would lead to a longer and higher-valued cycle because it is too complex, and does not depend that much on the 3-neighborhood context, which is the limit of information gather in each node with the GNN architecture used, as it only has 3 message passing GNN layers. Another possible explanation is that it is way harder for a model to learn to compute edge scores that help the choices of _GreedyCycles_ because it is inherently more complex than _GreedyPaths_, i.e. it is not just a sequence of simple decisions, as it also has to keep track of the rest of the nodes of the cycle being constructed, check if it closed a cycle, and remove from the solution in construction the edges added before the node where the cycle was closed. Put simply, the more complex the second step heuristic is, the harder it is for a machine learning model to learn to help it. As explained at Section VI-C, _GNN+GreedyPaths_ approximate solutions have much more consistent scores, which suggests that it probably handle much better "hard" instances. A plausible interpretation is that the GNN module helps the subsequent greedy heuristic to avoid choosing edges that are only locally good, but lead to worse paths overall. It is able to do this because it considers information of the neighborhood context. ### _Methods' Computational Time_ The GNN computational complexity is linear, as it performs a fixed amount of computations per graph node plus another fixed amount of computations per edge. As for the heuristic methods _GreedyPaths_ and _GreedyCycles_, their computational complexity is also linear, as the worst case scenario one edge for each node will be added, one by one, into the solution; hence, it always performs a quantity of computational operations linearly proportional to the number of nodes of the input instance, at worst. The results from Subsection VI-D show that every method tested in this work took very little time to execute, with the exception of the _integer programming_ method, which took so much time that applying it to 300 nodes instances became intractable. The _GreedyPaths_ method took a bit more time than _GreedyCycles_ probably because it found better solutions overall, and consequently took more computing steps to construct each solution. The same effect may also explain the prediction time difference between _GNN+GreedyPaths_ and _GNN+GreedyCycles_. The _UnsupervisedGNN_ method took a bit less time to execute than the two step methods, which was expected because it runs the same computations, but without the second step, which is the basic search heuristic. ## VIII Conclusion and Future Work In this work, several heuristic methods with and without machine learning for approximately solving the Kidney Exchange Problem were proposed and investigated. They were tested on an artificial dataset and compared between each other and with an implementation of an exact solution method. Additionally, it was made an experiment for measuring the time it took for the exact solution method to solve an instance in relation to the instance size. The results of the evaluations and experiments were then analysed and discussed. ### _Answers to the Research Questions_ As seen from the results in subsection VII-C, the main question presented at Section I was answered: **yes, the Kidney-Exchange problem can be better approximately solved with the help of machine learning**. As for the feasibility of the ML methods, the _GNN+GreedyPaths_ method surpassed all other evaluated heuristics in terms of the quality of the solutions it provides; among all evaluated methods, it remains the one that best approximately solves the dataset instances in a reasonable time. The other ML methods evaluated in the work (_UnsupervisedGNN_ and _GNN+GreedyCycles_), however, did not achieve good results. Regarding the viability of such methods in terms of computational time, the GNN module adds an almost insignificant overhead when compared to the non-learnable heuristics. When compared to the solver running the exact solution, it is several orders of magnitude faster for instances with at least 15 nodes. The complexity of the two stage methods is linear, turning instances that were previously intractable due to their size into easily approximately solvable in a reasonable time. As for the limitations of the employed machine learning methods for this problem, it is clear that they are not simple to use, as they need to be properly trained, which is not easy to do. Although using the two stage method potentially improves considerably the performance in relation to the basic heuristics, as happened with the _GNN+GreedyPaths_ method, it also introduces several new hyperparameters which need to be adequately set in order for the method to work. Applying supervised learning turned out to be unfeasible because of the need for the exact solution to be used as edge labels. Regarding the _UnsupervisedGNN_ method, our results suggest that imposing the constraints through adding terms in a loss function is actually really hard; hence, the method never learns to output valid solutions, rendering it useless. ### _Main Contributions_ In the following list, a summary of each of the main contributions that this work provided is presented. **Learnable Heuristics for KEP:** Although the two stage approach was already used by past work [17, 18, 24], this was the first work to adapt it and apply it to KEP. Two variations of the approach were implemented: _GNN+GreedyPaths_ and _GNN+GreedyCycles_, the first one having achieved satisfactory performance. **Non-Learnable Heuristics for KEP:** Two new deterministic heuristic methods for approximately solving the Kidney Exchange Problem were introduced: _GreedyPaths_ and _GreedyCycles_. They were also evaluated in the test dataset, giving insight on their effectiveness. **Node-wise Softmax:** A variation of the softmax activation function designed to be applied to edge scores in graph problems was created and implemented. It showed to be useful for the GNN, empirically improving the its performance. The author plans to contribute to the PyTorch library with the implementation of this technique, thus making it available and easily usable by its future users. **KEP Unsupervised Loss:** A novel loss function (described at IV-C) designed for KEP was introduced. It optimizes the weighted sum of the edges in the predicted solution without the need for supervision. It was validated in the training of the _GNN+GreedyPaths_ method, as seen in Figure 3 in Section VI-B, where it lead the GNN to learn to effectively help the heuristic method construct better approximate solutions. ### _Future Directions_ **Using real data:** Use data collected by countries' or hospital's healthcare system to evaluate how the presented methods would perform in real life situations. This would also allow us to compare our proposed methods with others that were already evaluated in the same data. **Using better artificial data:** There more sophisticated methods for generating artificial KEP instances, such as the ones presented at [32] and [3]. They are still far from sufficiently similar to real data so as to substitute evaluating it. However, it would still probably give an evaluation of KEP solving methods that is closer to that of real life situations. Furthermore, training the model with these instances could also potentially lead to better results. Another possibility of generating better artificial data would be to use a graph generator model that learns to create instances similar to the real data; the Graph Variational Auto-Encoder presented at [33] and the MolGAN presented at [34] are good examples of candidate methods to be adapted for that goal. **Training the models with supervised learning:** Another direction is to develop a method that learns with supervision, evaluate it, and compare it to the other methods. For that, we would first have to obtain the optimal solutions, which would then be used as labels for the supervised training. This could be done either by improving a lot the integer programming method's speed and/or by training on much smaller instances (i.e. instances with less than 15 nodes). Another promissing variation of this idea is to use the N best solutions, and create soft labels where each edge would have a value between 0 and 1 that would indicate how often it appears in the best solutions, weighted by the quality of these solutions. **Running a GNN before every step of the greedy heuristic:** Instead of running the GNN once and then passing the edge scores to the greedy heuristic method, new node embeddings could be generated before each step of the heuristic. Although significantly costlier in terms of inference, as the GNN is executed many times per instance, this has shown good results for other graph route optimization problems [22]. This approach is called _autoregressive decoding_ and explored for solving the TSP by [18]. ## Acknowledgments This work is supported in part by the Brazilian Research Council CNPq and the CAPES Foundation - Finance Code 001.
2310.12574
A reproducible 3D convolutional neural network with dual attention module (3D-DAM) for Alzheimer's disease classification
Alzheimer's disease is one of the most common types of neurodegenerative disease, characterized by the accumulation of amyloid-beta plaque and tau tangles. Recently, deep learning approaches have shown promise in Alzheimer's disease diagnosis. In this study, we propose a reproducible model that utilizes a 3D convolutional neural network with a dual attention module for Alzheimer's disease classification. We trained the model in the ADNI database and verified the generalizability of our method in two independent datasets (AIBL and OASIS1). Our method achieved state-of-the-art classification performance, with an accuracy of 91.94% for MCI progression classification and 96.30% for Alzheimer's disease classification on the ADNI dataset. Furthermore, the model demonstrated good generalizability, achieving an accuracy of 86.37% on the AIBL dataset and 83.42% on the OASIS1 dataset. These results indicate that our proposed approach has competitive performance and generalizability when compared to recent studies in the field.
Gia Minh Hoang, Youngjoo Lee, Jae Gwan Kim
2023-10-19T08:33:23Z
http://arxiv.org/abs/2310.12574v3
A Reproducible 3D Convolutional Neural Network with Dual Attention Module (3D-Dam) for Alzheimer's Disease Classification ###### Abstract Alzheimer's disease is one of the most common types of neurodegenerative disease, characterized by the accumulation of amyloid-beta plaque and tau tangles. Recently, deep learning approaches have shown promise in Alzheimer's disease diagnosis. In this study, we propose a reproducible model that utilizes a 3D convolutional neural network with a dual attention module for Alzheimer's disease classification. We trained the model in the ADNI database and verified the generalizability of our method in two independent datasets (AIBL and OASIS1). Our method achieved state-of-the-art classification performance, with an accuracy of 91.94% for MCI progression classification and 96.30% for Alzheimer's disease classification on the ADNI dataset. Furthermore, the model demonstrated good generalizability, achieving an accuracy of 86.37% on the AIBL dataset and 83.42% on the OASIS1 dataset. These results indicate that our proposed approach has competitive performance and generalizability when compared to recent studies in the field. Alzheimer's disease, Feature extraction, Magnetic resonance imaging, Brain modeling, Deep learning ## I Introduction Alzheimer's disease is one of the most common causes of neurodegenerative disease among the elderly population. It progressively causes memory impairment and greatly affects the activities of daily living. According to the Alzheimer's Association [1], more than 6.7 million Americans aged 65 or older are living with Alzheimer's disease, and by 2060, this number could rise to nearly 13.8 million. In patients with Alzheimer's disease, the brain undergoes progressive cerebral atrophy, initially manifesting in the medial temporal lobe, followed by the hippocampus, amygdala, and para-hippocamps [2, 3]. While there is currently no effective cure for Alzheimer's disease, there are treatments available that may help manage symptoms or delay disease progression. Therefore, an accurate diagnosis of Alzheimer's disease is crucial as it enables patients to initiate preventive interventions to slow or halt the disease's progression. With the development of advanced neuroimaging techniques, brain atrophy has emerged as a potential biomarker for Alzheimer's disease diagnosis, visualized through MRI scans. However, manual diagnosis by doctors using MRI scans is time-consuming and relies on the expertise of the clinician. Therefore, there is a growing need for computer-aided approaches in Alzheimer's disease diagnosis. In recent years, various categories of computer-aided diagnostic methods have been increasingly applied to AD diagnosis. One category, known as regional feature-based methods, focuses on determining regions of interest (ROIs) associated with Alzheimer's disease. Segmentation is then performed on these regions, followed by prediction. For instance, Ahmed et al. achieved an accuracy of 90.73% and a precision of 90.17% in Alzheimer's disease classification by extracting the hippocampus region from MRI scans [4]. Similarly, Li et al. demonstrated the effective prediction of early Alzheimer's disease using the hippocampus extracted from MRI scans [5]. However, the features extracted from these regions may not capture the intricate alterations that occur in the brain. To overcome this limitation, whole brain-based methods have been employed to capture the structural changes more effectively in MRI scans. Zhang et al. achieved an accuracy of 91.3% in Alzheimer's Disease classification using self-attention CNN models [6]. Feng et al. demonstrated that whole brain-based deep learning methods outperformed other clinical biomarkers of AD [7]. Recent studies have also reported the efficacy of whole brain-based deep learning approaches not only AD-CN classification but also MCI conversion classification [8, 9, 10, 11]. In this study, we applied whole-brain MRI scans for the diagnosis of Alzheimer's disease and MCI progression. The Convolutional Block Attention Module (CBAM) was first introduced by Woo et al. in 2018 at the European Conference on Computer Vision [12]. The module included two main components: spatial attention and channel attention, which can learn 'what' and 'where' to focus in the channel and spatial axes, respectively. In our study, we applied dual attention to our convolutional neural networks to capture slice information across the channel and structural information across spatial axes, taking into consideration the 3D structure of whole brain MRI scans. In this study, we proposed the 3D Convolutional Neural Networks with Dual Attention Module (3D-DAM) for Alzheimer's disease classification using whole brain-based MRI scan. We make the following contributions. Firstly, we enhance the 3D-CNN architecture by incorporating a dual attention module, leading to improved accuracy compared to recent studies. Secondly, we demonstrate the generalizability of our model by achieving promising results on an independent dataset. Additionally, we visualize the regions that our model primarily focused on to ensure interpretability and reliability. Our findings align with previous studies, indicating that the hippocampus and temporal lobe are strong predictors of Alzheimer's disease diagnosis. ## II MATERIAL AND METHOD ### _Dataset description and image pre-processing._ In this study, the 1.5 T T1-weighted MRI images were collected from the public database of Alzheimer's Disease Neuroimaging Initiative (ADNI). The ADNI, initiated in 2003by Principal Investigator Michael W. Weiner, collected brain images and clinical assessments from thousands of participants across North America. For our study, we selected 403 Alzheimer's disease patients (AD) and 653 cognitive normal patients (CN). The Australian Imaging, Biomarker & Lifestyle Flagship Study of Ageing (AIBL) and the Open Access Series of Imaging Studies 1 (OASIS-1) were used as independent dataset to evaluate the generalizability of our method. Table I presents the demographic information of the subjects included in the study. The ADNI data have been curated and converted to the Brain Imaging Data Structure (BIDS) format following the processing pipeline of the Clinica software [13] to address data leakage concerns highlighted by previous studies [14, 15], such as incorrect data split and delayed split. The images were then pre-processed to extract more informative image features for classification. The pre-processing steps followed the t1-linear pipeline of Clinica software [13]. Firstly, bias field correction was applied using the N4ITK method [15]. Next, an affine registration was performed using the SyN algorithm from ANTs [16] to align each image to the MNI space with the ICBM 2009c nonlinear symmetric template. ### _3D Convolutional Neural Networks with Dual Attention Module (3D-DAM)._ Inspired by the Convolutional Block Attention Module (CBAM) [12], we applied a dual attention module to our 3D-CNN model to capture slice information across the channel and structural information across spatial axes. Firstly, we generate a channel attention map by examining the inter-channel relationships of features. Each feature map channel is treated as a feature detector, and the channel attention mechanism focuses on sliced information within an input MRI scan. Given an intermediate feature map F\(\text{\text{\text{\text{\text{\text{\text{e}}}}}}}\)R\(\text{\text{\text{\text{\text{e}}}}}\)R\(\text{\text{\text{\text{\text{e}}}}}\)S as input, we employ average-pooling and max-pooling operations to derive two different spatial representations of the feature map, denoted as F\({}^{\text{\text{\text{\text{\text{e}}}}}}_{\text{\text{\text{\text{\text{\text{ \text{e}}}}}}}}\) and F\({}^{\text{\text{\text{\text{\text{\text{e}}}}}}}_{\text{\text{\text{\text{ \text{\text{\text{\text{\text{\text{\text{\text{\text{\text{\text{\text{\text{\text{ \texttext{\text module is applied, followed by feature pooling using the Avg Pooling layer. Finally, a Fully Connected layer is utilized for classification. ## III Results ### _Evaluation in ADNI datasets_ The proposed architecture was implemented in Python using the PyTorch package. The implementation was carried out on a computer equipped with an Intel(R) Xeon(R) Gold 6258R CPU @ 2.70GHz with 256GB RAM, and 4x NVIDIA GeForce RTX 3090 GPUs. The network was trained using the SGD optimizer with a first momentum of 0.9 and a second momentum of 0.999. The initial learning rate was set to \(10^{6}\) and L2-Regularization value was set to \(10^{6}\). The maximum number of training epochs was set to 200, and a batch size of 16 was used at each iteration. The performances on AD classification achieved by our 3D-DAM method and the other methods on the test set from ADNI were shown in Table II. As shown in Table II, our method achieved an accuracy of 96.30%, a sensitivity of 93.76%, and a specificity of 97.95% in AD classification. Our proposed method demonstrated top-ranked performance in AD classification. The Area Under the Curve of the Receiver Operating Characteristic curve (ROC-AUC) for AD classification in the ADNI dataset was 0.98 (Fig. 2(a)). The 5-fold cross validation test accuracy results of AD classification in ADNI have been shown in Fig. 4. ### _Generalizability Evaluation using AIBL and OASIS datasets_ To investigate the generalizability of our proposed model, we conducted evaluations on two independent datasets: AIBL and OASIS1. We perform two evaluation experiments as follow. Firstly, we trained our proposed model based on the ADNI dataset and evaluated it using two independent datasets. Secondly, we reversed the training and test datasets in which we use AIBL and OASIS1 as training and ADNI as the test set. The classification performance is shown in Table III and Fig 2(b)-c. The 3D-DAM method obtained potential classification results with an accuracy of 86.3%, sensitivity of 80.2%, and specificity of 87.1% for AD classification in the AIBL dataset. For the OASIS dataset, the model trained on the ADNI dataset achieved classification results of 83.4%, 85.8%, and 82.6% in accuracy, sensitivity, and specificity respectively. The 5-fold cross validation test accuracy results of AD classification in AIBL and OASIS have been shown in Fig. 4. Furthermore, when we trained our model with the AIBL and OASIS datasets and evaluated it on the ADNI set, the classification results were 85.4%, 80.1%, and 89.5% in accuracy, sensitivity, and specificity respectively. ### _Pathological brain region by 3D-DAM model_ One of the most important tasks in computer-aided diagnosis is defining the pathological region that the model focuses on. In this study, we employed Grad-CAM to investigate the most crucial brain region of our 3D-DAM model, ensuring interpretability and reliability. Fig. 5, which depicts sagittal, coronal, and axial plane slices with attention score overlays, demonstrates the highest attention region. As shown in Fig. 5, the hippocampus, medial temporal lobe, and amygdala are three brain regions that play important roles in classifying AD and CN in our proposed model. These regions are consistent with numerous previous studies on AD diagnosis [4,20,21]. ## IV Discussion Effective and precise Alzheimer's disease classification based on computer-aid techniques is critical for early intervention to slow down the progress of the disease. With the development of medical imaging techniques, especially MRI, we could use them as an effective biomarker to detect brain atrophy in Alzheimer's disease patients. In this study, we investigated a comparative study focusing on the classification performance of the 3D convolutional neural networks with dual attention modules. Our proposed method outperformed the current SOTA MRI-based studies [17, 18, 19] on AD classification task. These results imply that the CNN model equipped with channel and spatial attention could achieve better classification performance compared with the current traditional CNN model. In our opinion, one of the possible reasons is that the dual attention mechanism could effectively capture the disease-related structural changing features in the brain. To verify that hypothesis, we visualize the brain region mostly focused on by our model using Grad-CAM. In Fig. 5, we observed that in AD vs CN classification, the 3D-DAM model focused mostly on the hippocampus, medial temporal, and amygdala regions in agreement with previous studies on AD diagnosis [4, 20, 21]. The medial temporal lobe including the hippocampus is crucial for episodic and spatial memory. The amygdala is involved with the formation of long-term declarative memory. In Alzheimer's disease, brain atrophy is first manifested in the medial temporal lobe several years before diagnosis and then closely followed by the hippocampus, and amygdala. The pathological brain region (hippocampus, temporal lobe, and amygdala) evaluated by attention scores in our model could suggest informative regions for future feature extraction to improve our proposed method by focusing on these ROIs. In addition, these brain regions could give more useful clues or information for doctors in clinical diagnosis. Application of the Deep Learning model in medical clinical is still challenging due to its difficulty in reproducibility and generalizability. To test our model generalizability, we use two independent datasets to evaluate our method. We have promising performance when evaluating AIBL and OASIS1 using the ADNI-trained model and vice versa. The evaluation result indicates the good generalization capability of our method for AD diagnosis. The Acc, Sen, and Spec of our proposed method based on ADNI are slightly higher than other datasets. The main reason is the ADNI dataset and the AIBL as well as the OASIS1 dataset are collected from distinct protocols, which could have different signal-to-noise ratios and device parameters. ## V Conclusion Inspired by the dual attention mechanism and 3D convolutional neural networks, we propose a 3D convolutional neural network with a dual attention module (3D-DAM) approach to advance computer-aided Alzheimer's disease diagnosis. Our proposed method makes three major contributions. We evaluated our proposed method on the largest Alzheimer's disease database, ADNI, and verified its generalizability on other independent datasets, namely AIBL and OASIS1. We achieved an Alzheimer's disease classification accuracy of 96.30%, a sensitivity of 93.76%, and a specificity of 97.95%. Furthermore, our proposed method demonstrated good generalizability performance in AIBL and OASIS1 datasets. The high attention scores in the hippocampus and medial temporal lobe, as revealed by an explainable AI, highlight the interpretability and reliability of our model. ## Acknowledgment This work was supported by Healthcare AI Convergence Research & Development Program through the National IT Industry Promotion Agency of Korea (NIPA) funded by the Fig 5: Visualization of the pathological brain region identified by the proposed method of AD Classification. The left panel shows the informative locations suggested by attention scores. The right panel shows the related brain region, respectively, with mark. Ministry of Science and ICT (No. S1601-20-1016); National Research Foundation of Korea (NRF-2022R1A2C3009749, 2022K1A3A1A20014975) and "GIST Research Institute (GRI) IIBR" grant funded by the GIST in 2023. ## Compliance with Ethical standards This work is a study using human subject data made available in open access by ADNI, AIBL and OASIS. Ethical approval was not required as confirmed by license attached with the open access data.
2303.03227
Parallel Hybrid Networks: an interplay between quantum and classical neural networks
Quantum neural networks represent a new machine learning paradigm that has recently attracted much attention due to its potential promise. Under certain conditions, these models approximate the distribution of their dataset with a truncated Fourier series. The trigonometric nature of this fit could result in angle-embedded quantum neural networks struggling to fit the non-harmonic features in a given dataset. Moreover, the interpretability of neural networks remains a challenge. In this work, we introduce a new, interpretable class of hybrid quantum neural networks that pass the inputs of the dataset in parallel to 1) a classical multi-layered perceptron and 2) a variational quantum circuit, and then the outputs of the two are linearly combined. We observe that the quantum neural network creates a smooth sinusoidal foundation base on the training set, and then the classical perceptrons fill the non-harmonic gaps in the landscape. We demonstrate this claim on two synthetic datasets sampled from periodic distributions with added protrusions as noise. The training results indicate that the parallel hybrid network architecture could improve the solution optimality on periodic datasets with additional noise.
Mo Kordzanganeh, Daria Kosichkina, Alexey Melnikov
2023-03-06T15:45:28Z
http://arxiv.org/abs/2303.03227v2
# Parallel Hybrid Networks: ###### Abstract Quantum neural networks represent a new machine learning paradigm that has recently attracted much attention due to its potential promise. Under certain conditions, these models approximate the distribution of their dataset with a truncated Fourier series. The trigonometric nature of this fit could result in angle-embedded quantum neural networks struggling to fit the non-harmonic features in a given dataset. Moreover, the interpretability of neural networks remains a challenge. In this work, we introduce a new, interpretable class of hybrid quantum neural networks that pass the inputs of the dataset in parallel to 1) a classical multi-layered perceptron and 2) a variational quantum circuit, and then the outputs of the two are linearly combined. We observe that the quantum neural network creates a smooth sinusoidal foundation base on the training set, and then the classical perceptrons fill the non-harmonic gaps in the landscape. We demonstrate this claim on two synthetic datasets sampled from periodic distributions with added protrusions as noise. The training results indicate that the parallel hybrid network architecture could improve the solution optimality on periodic datasets with additional noise. ## I Introduction Machine learning and quantum computing have become attractive research areas in recent years. The quest for an efficient quantum neural network (QNN) has dominated the cross-section of these two technologies. Many suggestions have been made for the potential inner workings of a classically-intractable quantum machine learning model [1; 2], but theoretical and hardware limitations could prove challenging to implement. The noise-free barren plateau problem [3] or the curse of dimensionality [4] are examples of the theoretical challenges with QNNs. At the same time, the hardware limitations point to the industry limits on the accuracy, and the number of qubits [5; 6]. Therefore, contemporary practical use of quantum technologies in machine learning should come from complementary quantum-classical architectures, called hybrid quantum neural networks (HQNN), that employ relatively small, realisable quantum circuits and classical multi-layered perceptrons (MLP) where the two work in tandem. In [7; 8; 9; 10], we explored the applicability and performance of sequential HQNNs, where MLPs and QNNs are connected in series, passing the information from one network to another. The sequential HQNNs could introduce information bottlenecks in the representational power of the model, which could limit the expressivity of the network. This work explores the theoretical basis of parallel HQNNs, where variational quantum circuits (VQC) and MLPs process information in parallel. The approach is based on the universality theorems from two sources: 1) MLPs can produce non-harmonic functions [11] and 2) QNNs fit smooth truncated Fourier series on the training data [12]. This work was inspired by the Fourier neural operator introduced by Ref. [13]. In Sec II, we review the theoretical foundations of MLP and VQCs, and in Sec III, we introduce the design and experimental results of PHN. In Sec III.2, we address the potential problem of component primacy in training PHNs, where either the VQC or the MLP could dominate the training, and propose a remedy to it. Finally, in Sec IV, we summarise our findings and discuss future directions. ## II Theoretical foundation In this study, we concentrate on solving a supervised regression problem using a dataset \((\mathbf{x}_{i},y_{i})\), where \(\mathbf{x}_{i}\in\mathcal{X}\) is a feature vector and \(y_{i}\in\mathcal{Y}\) is the label. Our objective is to discover a function \(f(\mathbf{x})\) that can approximate the labels \(y\) of out-of-sample features. To achieve this, we create a machine learning model with parameters \(\theta\) to create the functionality, \(f\theta(\mathbf{x})\). We adjust these parameters according to the training sample to maximise the probability of obtaining the correct label for a given feature. The general functionality \(f\) is a machine learning architecture, while a specific realisation of its parameters, \(\theta\), is a machine learning model. In the subsequent sections, we will explore two well-known architectures and then use that theoretical foundation to justify the PHN architecture in Sec III. ### Multi-layered perceptrons MLPs constitute a large class of successful machine learning architectures. They are directional graphs whose nodes are ordered in one-dimensional layers which take input from the previous layer and provide the next layer with their outputs. In the case of fully connected MLPs (FCN), all neurons of each layer feed information to all the neurons in their immediate front neighbourhood. Each edge of the graph has an associated multiplicative factor (weight), and each neuron has an associated additive quantity (bias), which together form the parameters of the MLP. The first neural layer is called the input layer, and the last is the logits. Ref. [14] provides a comprehensive overview of neural networks and their properties. Ref. [15] showed that MLPs are asymptotically universal approximators whose fit on the training data becomes perfect as the numbers of neurons in the intermediate neural layers approach infinity. Moreover, [16; 11] proved this using a novel graphical method that showed a fully-connected network with a single intermediate neural layer can approximate any function by fitting a superposition of rectangular waves. To utilise this graph as a machine learning architecture, we could encode the features of a data point taken from the sample, \(\mathbf{x}_{i}\), onto the input layer and then propagate their values through the graph by multiplying their values by the weights of the architecture \(\mathbf{w}\) and adding the biases \(\mathbf{b}\) \[h_{i}=\sigma(w_{i,j}^{(0)}x_{j}+b_{i}), \tag{1}\] where \(\sigma\) is known as the activation function1, \(h_{i}\) indicates the values of the consecutive neural layer, and Einstein's summation notation is implied. The propagation process can be passed along to the entire graph until we arrive at the terminal nodes (in this case, for a single label, we require a single terminal node). The terminal node is the output of the function and is, therefore, the approximation of the model to the label associated with the input features. We can then employ an optimisation strategy such as the stochastic gradient descent [17] to improve this approximation by adjusting the weights and biases. Footnote 1: In this work, the particular functionality of the activation function is not material, and for simplicity, we take it to be the sigmoid function everywhere, \(\sigma(t)=\frac{1}{1+e^{-t}}\), and otherwise only where clearly stated. ### Variational quantum circuits Variational quantum circuits (VQC) employ variational group rotations to create a machine learning architecture on a quantum computer [18; 19; 20; 21]. To construct a VQC, one could start by creating a quantum node of several qubits in the ground state. Then, a series of variational and fixed quantum gates can be applied to the circuit. The variational gates could include the Pauli rotation gates, which require single-qubit time evolution Hamiltonians of the respective Pauli gate. The fixed quantum gates might consist of the controlled-NOT (CNOT) and the Hadamard (H) gates. We split the variational gates into embedding, and trainable gates, which encode the features, \(\mathbf{x}\), and act as model parameters, \(\theta\). At the end of the circuit, we measure the qubits in a specified basis, such as the Pauli bases, and obtain either a 0 or a 1. After many iterations of the circuit, we can find the likelihood of getting a 0 over 1, and by taking the average, we can obtain the expectation value of the circuit. By the Born rule [22], we can find this probability by taking the expectation of the measurement matrix, \(M\), and then using it as the output of our model: \[f(\mathbf{x},\theta)=\left\langle\psi(\mathbf{x},\theta)\right|M\left|\psi( \mathbf{x},\theta)\right\rangle, \tag{2}\] where \(\left|\psi(\mathbf{x},\theta)\right\rangle\) denotes the state of the quantum circuit before the measurement. We can improve this approximation to the labels by optimising the parameters of the VQC, \(\theta\). [12] proved that VQCs are also universal approximators, and the way they work is by fitting a truncated Fourier series over the samples: \[f(x)=\sum_{k=-L}^{L}c_{k}e^{ikx}, \tag{3}\] where L is the highest degree Fourier term expressible by the VQC. ## III Results - parallel hybrid networks We split the HQNN hybrid interfaces into two categories: 1) sequential: where the classical and quantum parts feed directly into each other, and 2) parallel: where a classical multi-layered perceptron and a variational quantum circuit in parallel process the same information. In this section, we take an in-depth look into HQNNs of the latter type and the functions they represent. We shall refer to these networks as parallel hybrid networks (PHN). Fig 1 shows the general architecture of PHNs. The combination is a weighted linear addition with trainable weights. These weights determine the contribution of each network to the final output. The specific VQC used here is a generalised data re-uploading VQC, where \(K\) qubits are initialised in the state \(\left|0\right\rangle^{\otimes K}\). Then in alternation, a series of variational and encoding layers are applied. The encoding layers \(S\) take the input features, \(\{x_{1},\cdots,x_{N}\}\), and encode them in a unitary transformation which is then applied to the state of the qubit. The variational layers, \(U\), are unitaries that encapsulate the VQC model parameters as an operator that can be used for the quantum state of the network. Finally, the measurements are where the quantum information collapses into \(M\) classical outputs, which can be obtained by taking the expectation value of the circuit with respect to the measurement observable. Note the difference between \(M\), the number of classical outputs out of the VQC, and \(K\), the number of qubits, and that they are not necessarily the same, as often we are only required to measure some of the qubits. In parallel, the fully connected MLP also takes in the \(N\) features and passes them to a single layer of hidden neurons of size \(F\) by multiplying the feature vector by a weight matrix of size \(N\times F\). Then, biases are applied to these values and scaled using an activation function. The use of an activation function is necessary as it provides a measure of non-linearity to an otherwise linear system. Then, the neurons are propagated to \(M\) MLP output neurons with their own biases and activation functions, denoted as \(\{c_{1},\cdots,c_{M}\}\). The MLP and VQC outputs are then combined, using a two-to-one linear weight layer, to form the PHN outputs, \(\{o_{1},\cdots,o_{M}\}\). This final layer combines the first output of the VQC with the first output of the MLP: \(o_{1}=s_{1}^{c}c_{1}+s_{1}^{g}q_{1}\), and similarly for all the \(M\) outputs, where \((\{s^{q}\},\{s^{c}\})\) are trainable parameters. In Sec II, we saw that an MLP with a single hidden layer created a non-harmonic functional fit for the dataset and that the VQC created a truncated Fourier series, a harmonic function. Thus, a network combining these two results could map the smooth, sinusoidal parts through the VQC and fill the protruding sections via the MLP. This complementary setting has the potential to approximate a function that fits the dataset both in the position space (MLP) and in the conjugate momentum space (VQC). We could compare this duality to the Fourier neural operator in Ref. [13] or the models with benign overfitting in Ref. [23]. The scope of this work includes architectures that use multiple VQCs (MLPs) in parallel, as they can always be combined to form a single VQC (MLP). ### Performance We start with a ground truth consisting of an overall single-frequency sinusoidal function and then introduce high-frequency perturbations to this system. Specifically, the functional form was \[f=\sin(x)+0.05\sin(8x)+0.03\sin(16x)+0.01\sin(32x),\] which was scaled to -1 and 1. 100 equally-spaced data samples were taken from this distribution for training. We train a simple PHN, described in detail in Appendix A, to recreate the ground truth as accurately as possible. We then train the individual constituents of the same PHN architecture to see their performances. Fig 2 shows the training loss curves, and Fig 3 shows the best fits that each architecture created for the ground truth. The PHN trains to a lower MSE training loss than its elements, which suggests that adding the VQC improves the overall expressivity of the MLP. Furthermore, by examining the loss curves, we see that the PHN inherits the same speedy descent as the VQC but also shares many of the features present in the MLP loss curve, such as the spikes or the gradual flattening near the end of training. We see that the PHN outperforms both individual components, which means that both the VQC and MLP contribute to the training, and neither becomes redundant. In Sec III.2, we explore how to measure the contri Figure 1: The general architecture of the PHN. The PHN takes an input vector of features and passes them to an angle-embedded VQC (a VQC that uses single-qubit, Pauli gate embedding of features without applying any non-linear kernel on the features) of the appropriate architecture in parallel to a multi-layered perceptron with a single hidden layer of the appropriate size. The outputs of the VQC are then combined linearly with the outputs of the MLP to produce a final output vector. bution of each and how the tuning of hyper-parameters could change this contribution. ### PHN primacy A way to understand the relative contributions of each network is by inspecting the weights of the combination phase, \(s_{q}\) and \(s_{c}\), for VQC and MLP, respectively. In this section, we look at how this contribution can unfold when training the PHN. When training a PHN, we must be wary that the VQC and MLP train at different rates. We define the primary of one of the constituent architectures (VQC or MLP) over another as when the last weights preceding the PHN output layer vanish for one of the components. Equivalently, this makes the output of the latter network independent from the input features, which would mean that the prediction curve is solely constructed by either the MLP or the VQC. A primacy of this type could prevent the PHN from reaching the global minimum, as it is limited to what only one of the components could offer. The ratio of the final weights, \(r=\frac{|s_{c}|}{|s_{q}|}\), was used to track intervals of different primacy regimes recorded for different hyper-parameterisations of the PHN. Specifically, we fixed the learning rate of the VQC at 0.01 and then selected the learning rate of the MLP from 54 values of \(\alpha_{c}\in\{1.0\mathrm{e}{-7},2.0\mathrm{e}{-7},\cdots,9.0\mathrm{e}{-7},1. 0\mathrm{e}{-6},\cdots,9.0\mathrm{e}{-2}\}\). We, then, trained the PHN for 1000 epochs at a fixed initialisation point. Lastly, we recorded the ratios \(r\) throughout each training. The bigger the ratio, the more the MLP would contribute compared with the VQC. Notably, even a small contribution could make a critical difference, and primacy occurs only when one of the contributions completely vanishes. The dependence of the final loss on the ratio of the final weights for the VQC and MLP, shown in Fig 2(b), highlights the potential for either component to dominate training in the PHN architecture. The results exhibit an optimal range for the ratio between 0.1 and 1, indicating that a balanced contribution from the VQC and MLP is desirable for achieving the best results. It is also evident that complete MLP primacy, where the ratio approaches 0, leads to worse final losses. However, we also observe that adjusting the learning rates of the two components can sometimes improve the loss. Therefore, tuning the learning rates of the VQC and MLP is crucial to achieve a balanced contribution from both parts and to prevent either component from dominating the training. Figure 3: The functional fits of each architecture to the ground truth. The VQC, expectedly, produced a sinusoidal curve. The MLP created an overall curve close to a sinusoidal curve but with jagged edges. The PHN, however, produced the best result, predicting the protrusion at the peak. Figure 2: (a) The training losses of the individual elements of the PHN when trained separately, as well as the full PHN. (b) The scatter plot of final losses and their respective final ratios after 1000 epochs of training. The optimal loss value is achieved at non-zero ratios, where ratios to the side of this value provide sub-optimal losses. Note that this figure only includes the runs with learning rates whose final loss is low enough for comparison. ### Scalability and generalisation To show the scalability of the PHN, in this section, we try a 2-dimensional problem with the view that this can be scaled to an arbitrarily complex problem with many qubits. To solve the problem in Fig. 4(a), a simple PHN, described in Appendix. A, was employed. The distribution used to create this ground truth was \[f(x_{1},x_{2})=\sin(x_{1})+\sin(x_{2})+0.8\sin(x_{1}+x_{2})\] \[+0.3\sin(x_{1}-x_{2})+0.09\sin(8x_{1}+4x_{2})\] \[+0.05\sin(16x_{1}-12x_{2})+0.04\sin(12x_{1}+8x_{2}).\] Note that this function (similarly to the 1D case) was chosen entirely at random to have a coarse harmonic structure (first four terms) as well as high-frequency noise (the last three terms) and not engineered to showcase the PHN in a favourable light. 100 equidistant points were sampled from this ground truth to create a training set. This set was then trained on only the VQC, MLP, and the complete PHN for \(10,000\) epochs. The trained models were then tested on \(10,000\) equidistant points data points to see the generalisation ability of each architecture. Figs. 4(b), (c), and (d) respectively showcase the fit of the VQC, MLP, and PHN, and Fig 5 shows the evolution of their training loss. We see that the VQC creates a symmetric, sinusoidal pattern, whereas the MLP creates jagged regions to fit the ground truth. However, the PHN can generalise the ground truth by employing both elements and thus creates a closer fit, which could mean that for such datasets, the PHN could provide a high generalisation power over the MLP or the VQC. ## IV Conclusion Overall, our findings demonstrate the potential of PHN as a powerful tool for quantum machine learning. It is a hybrid architecture that can extract harmonic and non-harmonic features from a dataset. By leveraging its unique architecture, the PHN can learn complex patterns and relationships within the data that might be difficult to capture using traditional machine learning algorithms. However, it is essential to note that the performance of the PHN is highly dependent on the choice of hyperparameters. The number of layers, number of neurons in each layer, activation functions, and learning rate are crucial in determining how well the network performs on a given task. Therefore, hyperparameter tuning is a critical step in training a successful PHN. One potential direction for future research is to explore using a custom learning rate scheduler to modify the learning rate during training. A learning rate scheduler can dynamically adjust the learning rate based on the network's performance on the training set, allowing the model to learn more efficiently and converge faster. Implementing a learning rate scheduler may further improve the performance of the PHN on a wide range of tasks. Figure 4: Figure (**a**) shows the ground truth for our 2D problem in the form of a contour map. The predictions shown are for the VQC (**b**), MLP (**c**), and PHN (**d**). We see that the prediction of the VQC is smooth and convex, whereas the MLP creates jagged shapes. Taking advantage of both of these properties, the PHN represents the harmonic functions of the VQC with the added, necessary protrusions. Figure 5: The evolution of the loss function of the PHN model in Fig 6(b) and its constituents (VQC and MLP) on the 2D dataset. The PHN achieves an impressively low training MSE loss.
2306.13826
Generalised f-Mean Aggregation for Graph Neural Networks
Graph Neural Network (GNN) architectures are defined by their implementations of update and aggregation modules. While many works focus on new ways to parametrise the update modules, the aggregation modules receive comparatively little attention. Because it is difficult to parametrise aggregation functions, currently most methods select a ``standard aggregator'' such as $\mathrm{mean}$, $\mathrm{sum}$, or $\mathrm{max}$. While this selection is often made without any reasoning, it has been shown that the choice in aggregator has a significant impact on performance, and the best choice in aggregator is problem-dependent. Since aggregation is a lossy operation, it is crucial to select the most appropriate aggregator in order to minimise information loss. In this paper, we present GenAgg, a generalised aggregation operator, which parametrises a function space that includes all standard aggregators. In our experiments, we show that GenAgg is able to represent the standard aggregators with much higher accuracy than baseline methods. We also show that using GenAgg as a drop-in replacement for an existing aggregator in a GNN often leads to a significant boost in performance across various tasks.
Ryan Kortvelesy, Steven Morad, Amanda Prorok
2023-06-24T00:39:12Z
http://arxiv.org/abs/2306.13826v2
# Generalised \(f\)-Mean Aggregation ###### Abstract Graph Neural Network (GNN) architectures are defined by their implementations of update and aggregation modules. While many works focus on new ways to parametrise the update modules, the aggregation modules receive comparatively little attention. Because it is difficult to parametrise aggregation functions, currently most methods select a "standard aggregator" such as \(\mathrm{mean}\), \(\mathrm{sum}\), or \(\mathrm{max}\). While this selection is often made without any reasoning, it has been shown that the choice in aggregator has a significant impact on performance, and the best choice in aggregator is problem-dependent. Since aggregation is a lossy operation, it is crucial to select the most appropriate aggregator in order to minimise information loss. In this paper, we present GenAgg, a generalised aggregation operator, which parametrises a function space that includes all standard aggregators. In our experiments, we show that GenAgg is able to represent the standard aggregators with much higher accuracy than baseline methods. We also show that using GenAgg as a drop-in replacement for an existing aggregator in a GNN often leads to a significant boost in performance across various tasks. ## 1 Introduction Graph Neural Networks (GNNs) provide a powerful framework for operating over structured data. Taking advantage of relational inductive biases, they use local filters to learn functions that generalise over high-dimensional data. Given different graph structures, GNNs can represent many special cases, including CNNs (on grid graphs) [12], RNNs (on line graphs) [4], and Transformers (on fully connected graphs) [19]. All of these architectures can be subsumed under the Graph Networks framework, parametrised by update and aggregation modules [2]. Although the framework itself is general, the representational capacity is often constrained in practice through design choices, which create a human prior [21]. There are two primary reasons for introducing this human prior. First, there are no standard methods to parametrise all of the modules--MLPs can be used as universal approximators in the update modules, but it is nontrivial to parametrise the function space of aggregators. Consequently, most GNNs simply make a design choice for the aggregation functions, selecting mean, sum, or max [21]. Figure 1: A qualitative demonstration of the diversity of functions which can be represented by GenAgg. In these visualisations, GenAgg is plotted as a function of inputs \(x_{0}\) and \(x_{1}\) for different parametrisations \(\theta=\langle f,\alpha,\beta\rangle\) (see Equation (1)). Second, constraints can boost performance in GNNs, either through invariances or a regularisation effect. In this paper, we focus on the problem of parametrising the space of aggregation functions. The ultimate goal is to create an aggregation function which can represent the set of all desired aggregators while remaining as constrained as possible. In prior work, one approach introduces learnable parameters into functions that could parametrise min, mean, and max, such as the Powermean and a variant of Softmax [8; 13; 20]. However, these approaches can only parametrise a small set of aggregators, and they can introduce instability in the training process (see Section 4). On the opposite end of the spectrum, methods like Deep Sets [22] and LSTMAgg [9] are capable of universal approximation over set functions, but they are extremely complex, which leads to poor sample efficiency. These methods scale in complexity (_i.e._ number of parameters) with the dimensionality of the input, and lack some of the useful constraints that are shared among standard aggregators (see Section 4). Consequently, the complexity of these methods counteracts the benefits of simple GNN architectures. Although existing approaches present some limitations, the theoretical advantages of a learnable aggregation module are evident. It has been shown that the choice of aggregation function not only has a significant impact on performance, but also is problem-specific [21]. Since there is no aggregator that can discriminate between all inputs [5], it is important to select an aggregator that preserves the relevant information. In this paper, we present a method that parametrises the function space, allowing GNNs to learn the most appropriate aggregator for each application. Contributions * We introduce Generalised Aggregation (GenAgg), the first aggregation method based on the _generalised f-mean_. GenAgg is a learnable permutation-invariant aggregator which is provably capable (both theoretically and experimentally) of representing all "standard aggregators" (see Appendix C for proofs). The representations learned by GenAgg are _explainable_--each learnable parameter has an interpretable meaning (Section 6). * Our experiments provide several insights about the role of aggregation functions in the performance of GNNs. In our regression experiments, we demonstrate that GNNs struggle to "make up for" the lack of representational complexity in their constituent aggregators, even when using state-of-the-art parametrised aggregators. This finding is validated in our GNN benchmark experiments, where we show that a GenAgg-based GNN outperforms all of the baselines, including standard aggregators and other state-of-the-art parametrised aggregators. * Finally, we show that GenAgg satisfies a generalisation of the distributive property. We derive the a solution for a binary operator that satisfies this property for given parametrisations of GenAgg. The generalised distributive property can be leveraged in algorithms using GenAgg to improve space and memory-efficiency. ## 2 Problem Statement Consider a multiset \(\mathcal{X}=\{x_{1},x_{2},\ldots,x_{n}\}\) of cardinality \(|\mathcal{X}|=n\), where \(x_{i}\in\mathbb{R}^{d}\). We define an aggregation function as a symmetric function \(\bigcirc:\mathbb{R}^{n\times d}\mapsto\mathbb{R}^{1\times d}\). The aggregator must be independent over the feature dimension, so without loss of generality it can be represented over a single dimension \(\bigcirc:\mathbb{R}^{n}\mapsto\mathbb{R}^{1}\). A set of standard aggregators is defined \(\mathcal{A}=\{\mathrm{mean},\mathrm{sum},\mathrm{product},\mathrm{min}, \mathrm{max},\ldots\}\) (for the full list see Table 1). Our task is to create an aggregator \(\bigoplus_{\theta}:\mathbb{R}^{n}\mapsto\mathbb{R}^{1}\) parametrised by \(\theta\) which can represent all standard aggregators: \(\forall\bigcirc_{i}\in\mathcal{A}\;\exists\theta:\;\bigoplus_{\theta}=\bigcirc_ {i}\). ## 3 Method In this section we introduce GenAgg, a parametrised aggregation function which is based on the _generalised f-mean_[11]. In our formulation, we introduce additional parameters to increase the representational capacity of the \(f\)-mean, producing the _augmented f-mean_ (AFM). Then, as the implementation is non-trivial, we propose a method to implement it. The novel aspect of GenAgg is not only the augmented \(f\)-mean formula, but also the implementation, which allows the mathematical concept of a generalised mean to be utilised in a machine learning context. ### Generalised \(f\)-Mean The _generalised f-mean_[11] is given by: \(f^{-1}(\frac{1}{n}\sum_{i}f(x_{i}))\). While it is difficult to define aggregation functions, the generalised \(f\)-mean provides a powerful intuition: most aggregators can be represented by a single invertible scalar-valued function \(f:\mathbb{R}^{1}\mapsto\mathbb{R}^{1}\). This is a useful insight, because it allows comparisons to be drawn between aggregators by analysing their underlying functions \(f\). Furthermore, it provides a framework for discovering new aggregation functions. While classic functions like \(e^{x},\log(x),x^{p}\) all map to aggregators in \(\mathcal{A}\), new aggregators can be created by defining new functions \(f\). ### Augmented \(f\)-Mean The standard generalised \(f\)-mean imposes strict constraints, such as symmetry (permutation-invariance), idempotency (\(\bigoplus(\{x,\ldots,x\})=x\)), and monotonicity (\(\forall i\in[1..n],\frac{\partial\bigoplus(\{x_{1},\ldots,x_{n}\})}{\partial x _{i}}\geq 0\)). However, this definition is too restrictive to parametrise many special cases of aggregation functions. For example, sum violates idempotency (\(\sum_{i\in[1..n]}x_{i}=nx\)), and standard deviation violates monotonicity (\(\frac{\partial\sigma(\{x_{1},1\})}{\partial x_{1}}|_{x_{1}=0}<0\)). Consequently, we deem these constraints to be counterproductive. In our method, we introduce learnable parameters \(\alpha\) and \(\beta\) to impose a relaxation on the idempotency and monotonicity constraints, while maintaining symmetry. We call this relaxed formulation the _augmented \(f\)-mean_ (AFM), given by: \[\bigoplus_{i\in[1..n]}x_{i}=f^{-1}\left(n^{\alpha-1}\sum_{i\in[1..n]}f(x_{i}- \beta\mu)\right). \tag{1}\] The \(\alpha\) parameter allows AFM to control its level of dependence on the cardinality of the input \(\mathcal{X}\). For example, given \(f(x)=\log(|x|)\), if \(\alpha=0\), then AFM represents the geometric mean: \(\bigoplus_{(f,\alpha,\beta)}=\bigoplus_{(\log(|x|),0,0)}=\sqrt[3]{\prod|x_{i}|}\). However, if \(\alpha=1\), then the \(n\)-th root disappears, and AFM represents a product: \(\bigoplus_{(\log(|x|),1,0)}=\prod|x_{i}|\). \begin{table} \begin{tabular}{|l|c|c|c|c|c|c|} \hline Aggregation Function & \(\alpha\) & \(\beta\) & \(f\) & GenAgg & SoftmaxAgg & PowerAgg \\ \hline \hline mean: \(\frac{1}{n}\sum x_{i}\) & 0 & 0 & \(f(x)=x\) & ✓ & ✓ & ✓ \\ \hline sum: \(\sum x_{i}\) & 1 & 0 & \(f(x)=x\) & ✓ & ✗ & ✗ \\ \hline product: \(\prod|x_{i}|\) & 1 & 0 & \(f(x)=\log(|x|)\) & ✓ & ✗ & ✗ \\ \hline min (magnitude): \(\min|x_{i}|\) & 0 & 0 & \(f(x)=\lim_{p\rightarrow\infty}|x|^{-p}\) & ✓ & ✗ & ✓ \\ \hline max (magnitude): \(\max|x_{i}|\) & 0 & 0 & \(f(x)=\lim_{p\rightarrow\infty}|x^{p}|^{p}\) & ✓ & ✗ & ✓ \\ \hline min: min \(x_{i}\) & 0 & 0 & \(f(x)=\lim_{p\rightarrow\infty}e^{-p\alpha}\) & ✓ & ✓ & ✗ \\ \hline max: \(\max x_{i}\) & 0 & 0 & \(f(x)=\lim_{p\rightarrow\infty}e^{\alpha}\) & ✓ & ✓ & ✗ \\ \hline harmonic mean: \(\frac{n}{\sum x}\) & 0 & 0 & \(f(x)=\frac{1}{2}\) & ✓ & ✗ & ✓ \\ \hline geometric mean: \(\sqrt[3]{\prod|x_{i}|}\) & 0 & 0 & \(f(x)=\log(|x|)\) & ✓ & ✗ & ✓ \\ \hline root mean square: \(\sqrt[3]{\sum x_{i}^{2}}\) & 0 & 0 & \(f(x)-x^{2}\) & ✓ & ✗ & ✓ \\ \hline collection norm: \(\sqrt[3]{\sum x_{i}^{2}}\) & 1 & 0 & \(f(x)-x^{2}\) & ✓ & ✗ & ✗ \\ \hline standard deviation: \(\sqrt[3]{\sum x_{i}^{2}(x_{i}-x_{i}^{2})^{2}}\) & 0 & 1 & \(f(x)-x^{2}\) & ✓ & ✗ & ✗ \\ \hline log-sum-exp: \(\log\left(\sum e^{\alpha}\right)\) & 1 & 0 & \(f(x)-e^{\alpha}\) & ✓ & ✗ & ✗ \\ \hline \end{tabular} \end{table} Table 1: A table of all of the most common aggregators. For each special case, we specify the values of \(\alpha\), \(\beta\), and \(f\) for which the augmented \(f\)-mean is equivalent (see Appendix C). We also report whether or not SoftmaxAgg and PowermeanAgg can represent each aggregator. The \(\beta\) parameter enables AFM to calculate _centralised moments_, which are a quantitative measures of the distribution of the input \(\mathcal{X}\)[17]. The first raw moment of \(\mathcal{X}\) is the mean \(\mu=\frac{1}{n}\sum x_{i}\), and the \(k\)-th central moment is given by \(\mu_{k}=\sum\left(x_{i}-\mu\right)^{n}\). With the addition of \(\beta\), it becomes possible for AFM to represent \(\sqrt[k]{\mu_{k}}\), the \(k\)-th root of the \(k\)-th central moment. For \(k=2\), this quantity is the standard deviation, which is in our set of standard aggregators \(\mathcal{A}\). If the output is scaled to the \(k\)-th power, then it can also represent metrics such as variance, unnormalised skewness, and unnormalised kurtosis. It is clear that these metrics about the distribution of data are useful--they can have real-world meaning (_e.g._, moments of inertia), and they have been used as aggregators in GNNs in prior work [5]. Consequently, \(\beta\) provides AFM with an important extra dimension of representational complexity. In addition to representing the centralised moments when \(\beta=1\) and \(f(x)=x^{p}\), \(\beta\) allows _any_ aggregator to be calculated in a centralised fashion. While the centralised moments are the only well-known aggregators that arise from nonzero \(\beta\), there are several aggregators with qualitatively unique behaviour that can only be represented with nonzero \(\beta\) (see Fig. 1). With this parametrisation, AFM can represent any standard aggregator in \(\mathcal{A}\) (Table 1). Furthermore, by selecting new parametrisations \(\theta=\langle f,\alpha,\beta\rangle\), it is possible to compose new aggregators (Fig. 1). ### Implementation In Equation (1), the manner in which \(f^{-1}\) is implemented is an important design choice. One option is to learn the coefficients for an analytical function (_e.g._ a truncated Taylor Series) and analytically invert it. However, it can be difficult to compute the analytical inverse of a function, and without carefully selected constraints, there is no guarantee that \(f\) will be invertible. Another possible option is an invertible neural network (_e.g._ a parametrised invertible mapping from _normalising flows_[10]). We have tested the invertible networks from normalising flows literature as implementations for \(f\). While they work well on smaller tasks, these methods present speed and memory issues in larger datasets. In practice, we find that the most effective approach is to use two separate MLPs for \(f\) and \(f^{-1}\). We enforce the constraint \(x=f^{-1}(f(x))\) by minimizing the following optimisation objective: \[\mathcal{L}_{\mathrm{inv}}(\theta_{1},\theta_{2})=\mathbb{E}\left[\left(\left| f_{\theta_{2}}^{-1}(f_{\theta_{1}}(x))\right|-|x|\right)^{2}\right]. \tag{2}\] The absolute value operations apply a relaxation to the constraint, allowing \(f^{-1}(f(x))\) to reconstruct either \(x\) or \(|x|\). This is useful because several of the ground truth functions from Table 1 include an absolute value, making them non-invertible. With this relaxation, it becomes possible to represent those cases. This optimisation objective ensures that \(f\) is both monotonic and invertible over the domains \(\mathbb{R}^{+}\) and \(\mathbb{R}^{-}\), independently. In our implementation, this extra optimisation objective is hidden behind the GenAgg interface and gets applied automatically with a forward hook, so it is not necessary for the user to apply an extra loss term. While using a scalar-valued \(f:\mathbb{R}^{1}\mapsto\mathbb{R}^{1}\) is the most human-interpretable formulation, it is not necessary. A valid implementation of GenAgg can also be achieved with \(f:\mathbb{R}^{1}\mapsto\mathbb{R}^{d}\) and \(f^{-1}:\mathbb{R}^{d}\mapsto\mathbb{R}^{1}\). In our experiments, we found that mapping to a higher intermediate dimension can sometimes improve performance over a scalar-valued \(f\) (see training details in Appendix E). ### Generalised Distributive Property Given that GenAgg presents a method of parameterising the function space of aggregators, it can also be used as a tool for mathematical analysis. To demonstrate this, we use the augmented \(f\)-mean to analyse a generalised form of the distributive property, which is satisfied if \(\psi\left(c,\sum_{x_{i}\in\mathcal{X}}x_{i}\right)=\bigcirc_{x_{i}\in \mathcal{X}}\psi(c,x_{i})\) for binary operator \(\psi\) and aggregator \(\bigcirc\). For a given aggregation function parametrised by \(f\) (assuming \(\alpha\) is either \(0\) or \(1\) and \(\beta\) is \(0\)), we derive a closed-form solution for a corresponding binary operator which will satisfy the generalised distributive property (for further explanation and proofs, see Appendix A). **Theorem 3.1**.: _For GenAgg parametrised by \(\theta=\langle f,\alpha,\beta\rangle=\langle f,1,0\rangle\), the binary operator \(\psi\) which will satisfy the Generalised Distributive Property for \(\bigoplus_{\theta}\) is given by \(\psi(a,b)=f^{-1}(f(a)+f(b))\), and for \(\theta=\langle f,\alpha,\beta\rangle=\langle f,0,0\rangle\), the operator \(\psi\) is given by \(\psi(a,b)=f^{-1}(f(a)\cdot f(b))\)._ For example, for the geometric mean where \(f(x)=x^{2}\) and \(\alpha=0\), the binary operator is \(\psi(a,b)=(a^{2}\cdot b^{2})^{-2}=a\cdot b\), which implies that a constant multiplicative term can be moved outside of the geometric mean. This is a useful finding, as the distributive property can used to improve algorithmic time and space complexity (_e.g._ the FFT) [1]. With our derivation of \(\psi\) as a function of \(f\), it is possible to implement similar efficient algorithms with GenAgg. ## 4 Related Work Several existing works propose methods to parametrise the space of aggregation functions. These methods can broadly be divided into two categories. _Mathematical_ approaches derive an explicit equation in terms of the inputs and one or more learnable parameters. Usually, these approaches represent a smooth interpolation through function space from min, through mean, to max. Alternatively, _Deep Learning_ approaches seek to use the universal approximation properties of neural networks to maximise representational complexity. ### Mathematical Approaches **SoftmaxAgg** SoftmaxAgg computes the weighted sum of the set, where the weighting is derived from the softmax over the elements with some learnable temperature term \(s\)[13; 20]. This formulation allows SoftmaxAgg to represent mean, min, and max (see Table 1). Unfortunately, it fails to generalise across the majority of the standard aggregators. **PowerAgg** Based on the \(p\)-norm, PowerAgg is a special case of GenAgg where \(\alpha=0\), \(\beta=0\), and \(f(x)=x^{p}\). There are some methods which use the powermean directly [13; 20; 8], and others which build on top of it [18]. Theoretically, PowerAgg can represent a significant subset of the standard aggregators: min magnitude, max magnitude, mean, root mean square, harmonic mean, and geometric mean (although the geometric mean requires \(\lim_{p\to 0}\), so it is not practically realisable) (see Table 1). Unfortunately, there is a caveat to this approach: for negative inputs \(x_{i}<0\) and non-integer values \(p\), it is only defined in the complex domain. Furthermore, for negative inputs, the gradient \(\frac{\partial x^{p}}{\partial p}\) with respect to trainable parameter \(p\) is complex and oscillatory (and therefore is prone to getting stuck in local optima). In order to fix this problem, the inputs must be constrained to be positive. In prior work, this has been achieved by clamping \(x^{\prime}_{i}=\max(x_{i},0)\)[13], subtracting the minimum element \(x^{\prime}_{i}=x_{i}-\min(\mathcal{X})\)[20], or taking the absolute value \(x^{\prime}_{i}=|x_{i}|\)[8]. However, this removes important information, making it impossible to reconstruct most standard aggregators. ### Deep Learning Approaches **PNA** While Principle Neighbourhood Aggregation [5] is introduced as a GNN architecture, its novelty stems from its method of aggregation. In PNA, input signal is processed by a set of aggregation functions, which is produced by the cartesian product of standard aggregators \(\{\text{mean},\text{min},\text{max},\text{std}\}\) and scaling factors \(\{\frac{1}{n},1,n\}\). The output of every aggregator is concatenated, and passed through a dense network. While this increases the representational complexity of the aggregator, it also scales the dimensionality of the input by the number of aggregators multiplied by the number of scaling factors, which can decrease sample efficiency. Furthermore, the representational complexity of the method is limited by the choice of standard aggregators--it cannot be used to represent many of the special cases of parametrised general aggregators. **LSTMAgg** In LSTMAgg, the input set is treated as a sequence (applying some random permutation), and is encoded with a recurrent neural network [9]. While this method is a universal approximator, it is not permutation-invariant. Due to the factorial complexity of possible orderings, this leads to sample inefficiency. SortAgg addresses this issue by sorting the inputs with computed features, and passing the first \(k\) sorted inputs through convolutional and dense networks [23]. While this method solves the issue of non-permutation-invariance, it loses the capability of universal approximation by truncating to \(k\) inputs. While universal approximation is not a requirement for an effective aggregation function, we note that it cannot represent many of the standard aggregators. **Deep Sets** Deep Sets is a universal set function approximator [22]. Due to its complexity, it is not usually viewed as an aggregator--it usually serves as a full GNN layer or graph pooling architecture [14; 15]. One may note that the formulation for Deep Sets \(\phi(\sum_{i\in[1..n]}f(x_{i}))\) bears some resemblance to our method. However, there are two important differences. First, our method adds the constraint \(\phi=f^{-1}\), limiting possible parametrisations to the subspace where all of the standard aggregators lie. Second, while the learnable functions \(\phi\) and \(f\) in Deep Sets are fully connected over the feature dimension, the \(f\) and \(f^{-1}\) modules in our architecture are scalar-valued functions which are applied element-wise. To summarise, Deep Sets is useful as a set function approximator, but it lacks constraints that would make it viable as an aggregation function. ## 5 Experiments In this paper, we run three experiments. First, we show that GenAgg can perform regression to recover any standard aggregation function. Then, we evaluate GenAgg and several baselines inside of a GNN. The resulting GNN architectures are given the same task of regressing upon graph-structured data generated with a standard aggregator. This tests if it is possible for a GNN with a given aggregator to represent data which was generated by different underlying aggregators. Finally, we provide practical results by running experiments on public GNN benchmark datasets: CLUSTER, PATTERN, CIFAR10, and MNIST [6]. For all baselines, we use the implementations provided in PyTorch Geometric [7]. The only exception is PNA, which is a GNN architecture by nature, not an aggregation method. For our experiments, we adapt PNA into an aggregation method, staying as true to the original formulation as possible: \(\mathrm{PNA}(\mathcal{X})=f([1,n,\frac{1}{n}]\otimes[\mathrm{mean}(\mathcal{ X}),\mathrm{std}(\mathcal{X}),\min(\mathcal{X}),\max(\mathcal{X})])\), where \(f\) is a linear layer mapping from \(\mathbb{R}^{12d}\) back to \(\mathbb{R}^{d}\). For more training details, see Appendix E. Our code (including a python package with the GenAgg torch module, as well as our experiments) can be found at: [https://anonymous.4open.science/r/generalised-aggregation-42C3](https://anonymous.4open.science/r/generalised-aggregation-42C3). ### Aggregator Regression In this experiment, we generate a random graph \(\mathcal{G}=\langle\mathcal{V},\mathcal{E}\rangle\) with \(|\mathcal{V}|=8\) nodes and an edge density of \(\frac{|\mathcal{E}|}{|\mathcal{V}|}2=0.3\). For each node \(i\in\mathcal{V}\), we draw an internal state \(x_{i}\in\mathbb{R}^{d}\) from a normal distribution \(x_{i}\sim\mathcal{N}(\mathbf{0}_{d},I_{d})\) with \(d=6\). Then, we generate training data with a set of ground truth aggregators (\(\bigcirc\)\({}_{k}\in\mathcal{A}\) (where \(k\) is an index). For each aggregator \(\bigcirc_{k}\), the dataset \(X_{k},Y_{k}\) is produced with a Graph Network [2], using \(\bigcirc\)\({}_{k}\) as the node aggregation module. The inputs are defined by the set of neighbourhoods in the graph \(X_{k}=\{\mathcal{X}_{i}\mid i\in[1..|\mathcal{V}|]\}\) where the neighbourhood \(\mathcal{X}_{i}\) is defined as \(\mathcal{X}_{i}=\{x_{j}\mid j\in\mathcal{N}_{i}\}\) with \(\mathcal{N}_{i}=\{j\mid(i,j)\in\mathcal{E}\}\). The corresponding ground truth outputs are defined as \(Y_{k}=\{y_{i}\mid i\in[1..|\mathcal{V}|]\}\), where \(y_{i}=\bigcirc_{k}(\mathcal{X}_{i})\). Figure 2: Results for the Aggregator Regression and GNN Regression experiments, indicating the ability of GenAgg, PowerAgg (P-Agg), SoftmaxAgg (S-Agg), and mean to parametrise each standard aggregator in \(\mathcal{A}\). We report the correlation coefficient between the ground truth and predicted outputs. The highest-performing methods (and those within \(0.01\) correlation) are shown in bold. The model that we use for regression takes the same form as the model used to generate the data, except that the standard aggregator used to generate the training data \(\bigodot_{k}\) is replaced with a parametrised aggregator \(\bigoplus_{\theta}\): \[\hat{y}_{i}=\bigoplus_{x_{j}\in\mathcal{X}_{i}}x_{j} \tag{3}\] In our experiments, each type of parametrised aggregator (GenAgg, SoftmaxAgg, PowerAgg, and mean as a baseline) is trained separately on each dataset \(X_{k},Y_{k}\). **Results.** We report the MSE loss and correlation coefficient with respect to the ground truth in Table 2a. GenAgg is able to represent all of the standard aggregators with a correlation of at least \(0.96\), and most aggregators with a correlation of greater than \(0.99\). The only cases where the performance of GenAgg is surpassed by a baseline are \(\min\) and \(\max\), where SoftmaxAgg exhibits marginally higher accuracy (Table 1). One interesting observation is that even if the baselines can represent an aggregator in _theory_, they cannot necessarily do so in practice. For example, PowerAgg can theoretically represent the geometric mean with \(\lim_{p\to 0}(\frac{1}{n}\sum_{i}x_{i}^{p})^{\frac{1}{p}}\), but in practice there are instabilities as \(p\) approaches \(0\) because \(\frac{1}{p}\) approaches \(\frac{1}{0}\). Similarly, while in theory PowerAgg can represent min magnitude, max magnitude, harmonic mean, and root mean square, it falls short in practice (see Table 2a), likely because of the reasons stated in Section 4. In other cases, the baselines can perform well even if they should not be able to represent the target in theory. One such example is PowerAgg, which achieves a correlation of \(0.92\) on max, but only \(0.59\) on max magnitude, which is the opposite of what theory might suggest. This is likely due to the the clamp operation that Pytorch Geometric's implementation uses to restricts inputs to the positive domain. The performance of max magnitude suffers, as it misses cases where the highest magnitude element is negative. Similarly, the performance of Figure 3: Test accuracy for GNNs with various aggregators on GNN benchmark datasets. In this experiment, each trial uses the same base GNN architecture (4-layer GraphConv), and the default aggregator is replaced with either GenAgg, PowermeanAgg (P-Agg), SoftmaxAgg (S-Agg), PNA, mean, sum, or max. The plots depict the mean and standard deviation of the test accuracy over \(10\) trials (note that the y-axis is scaled to increase readability). The table reports the maximum of the mean test accuracy over all timesteps. max increases, because it simply selects the maximum among the positive elements. Another baseline which performs unexpectedly well is SoftmaxAgg, which achieves a high correlation with the log-sum-exp aggregator. While it cannot compute a log, the SoftmaxAgg formulation does include a sum of exponentials, so it is able to produce a close approximation. ### GNN Regression In GNN Regression, the experimental setup is the same as that of Aggregator Regression (Section 5.1), with the exception that the observation size is reduced to \(d=1\). However, instead of using GenAgg \(\bigoplus_{\theta}\) as a model, we use a multi-layer GNN. The GNN is implemented with \(4\) layers of GraphConv [16] with Mish activation (after every layer except the last), where the default aggregation function is replaced by a parametrised aggregator \(\bigoplus_{\theta}\): \[z_{i}^{(k+1)} =\operatorname{Mish}\left(W_{1}^{(k)}z_{i}^{(k)}+W_{2}^{(k)} \bigoplus_{j\in\mathcal{N}_{i}}z_{i}^{(k)}\right),\text{ s.t. }z_{i}^{(0)}=x_{i} \tag{4}\] \[\hat{y}_{i} =W_{1}^{(3)}z_{i}^{(3)}+W_{2}^{(3)}\bigoplus_{j\in\mathcal{N}_{i }}z_{i}^{(3)} \tag{5}\] While this experiment uses the same dataset as Aggregator Regression (Section 5.1), it provides several new insights. First, while the aggregator regression experiment shows that GenAgg _can_ represent various aggregators, this experiment demonstrates that training remains stable even when used within a larger architecture. Second, this experiment underlines the importance of using the correct aggregation function. While it is clear that it is advantageous to match a model's aggregation function with that of the underlying mechanism which generated a particular dataset, we often opt to simply use a default aggregator. The conventional wisdom of this choice is that the other learnable parameters in a network layer can rectify an inaccurate choice in aggregator. However, the results from this experiment demonstrate that even with additional parameters, it is not necessarily possible to represent a different aggregator, underlining the importance of aggregators with sufficient representational capacity. **Results.** The results show that GenAgg maintains its performance, even when used as a component within a GNN (Table 2b). GenAgg achieves a mean correlation of \(0.97\) across all aggregators. While the baselines perform significantly better with the help of a multi-layer GNN architecture, they still cannot represent many of the standard aggregators. The highest-performing baseline is SoftmaxAgg, which only achieves a mean correlation of \(0.86\). ### GNN Benchmark In this experiment, we examine the performance of GenAgg on GNN benchmark datasets [6]. In order to perform a comparison with benchmarks, we train on an existing GNN architecture (a 4-layer GraphConv [16] GNN with a hidden size of 64) where the default aggregator is replaced with a new aggregator, selected from \(\{\operatorname{GenAgg},\operatorname{PowerAgg},\operatorname{SoftmaxAgg}, \operatorname{PNA},\operatorname{mean},\operatorname{sum},\max\}\). **Results.** As shown in Fig 3, GenAgg outperforms all baselines in all four GNN benchmark datasets. It provides a significant boost in performance, particularly compared to the relatively small differences in performance between the baseline methods. The training plots in Fig. 3 provide complementary information. One interesting observation is that GenAgg converges at least as fast as the other methods, and sometimes converges significantly faster (in PATTERN, for example). Furthermore, the training plots lend information about the stability of training. For example, note that in MNIST, most of the baseline methods achieve a maximum and then degrade in performance, while GenAgg maintains a stable performance throughout training. ## 6 Discussion **Results**. In our experiments, we present two regression tasks and one GNN benchmark task. The regression experiments demonstrate that GenAgg is the only method capable of representing all of the standard aggregators, and a GNN cannot be used to "make up for" the shortcomings of the baseline aggregators. The GNN benchmark experiment complements these findings, demonstrating that this representational complexity is actually useful in practice. The fact that GenAgg outperforms the standard aggregators (\(\mathrm{mean}\), \(\mathrm{max}\), and \(\mathrm{sum}\)) on the GNN benchmark experiment implies that it is in fact creating a _new_ aggregator. Furthermore, the fact that it outperforms baseline methods like SoftmaxAgg and PowermeanAgg implies that the aggregator learned by GenAgg lies outside the set of functions which can be represented by such methods. **Limitations**. While GenAgg achieves positive results on these datasets, it is not possible to make generalisations about its performance in all applications. In particular, we observe that on smaller datasets where overfitting is already an issue, GenAgg often fails to deliver the same performance benefits, achieving a similar test accuracy to the baselines. For a full list of datasets that we considered and further discussion of limitations, see Appendix D. **Parameters**. When comparing the performance of different models, it is important to also consider the number of parameters. By introducing additional parameters, some models can improve overall performance at the cost of sample efficiency. While methods like PowerAgg and SoftmaxAgg only have one trainable parameter, GenAgg has two scalar parameters \(\alpha\) and \(\beta\), and a learnable function \(f\), which has \(30\) parameters in our implementation (independent of the size of the state). However, we observe that using GenAgg within a GNN is always at least as sample-efficient as the baselines, and sometimes converges significantly faster (Fig. 3 and Appendix B). Furthermore, while GenAgg has more parameters than PowerAgg and SoftmaxAgg, the increase is negligible compared to the total number of parameters in the GNN. We also note that GenAgg has significantly fewer parameters than the deep learning methods discussed in Section 4. While the deep learning methods scale linearly or quadratically in the dimension of the state, the number of parameters in GenAgg is constant. **Stability**. Another observation from our experiments is that GenAgg exhibits more stability during the training process than the baselines (Appendix B). In the GNN Regression experiment, the PowerAgg and SoftmaxAgg training curves tend to plateau at least once before reaching their maximum value. It is possible that these methods lead to local optima because they are optimised in a lower dimensional parameter space [3]. For example, it is straightforward to smoothly transform a learned \(f\) in GenAgg from \(x^{2}\) to \(x^{4}\), but to do so in PowerAgg, it is necessary to pass through \(x^{3}\), which has significantly different behaviour in the negative domain. While PowerAgg restricts inputs to the positive domain to circumvent this particular issue, the problem of local optima can still arise when methods like PowerAgg or SoftmaxAgg are used as components in a larger architecture. **Explainability**. While in this paper we primarily focus on the _performance_ of GenAgg, we note that it also presents benefits in the realm of explainability. The three parameters in GenAgg are all human-readable (scalars and scalar-valued functions can easily be visualised), and they all provide a unique intuition. The \(\alpha\) parameter controls the dependence on the cardinality of the input set. The \(\beta\) parameter dictates if the aggregator is computed in a raw or centralised fashion (colloquially, it answers if the aggregator operates over the inputs themselves, or the variation between the inputs). Lastly, the function \(f\) can be analysed by interpreting its magnitude \(|f(x_{i})|\) at a given point \(x_{i}\) as the relative impact of that point on the output. For example, the parametrisation of product is \(f(x)=\log(|x|)\), which implies that a value of \(1\) has no impact on the output since \(|\log(|1|)|=0\), and extremely small values \(\epsilon\) have a large impact, because \(\lim_{\epsilon\to 0}|\log(|\epsilon|)|=\infty\). Indeed, \(1\) is the identity element under multiplication, and multiplying by a small value \(\epsilon\) can change the output by many orders of magnitude. The interpretability of GenAgg can also be leveraged as a method to _select_ an aggregator--a model can be pre-trained with GenAgg, and then each instance of GenAgg can be replaced with the most similar standard aggregator in \(\mathcal{A}\). ## 7 Conclusion In this paper we introduced GenAgg, a generalised, explainable aggregation function which parametrises the function space of aggregators, yet remains as constrained as possible to improve sample efficiency and prevent overfitting. In our experiments, we showed that GenAgg can represent all \(13\) of our selected "standard aggregators" with a correlation coefficient of at least \(0.96\). We also evaluated GenAgg alongside baseline methods within a GNN, illustrating how other approaches have difficulties representing standard aggregators, even with the help of additional learnable parameters. Finally, we demonstrated the usefulness of GenAgg on GNN benchmark tasks, comparing the performance of the same GNN with various different aggregators. The results showed that GenAgg provided a significant boost in performance over the baselines in all four datasets. Furthermore, GenAgg often exhibited more stability and faster convergence than the baselines in the training process. These results show that GenAgg is an application-agnostic aggregation method that can provide a boost in performance as a drop-in replacement for existing aggregators. ## 8 Acknowledgements This work was supported by ARL DCIST CRA W911NF-17-2-0181 and European Research Council (ERC) Project 949940 (gAIa).
2310.04464
Integration of Fractional Order Black-Scholes Merton with Neural Network
This study enhances option pricing by presenting unique pricing model fractional order Black-Scholes-Merton (FOBSM) which is based on the Black-Scholes-Merton (BSM) model. The main goal is to improve the precision and authenticity of option pricing, matching them more closely with the financial landscape. The approach integrates the strengths of both the BSM and neural network (NN) with complex diffusion dynamics. This study emphasizes the need to take fractional derivatives into account when analyzing financial market dynamics. Since FOBSM captures memory characteristics in sequential data, it is better at simulating real-world systems than integer-order models. Findings reveals that in complex diffusion dynamics, this hybridization approach in option pricing improves the accuracy of price predictions. the key contribution of this work lies in the development of a novel option pricing model (FOBSM) that leverages fractional calculus and neural networks to enhance accuracy in capturing complex diffusion dynamics and memory effects in financial data.
Sarit Maitra, Vivek Mishra, Goutam Kr. Kundu, Kapil Arora
2023-10-05T14:53:19Z
http://arxiv.org/abs/2310.04464v2
# Integration of Fractional Order Black-Scholes ###### Abstract This study presents a novel approach to enhance option pricing accuracy by introducing the Fractional Order ack-Scholes-Merton (FOBSM) model. FOBSM combinesments of the traditional Black-Scholes-Merton (BSM) model with the flexibility of neural networks (NN). American options use unique pricing challenges due to free boundary difficulties. a the other hand, traditional models like BSM struggle to curately represent market pricing. The challenge is to develop pricing model that better captures the tail behavior, memory fees, volatility clustering, long-term dependencies, and evness inherent in financial data, while simultaneously liking the theoretical underpinnings of BSM and fractional leulus. The gap arises from the absence of a comprehensive ametwork that integrates fractional calculus and neural networks to enhance option pricing accuracy in complex fusion dynamics scenarios. Since FOBSM captures memory aracteristics in sequential data, it is better at simulating real-grid systems than integer-order models. Findings reveal that complex diffusion dynamics, this hybridization approach in option pricing improves the accuracy of price predictions. black schools model; diffusion dynamics; rational calculus; neural network; partial differential equation. ## I Introduction American options offer greater flexibility and profit potential than European options, but they are valued differently. European options use mathematical formulas foricing, while American options have an early exercise feature. The presence of early exercise options creates free boundary difficulties in the pricing process, making it more challenging than European options pricing. This research integrates fractional calculus and neural networks into option pricing and presents a theoretical framework to address this challenge. Fractional calculus (FC), which uses derivatives and integrals of any non-integer order, has gained popularity for its capacity to simulate memory-like systems ([1], [2]). Model based on fractional calculus account for volatility clustering, long-term dependencies, tail behavior, and skewness, making them better for options with longer maturities or market stress. Black and Scholes [3] introduced the fundamental equation in 1973, and Merton later modified it, earning them the Nobel Memorial Prize. This is known as the Black-Scholes-Merton (BSM) model which provides a solid theoretical framework. It has limitations when it comes to accurately reflecting actual market pricing. Despite this, the model is a helpful tool for evaluating options. However, a mathematically simpler binomial model was proposed [4] which is intuitive and more frequently used in practice for discrete price data. Our work pertains to continuous data, and it employs the BSM model as the foundation for option pricing. While recognizing the BSM model's theoretical significance, our study aims to enhance its applicability and precision by incorporating fractional calculus and neural networks to address the challenge posed by complex market dynamics and discrepancies between theoretical and market-based option pricing. The lognormal diffusion assumption is a fundamental assumption in the Black-Scholes-Merton (BSM) option pricing model, which plays a key role in the model's formulation. This assumption is incompatible with market prices, which led to the BSM model being modified over the years to enhance its performance. Examples of these modifications include jump diffusion models ([5], [6]), stochastic volatility models ([7], [8]), and others. We introduce fractional order Black-Scholes-Merton (FOBSM), which is an extension of the classical BSM that incorporates fractional calculus. A combination of closed-form and numerical solutions to address mathematical problems has been examined by researchers [9]. Their work has inspired the solution of FOBSM, which allows for the analysis of implied volatility and option prices' non-local behavior. FOBSM uses neural networks' flexibility and adaptability to improve option pricing accuracy in situations where traditional models may fall short. The hybridization of FOBSM and NN in options increases the accuracy of option price predictions, particularly in situations with complicated diffusion dynamics. The findings are divided into two categories: providing option values using more powerful numerical and analytic approaches and developing new pricing models that accurately reflect the financial market. The major contributions to this work are: 1. A novel approach to option pricing that leverages the strengths of both the FOBSM and NNs (Neural Networks) by integrating both models. 2. Improved accuracy in predicting option prices, especially in scenarios with complex diffusion dynamics, which refers to the movement or behavior of an underlying asset's price over time. ### _Black Scholes model with default risk_ The variables used by BSM are the volatility, underlying asset price, option strike price, expiration time, and risk-free interest rate. Eq. (1) and (2) formulate the put and the call options: \[Call =S_{0}N(d_{1})-N(d_{2})Ke^{-r\tau T} \tag{1}\] \[Put =N(-d_{2})Ke^{-r\tau}-N(-d_{1})S_{0} \tag{2}\] where, \(d_{1}=\left(ln(S/K)\ +\ (r+\frac{\sigma^{2}}{2})T\right)/\sigma\sqrt{T}\), \(d_{2}=d_{1}-\sigma\sqrt{T}\) and \(S=\) underlying asset prices corresponding to the observed option prices at time \(t\), \(N=\) normal distribution, \(K=\) strike price, \(t=\) time to maturity, \(\sigma=\) volatility (standard deviation of log return), \(r=\) risk-free interest rate, \(T=\) time to expiration for each option. The value of a call option is divided into two parts: * the amount paid when exercising the option (\(N(d_{2})Ke^{-r\tau}\)) * the amount received when selling the underlying (\(N(d_{1})S_{t}\)). The strike price (K) undergoes a discounting process using the standard discounting factor (\(e^{-r\tau}\)), where \(e\) represents the mathematical constant, and \(r\) signifies the risk-free interest rate applicable for investing funds over a specified period \(T\). The determination of this risk-free rate (\(r\)) can be achieved through a range of established methodologies. The cumulative distribution function (CDF) of a normal distribution serves as a crucial component in financial modeling. It provides the probability that a random variable will assume a value less than or equal to the input provided to the CDF. This aids in assessing the likelihood of various financial events and outcomes. In the context of option pricing, the variables (\(d_{1}\) and \(d_{2}\)) play a pivotal role. As these variables increase in value, so does the corresponding cumulative distribution function \(N(d_{1})\), and \(N(d_{2})\) respectively. This, in turn, directly impacts the valuation of the option. Additionally, as the underlying asset's price (\(S_{t}\)) experiences an increase, the option's intrinsic value also rises, thereby resulting in potential gains associated with the exercise of the option. These dynamics underscore the critical relationship between the various parameters involved in option pricing and the potential financial outcomes. Volatility (\(\sigma\)) is a crucial factor in option pricing. The presence of volatility in both the numerator and denominator of the BSM formula reflects its importance in determining the option's price. The square of volatility in the numerator is associated with the volatility's effect on the stock's expected drift over time. Higher volatility leads to larger potential price movements, which results in a higher expected return and therefore a higher option price. BSM model assumes constant volatility over time, which may not always be an accurate representation of real-world markets. The implied volatility, which represents market expectations of future volatility, can vary across different strike prices of options with the same expiration date. This leads to the observation of a volatility skew when implied volatilities are graphed against strike prices. These shortcomings of the BSM have led some researchers to place more importance on historical volatility as opposed to implied volatility (e.g., [10]). The underlying lognormal distribution in BSM is frequently used to simplify the behavior of stock prices over time. Researchers have solved the problem using various analytical and numerical methods (e.g., [11], [12], [13], [3], etc.). Many models now in use, however, make rigid assumptions, such as ideal markets, constant risk-free rates and volatility, a lognormal distribution of share price dynamics, the absence of dividends, and continuous delta hedging. ## II Problem Formulation Our objective is to present an integrated model that combines the FOBSM with a NN to predict option prices more reliably. Considering the variables: * \(C=\) Option price as a function of the underlying asset price S and time to expiry t, * \(C_{obs}=\) actual prices for a set of options. * \(S=\) underlying asset prices corresponding to the observed option prices at time t. * \(\theta=\) Fractional order parameters with respect to underline price characterizing the fractional diffusion process in the FOBSM. * \(\alpha\)= Fractional order parameter with time * \(N=\) Neural Network with parameters * \(\mathrm{W}=\) weights and biases. * \(C_{pred}=\) predicted option prices generated by the integrated model. * \(TC\): Transaction costs associated with buying or Because of TC, investors are deterred from trading when market impulses are prevalent. Thus, TCs are an important consideration in financial markets and can lead to non-linear dynamic adjustments in option prices [14]. Eq. (3) is a stochastic differential equation describes how the variable S normally moves in a geometric Brownian motion: \[dS(t)\ =\ rS(t)dt\ +\ \sigma S(t)dW(t) \tag{3}\] where, \(r=\) risk free interest, \(\sigma=\) volatility of the stock returns, \(dW=\) Wiener process (Brownian motion). The assumption of BSM's lognormal diffusion can be expressed by Eq. (3) as well. We introduce a set of unknown parameters \(\Phi=(\Phi_{1},\Phi_{2},\ldots,\Phi_{k})\) that influence the functions \(\mu=\mu_{\phi}\) and \(\sigma=\sigma_{\phi}\) in the stochastic model. These parameters are estimated to maximize the log-likelihood function as displayed in \(d_{1}\) and \(d_{2}\) in Equations (1) & (2) which help determine the best-fit values based on observed data. Thus, our goal is to develop a model that considers transaction costs, the stochastic nature of asset price movements, and unknown parameters to make predictions that better reflect real-world market dynamics, including skewness, kurtosis, and volatility skew. ## III Fractional Order Black-Scholes Model (FOBSM) To achieve the goal, we introduce a time-fractional BSM by employing Riemann-Liouville fractional derivatives within the framework of partial differential equations (PDEs). The Riemann-Liouville mathematical tool facilitates the computation of fractional derivatives. It plays a vital role in capturing the intricate dynamics of financial data, particularly when dealing with long memory, fractal behavior, or non-Gaussian distributions. Following the introduction of the traditional BSM, PDEs theory and methodology started to gain popularity for the research of option pricing issues. Several researchers have emphasized the study of fractional differential equations (e.g., [15]; [16]; etc.). Eq. (4) presents the option price using the BSM equation. \[C_{\text{FBM}}(S,K,T,r,\sigma)=\text{ Ke}^{-rT}N(-d_{2})-SN(-d_{1}) \tag{4}\] FOBSM is given by Eq. (5), which extends the partial differential equations by applying fractional derivatives with both \(1^{st}\) order and \(2^{nd}\) order derivatives: \[\frac{\partial^{\alpha}C}{\partial t^{\alpha}}+\tau S\frac{\partial^{\alpha}C }{\partial S\theta}+\frac{1}{2}\sigma^{2}S^{2}\frac{\partial^{2\theta}C}{ \partial S^{2\theta}}-rC-TC(t)=0 \tag{5}\] \[where,0<\alpha<1,S\geq 0,t\geq 0\ and\ t\in[0,T],where\ 0\] \[<\theta<1\] Eq. (5) is the continuous form, where \(\partial^{\alpha}C/\partial t^{\alpha}=\) fractional time derivative of the option price C with respect to time t, where \(\alpha=\) order of the time fractional derivative. This portion of our work is based on the research work [17], which derived a numerical scheme of second order in space. Eq. 6 displays the fractional time derivative. \[\frac{\partial^{\alpha}C}{\partial t^{\alpha}}=\frac{1}{r(1-\alpha)}\int_{0}^{ t}(t-\tau)^{-\alpha}\frac{\partial C}{\partial r}d\tau \tag{6}\] The FOBSM equation (Eq. 5) with Riemann-Liouville fractional derivatives becomes: \[\frac{1}{r(1-\alpha)}\int_{0}^{t}(t-\tau)^{-\alpha}\frac{\partial c}{ \partial\tau}d\tau+\tau S\frac{\partial^{\alpha}C}{\partial S\theta}+\frac{1} {2}\sigma^{2}S^{2}\frac{\partial^{2\theta}C}{\partial S^{2\theta}}-rC-TC(t)=0 \tag{7}\] where, \(0<\alpha<1,S\geq 0,t\geq 0\ and\ t\in[0,T],0<\theta<1\) Eq. 8 displays the discretize form of this using finite difference: \[\frac{\partial^{\alpha}C}{\partial t^{\alpha}}\approx\frac{1}{r(1-\alpha)} \sum_{k=0}^{i-1}(t_{1}-t_{k})^{-\alpha}(\Delta C_{k})\,\text{u} \tag{8}\] Where, t = current time step, \(t_{i}=\) current time, \(\Delta t=\) time step size, \(\Delta C_{k}=\) change in C from time \(t_{k}\) to \(t_{k+1}\). The fractional derivative of order \(\theta\) approximated as: \[\frac{\partial^{\theta}C}{\partial S\theta}\approx D_{S}^{\theta}C_{i,j} \tag{9}\] where \(D_{S}^{\theta}\) is fractional difference operator. Contrary to integer-order differential operators, which are local, fractional-order differential operators are nonlocal, allowing a system's next state to depend on both its present state and its past state ([18], [19]). When we add fractional derivatives to the Black-Scholes-Merton model, we are using fractional-order differential operators. ### _Stationarity assumptions_ The stationarity assumption is a fundamental concept in time series analysis and stochastic processes. In the context of financial modeling, including the BSM model and its extensions, stationarity assumptions are important considerations. #### Iii-A1 Fractional BSM Model and Stationarity Fractional calculus deals with derivatives and integrals of non-integer orders. It extends the traditional concepts of differentiation and integration to include fractional or non-integer orders. Though fractional calculus allows for the incorporation of non-standard diffusion phenomena, including long memory and volatility clustering; however, the degree of non-stationarity introduced depends on the choice of fractional orders and the modeling assumptions, so the level of stationarity vs. non-stationarity can vary in practice. In this case, the selection of fractional orders (\(\alpha\) and \(\theta\)) in the fractional calculus equations is a crucial decision. Different values of these can lead to varying degrees of non-stationarity and memory effects in the model. We need to calibrate these parameters based on the specific characteristics of the data. Thus, when introducing fractional derivatives to the BSM model, the assumption of stationarity becomes more flexible. ## IV Neural Network Integration The ability of neural networks to approximate the relationship between multiple Black-Scholes parameters and the ultimate option price has been established by researchers ([20], [21]). The growing utilization of neural networks as function approximators [22] and numerical solvers has opened new horizons in the fields of machine learning and numerical analysis ([23], [24]). Building upon these foundational contributions, a comprehensive literature review was presented [25] which reveals that neural networks have been employed in option pricing since the early 1990s. Neural networks, particularly those employing the Universal Approximation-Rectified Linear Unit (ReLU), possess the capability to approximate any continuous function within bounded subsets of real numbers [26]. Furthermore, empirical evidence suggests that neural networks often outperform the Black-Scholes model in many scenarios [27]. Notably, neural networks tend to excel in stable market conditions, whereas the Black-Scholes model exhibits superiority in more volatile market environments [28]. These findings have served as compelling motivation for the integration of neural networks into our research study. Fig. 2 displays the convergence of the mean squared error (MSE) for the integrated model using a different optimizer (Adam, SGD, RMSprop). During training, each optimizer adjusts the model's weights to reduce the MSE between the predicted and actual option prices. \begin{table} \begin{tabular}{l} function fractional,derivative(C, alpha, delta,t): \\ n = length(C) \\ result = array of zeros with the same length as C \\ for i from 1 to n - 1: \\ integral,sum = 0.0 \\ for k from 0 to i : \\ integral,sum = integral,sum + ([i - k) \(\wedge\) [-alpha]) * C[k] \\ result[i] = (1 / gamma(1 - alpha)) * integral,sum * (delta,t \(\wedge\) (-alpha))) \\ return result \\ \end{tabular} \end{table} Table 1: Pseudocode (Riemann-Liouville fractional derivatives) From the plots, we can see ADAM consistently results in a lower MSE and converges more quickly; it can be considered more effective for this specific problem. However, we have used a custom loss function, which combines both mean squared error (MSE) loss and a BSM-based loss. ## V Model architecture and Loss We simulated realistic financial scenarios to generate synthetic with the key parameters S, K, T, r, \(\sigma\) and \(\theta\). These parameters vary within predefined ranges to create diverse data points. The fractional BSM introduces two fractional orders: \(a\) (for time) and \(\theta\) (for spatial derivatives). ### _Fractional Derivative Implementation_ We implement fractional derivatives using the Riemann-Liouville fractional derivative numerical approximation. It iterates over points in the time domain and computes the left Riemann-Liouville fractional derivative for each point based on the generated data. ### _Discretization Process_ To calculate the fractional derivative numerically, we discretized the integral in the Riemann-Liouville formula. For each data point, the code computes option prices using both the fractional Black-Scholes formula and the traditional Black-Scholes formula. The fractional Black-Scholes formula mitigates issues related to singularity and avoids division by zero by adding a small constant (\(\epsilon\)). Three key features for each data point were extracted: * The last value of the option price * The last value of the fractional time derivative * The last value of the fractional spatial derivative Normalization is performed on these features by subtracting the mean and dividing by the standard deviation to ensure that features have similar scales. We design and construct a simple feedforward neural network (NN) to test our hypothesis. The architecture encompasses an initial input layer comprised of two neurons. These two neurons are dedicated to encoding the essential information regarding the normalized fractional time derivative and fractional spatial derivative, both of which are integral components of this model. Within the NN, there are two subsequent hidden layers, each of considerable depth, housing 64 neurons in each layer. These hidden layers are pivotal in the neural network's ability to capture intricate patterns and relationships within the data. To facilitate the activation of these hidden neurons, Rectified Linear Unit (ReLU) activation functions have been employed. The predictive capability is realized through the presence of an output layer with a singular neuron. This singular neuron serves as the neural network's interface for generating predictions related to the anticipated option prices, thereby encapsulating the core objective of the study. ### _Loss function_ The NN compiled using the Adam optimizer and mean squared error (MSE) loss function. \[\text{MSE}=\tfrac{1}{n}\sum_{i=1}^{n}(\hat{\mathcal{Y}}_{i}-\text{y}_{i})^{2} \tag{10}\] The network trained using the training data for 500 epochs. The batch size is set to 32, and 20% of the training data is used as a validation set. Early stopping is employed to prevent overfitting, monitoring the validation loss for improvement. Fig. 2 & 3 display the training - validation loss and actual vs predicted option pricing, respectively. To this end, this article presents a novel approach to option pricing that combines fractional calculus, numerical methods, adaptive techniques, and neural networks. Based on the theoretical foundation and experiments with synthetic data, this approach is likely to improve the accuracy of predicting option prices by accounting for memory, long-term dependencies, and complex behaviors. It also adds a data-driven element, capturing intricate financial data patterns and offering an alternative perspective on option pricing. Fig. 1: Comparison of different optimizers. Fig. 3: True vs Predicted option prices. Fig. 2: Learning curve. The model is trained and tested on synthetic data. While testing on synthetic data can help assess how well the model performs under controlled conditions, it is essential to validate the model's performance on real financial data which is the future direction beyond the scope of this work. ## VI Limitations & future direction While the work introduces a novel and promising approach to option pricing, it should be seen as a starting point for further research and refinement. It is theoretical in nature and focuses on integrating mathematical and computational techniques. The model's performance needs to be validated against real-world option pricing scenarios and historical data to assess accuracy and robustness. The integration involves tuning multiple parameters, including the trade-off parameter (\(\lambda\)) and neural network architecture and optimization parameters. Finding the optimal combination of these parameters can be challenging and time-consuming. Practitioners often use cross-validation, grid search, random search, or Bayesian optimization to systematically explore the parameter space and identify a reasonable set of parameters to solve these difficulties. FOBSM's accuracy is required to be empirically evaluated using historical data. The financial industry is known for its conservative approach to adopting new models and technologies. Investigating how well the proposed model can be integrated into existing financial systems and regulatory frameworks is crucial for its real-world adoption. ## VII Conclusion This study marks a substantial advancement in the pursuit of greater precision in option pricing models. Through the fusion of mathematical rigor and computational prowess, our objective has been to diminish the divide between theoretical models and the intricate realities of financial markets. It is imperative to acknowledge that our scholarly voyage remains an ongoing endeavor. The trajectory toward refining option \begin{table} \begin{tabular}{l} \hline \hline \multicolumn{2}{l}{**fractional derivative using Riemann-Liouville method***} \\ def fractional_derivative(C, alpha, delta_t): \\ n = len(C) \\ result = np.zeros\_like(C) \\ for i in range(1, n): \\ integral\_sum = 0.0 \\ for k in range(i): \\ integral\_sum = ((i - k) ** (- alpha)) * C[k] \\ result[i] = (1 / gamma(1 - alpha)) * integral\_sum * (delta\_t ** (- alpha))) \\ return result \\ \multicolumn{2}{l}{**synthetic data***} \\ num\_data\_points = 1000 \\ S = np.random.uniform(50, 150, num\_data\_points) \\ K = np.random.uniform(50, 150, num\_data\_points) \\ T = np.random.uniform(01, 1.0, num\_data\_points) \\ r = np.random.uniform(0.01, 0.05, num\_data\_points) \\ sigma = np.random.uniform(0.1, 0.5, num\_data\_points) \\ \multicolumn{2}{l}{**option prices using a time and price fractional BSM***} \\ alpha\_price = 0.7 \\ alpha\_time = 0.5 \\ option\_prices = np.zeros((num\_data\_points,)) \\ fractional\_price derivatives = np.zeros((num\_data\_points,)) \\ fractional\_time\_derivatives = np.zeros((num\_data\_points,)) \\ for i in range(num\_data\_points): \\ t = np.linspace(0, T[i], 1000) \\ delta\_t = {i[1] - [0]} \\ S0 = [S[i] \\ KO = K[i] \\ t0 = {f[i]} \\ sigma0 = sigma[i] \\ epsilon = 1e-10 \\ if sigma0 \textless{epsilon or ([-1] \textless{epsilon}:}\) \\ continue \\ \multicolumn{2}{l}{**option price using the BSM***} \\ d1 = (np.log(S0 / (K0 + epsilon)) + (t0 + (sigma0 ** 2) / 2) * t) / \\ (sigma0 * np.sqrt(t)) \\ d2 = d1 - sigma0 * np.sqrt(t) \\ option\_price = ( \\ KO * np.exp(-t0 * t) * norm.cdf(-d2) - S0 * norm.cdf(-d1)) \\ \multicolumn{2}{l}{**fractional price derivative for this data point***} \\ fractional\_price\_deriv = fractional\_derivative(option\_price, \\ alpha\_price, delta\_t) \\ \multicolumn{2}{l}{**fractional time derivative for this data point***} \\ fractional\_time\_deriv = fractional\_derivative(option\_price, \\ alpha\_time, delta\_t) \\ option\_prices[i] = option\_price[-1] \\ fractional\_price\_derivatives[i] = fractional\_price\_deriv[-1] \\ fractional\_time\_derivatives[i] = fractional\_time\_deriv[-1] \\ \multicolumn{2}{l}{**Normalize the data***} \\ mean option prices\_ = option\_prices.mean() \\ std\_option\_prices = option\_prices.std() \\ mean price derivatives = fractional\_price\_derivatives.mean() \\ std\_price\_derivatives = fractional\_price\_derivatives.std() \\ mean time\_derivatives = fractional\_time\_derivatives.mean() \\ std\_time\_derivatives = fractional\_price\_derivatives.std() \\ mean time\_derivatives = fractional\_time\_derivatives.mean() \\ std\_time\_derivatives = fractional\_time\_derivatives.std() \\ \multicolumn{2}{l}{**normalized\_option\_prices = (option\_prices - mean\_option\_prices) / std\_option\_prices - (fractional\_price\_derivatives - (fractional\_price\_derivatives) / std\_price\_derivatives - (fractional\_price\_derivatives) / std\_time\_derivatives - (fractional\_price\_derivatives) / pricing is a dynamic and ever-evolving domain within research.
2308.06987
Deep convolutional neural networks for cyclic sensor data
Predictive maintenance plays a critical role in ensuring the uninterrupted operation of industrial systems and mitigating the potential risks associated with system failures. This study focuses on sensor-based condition monitoring and explores the application of deep learning techniques using a hydraulic system testbed dataset. Our investigation involves comparing the performance of three models: a baseline model employing conventional methods, a single CNN model with early sensor fusion, and a two-lane CNN model (2L-CNN) with late sensor fusion. The baseline model achieves an impressive test error rate of 1% by employing late sensor fusion, where feature extraction is performed individually for each sensor. However, the CNN model encounters challenges due to the diverse sensor characteristics, resulting in an error rate of 20.5%. To further investigate this issue, we conduct separate training for each sensor and observe variations in accuracy. Additionally, we evaluate the performance of the 2L-CNN model, which demonstrates significant improvement by reducing the error rate by 33% when considering the combination of the least and most optimal sensors. This study underscores the importance of effectively addressing the complexities posed by multi-sensor systems in sensor-based condition monitoring.
Payman Goodarzi, Yannick Robin, Andreas Schütze, Tizian Schneider
2023-08-14T07:51:15Z
http://arxiv.org/abs/2308.06987v1
# Deep convolutional neural networks for cyclic sensor data ###### Abstract Predictive maintenance plays a critical role in ensuring the uninterrupted operation of industrial systems and mitigating the potential risks associated with system failures. This study focuses on sensor-based condition monitoring and explores the application of deep learning techniques using a hydraulic system testbed dataset. Our investigation involves comparing the performance of three models: a baseline model employing conventional methods, a single CNN model with early sensor fusion, and a two-lane CNN model (2L-CNN) with late sensor fusion. The baseline model achieves an impressive test error rate of 1% by employing late sensor fusion, where feature extraction is performed individually for each sensor. However, the CNN model encounters challenges due to the diverse sensor characteristics, resulting in an error rate of 20.5%. To further investigate this issue, we conduct separate training for each sensor and observe variations in accuracy. Additionally, we evaluate the performance of the 2L-CNN model, which demonstrates significant improvement by reducing the error rate by 33% when considering the combination of the least and most optimal sensors. This study underscores the importance of effectively addressing the complexities posed by multi-sensor systems in sensor-based condition monitoring. Predictive maintenance, hydraulic system, deep learning, convolutional neural network ## I Introduction Industrial systems and factories operate continuously, necessitating uninterrupted performance to avoid process downtime, significant financial losses, and potential safety hazards. To mitigate these risks, companies employ various maintenance approaches, including corrective maintenance, preventive maintenance, and predictive maintenance. Predictive maintenance (PdM) heavily relies on monitored signals from diverse sensors, with machine learning methods playing a pivotal role in data-driven PdM. These methods can be categorized into two groups: conventional approaches and deep learning techniques. Conventional methods involve preprocessing, feature extraction (FE), feature selection (FS), and the subsequent application of classification or regression algorithms [1], commonly referred to as FESC/FESR in this study. In contrast, modern deep neural networks have demonstrated exceptional performance across various applications, including PdM [2, 3, 4]. In line with these advancements, gas mixture measurement has emerged as a promising application for deep neural networks in recent research. Notably, Robin et al. [5] introduced a convolutional neural network (CNN) specifically designed for indoor air quality monitoring (TCOCNN), accurately predicting volatile organic compounds using temperature-cycled operation sensors. The proposed method surpassed existing data evaluation techniques, underscoring the effectiveness of CNNs in this domain. It is worth noting that the signals utilized in their study bear resemblance to the typical data encountered in condition monitoring and predictive maintenance applications, i.e. multiple sensors with periodic or cyclic data. Motivated by the aforementioned findings, the objective of our study is to compare our previously published method, TCOCNN, with a benchmark method in a different application context. To achieve this, we utilize a publicly available dataset from a hydraulic system testbed [6]. Recent research has applied various deep learning techniques to the dataset under investigation [7, 8, 9, 10, 11]. Prakash et al. [7] employed a 1D CNN model to analyze the pressure difference between two pressure sensors. Huang et al. [12] took a parallel approach by utilizing multiple independent convolutional neural networks to extract features from individual sensors. Furthermore, Berghout et al. [10] introduced a novel neural network model specifically designed to process the extracted features. In a distinct approach, Zhang et al. [9] demonstrated the application of a Transformer model with self-attention, originally trained on natural language, to the task of sensor fusion. Collectively, these studies contribute to the exploration of diverse methodologies for analyzing sensor data and extracting meaningful insights. The primary goal of our comprehensive evaluation is to assess the performance of the air quality model when applied to the field of condition monitoring. In doing so, we aim to address potential challenges and difficulties associated with multiple
2308.09444
An Efficient 1 Iteration Learning Algorithm for Gaussian Mixture Model And Gaussian Mixture Embedding For Neural Network
We propose an Gaussian Mixture Model (GMM) learning algorithm, based on our previous work of GMM expansion idea. The new algorithm brings more robustness and simplicity than classic Expectation Maximization (EM) algorithm. It also improves the accuracy and only take 1 iteration for learning. We theoretically proof that this new algorithm is guarantee to converge regardless the parameters initialisation. We compare our GMM expansion method with classic probability layers in neural network leads to demonstrably better capability to overcome data uncertainty and inverse problem. Finally, we test GMM based generator which shows a potential to build further application that able to utilized distribution random sampling for stochastic variation as well as variation control.
Weiguo Lu, Xuan Wu, Deng Ding, Gangnan Yuan
2023-08-18T10:17:59Z
http://arxiv.org/abs/2308.09444v2
An Efficient 1 Iteration Learning Algorithm for Gaussian Mixture Model And Gaussian Mixture Embedding For Neural Network ###### Abstract We propose an Gaussian Mixture Model(GMM) learning algorithm, based on our previous work of GMM expansion idea. The new algorithm brings more robustness and simplicity than classic Expectation Maximization (EM) algorithm. It also improves the accuracy and only take 1 iteration for learning. We theoretically proof that this new algorithm is guarantee to converge regardless the parameters initialisation. We compare our GMM expansion method with classic probability layers in neural network leads to demonstrably better capability to overcome data uncertainty and inverse problem. Finally, we test GMM based generator which shows a potential to build further application that able to utilised distribution random sampling for stochastic variation as well as variation control. GMM Density approximation Neural Network Expectation Maximization Inverse Problem Embedding ## 1 Introduction The inducement of events are varied and regularly alter throughout the real application process, which frequently results in different modes of data, i.e., a large shift in the mean value and covariance of the data. For linear regression modeling, it is standard procedure to separate the observable data into various components, and then to perform a weighted combination based on the posterior probability that the data belong to each component. The work of a Belgian astronomer, mathematician, statistician, and sociologist named Quitelet [34] suggested the potential of dissecting typical mixes into their component parts as early as 1846. Holmes [13] was another early scholar who emphasized mixing. He made the argument that using a single average to gauge the wealth disparity was insufficient, therefore he created the idea of population mixture. Dating back 130 years, Pearson[32], a famous biometrician, statistician and eugenicist, combined two normal probability density functions with different means and different variances to fit the crab data provided according to his observation of the biological data. This is the first major analysis involving mixture models. The research and application of probability distribution began in the same period. Pioneering work in this area included the work of a generalized theory by Newcomb [31] and the work by Pearson[32]. After this, aside from some contributions by Jeffreys[17] and Rao[36], the use of maximum likelihood methods (ML) to fit mixed models did not receive enough attention until the 1960s. Day and Wolfe [8, 49]have published a number of technical reports on iterative schemes for ML methods of mixed distribution fitting. Sadly, this approach has not yet been able to produce a formal iterative scheme, and its convergence has not yet been demonstrated. Successfully, Dempster et al.[10] used their famous expectation maximization (EM) algorithm to formalize this iterative scheme in general, which solved the problem and established the convergence of ML solutions of mixed problems on a theoretical basis. The creation of EM algorithm catalyzes the application and extensive research of finite mixture models. It has developed for nearly 100 year, Stigler [42] provides an absorbing account of this early work on mixtures. Later, New Combing proposed an iterative reweighting scheme, which can be seen as an application of the Expectation Maximization algorithm(EM). With development, many normal mixture model extensions show remarkable results. Moreover, many mixture models for different problems are widely used. Such as, exponential mixture model[30], t-distribution expansion model[5] and many normal mixture model modification and improvement methods[2, 4, 18, 40, 47, 50]. Among them, the classical Gaussian mixture model is a weighted combination of multiple Gaussian distributions, which is widely used in complex and huge data. Because such models are not only suitable for a wide range of multimodal models, but also have the advantage of simplicity and speed in calculation. However, due to the complexity of image data, financial data or industrial data, the data obtained by observing them are often too large to directly classify the components accurately. Therefore, it is necessary to extract features from observation data in advance. Then more convincing results can be obtained through the division of multiple modes and weighted integration modeling in the hidden variable space. In order to find the optimal solution of the GMM fit, the most classical practice is to employ the expectation maximization algorithm (EM) to compute estimates of these unknown parameters. According to the eigenvalue decomposition law, any full covariance matrix can be represented by its eigenvalues and eigenvectors. We can see that to convert the diagonal matrix to the full covariance matrix, we only need to construct the orthogonal matrix in it. So the EM algorithm can fit the GMM quickly and accurately. However, this algorithm still has problems that need to be overcome. First, the iterative nature of the EM algorithm makes it very dependent on the initial input values. The selection of the initial value has a great impact on the fitting results[4, 6, 25, 28, 33, 38], so the observation and analysis of the data before the iteration are highly demanding. Second, the EM algorithm is easy to fall into local optimal values [1, 9, 41]. According to its convex function gradient descent convergence[3, 20, 21], the basic EM algorithm is easy to fall into local extreme values and has poor fault tolerance. Third, EM does not perform well on functions with extreme or mixed features. EM algorithm based on Gaussian mixture is not suitable for fitting sharp or even discontinuous functions. Therefore, we need to seek convergence calculation methods with wider adaptability. With a high-fidelity output mixture model estimated from the input mixture model, the GMMs can be used for non-Gaussian uncertainty propagation. Determining the best number of components and weights is often discussed by scholars, although each Gaussian component can be easily propagated by moment matching methods. Terejanu et al.[43] showed that the weights of Gaussian components can be assumed to be invariant by nonlinear mapping if and only if their variance tends to infinity. They also proposed two optimization schemes based on quadratic programming for the weight update problem in nonlinear uncertainty propagation[44]. Within the next two or three years, Faubel et al. developed a Gaussian mixture filter that recursively splits each filter into a fixed number of unscented Kalman filters to deal with non-Gaussian noise[11]. Horwood et al.[15] established a segmentation scheme by comparing Gaussian moments obtained using Gauss-Hermite quadrature estimates. Similarly, Huber[16] designed a nonlinear filter to segment the Gaussian density based on the component weights and traces of the covariance matrix. Vishwajeet et al. proposed a Gaussian mixture uncertainty propagation scheme with weight updating and splitting based on the numerically calculated error of the Kol-mogorov equation[48]. Tuggle et al. proposed a filter scheme that assessed the nonlinearity by Kullback-Leibler divergence between two Gaussian distributions of first-order and second-order extended Kalman filters, and then split the distribution along characteristic directions that choose large[45] along both the Jacobian and the derivative of the directional variance. In our previous work[27], we proposed a GMM model structure to expand arbitrary unknown densities which inspired by Fourier expansion. A simple learning method is introduced to learn GMMs. Our learning algorithm's advantage is that it is not likelihood-based, allowing us to avoid drawbacks like many critical points and the local minimum problem associated with likelihood-based methods. We extend our earlier work[27] in this paper. A novel algorithm is created with a clearer mathematical justification. In our earlier work, we demonstrated that, in terms of probability, GMM density estimation could be as accurate as frequency distribution estimation. In this study, we offer a more substantial mathematical demonstration that GMM can estimate a large set of density even in high-dimensional situations like mixed density with multivariate facets. In other words, the GMM's performance in estimating arbitrary density could always be relied upon. While estimating density, it could be used as a generalizing technique. The performance of our approach is demonstrated by experiments in both 1 and 2 dimensional examples. Additionally, we were able to map any density using independent normals and a multilayer perceptron (MLP) network using our technique. This is especially useful for stochastic processes, among many other applications. Diffusion models, for instance, use the diffusion process to transform latent variables into a Normal distribution before gradually reverting to the original latent distribution. We could gain more control of the latent domain using this straightforward strategy. An Decoder Network(autoencoder) is used to test the effectiveness of our embedding strategy. Complete embedding technique is provided in section 5. Section 2 provides preliminary which state the general notation and related theorems. Section 3 provides our prove of generality of GMMs as density estimation. Section 4 provides our 1 iteration GMM learning algorithm with proof and experiments. Section 5 introduce our GMM embedding technique and neural network experiment. The final section provides a summary and conclusions. ## 2 Preliminary ### Gaussian Mixture Model(GMM) The classical Gaussian mixture model is widely used in clustering problems. Its essence is to represent the distribution density function of sample points with the weighted average sum of several Gaussian functions. For data obtained \(x\in\mathbb{R}^{D}\), the weight of the \(n\)-th Gaussian \(\pi_{n}\), mean vector \(M_{n}\in\mathbb{R}^{D}\), covariance matrix \(\Sigma_{n}\in\mathbb{R}^{+D}\times\mathbb{R}^{+D}\) and \(N,D\in\mathbb{N}^{+}\), \[G(x)=\sum_{n=1}^{N}\pi_{n}\phi(x;M_{n},\Sigma_{n}). \tag{1}\] Among them, \(\phi\) is noted as the normal distribution. According to the definition of GMM, it is essentially a probability density function. The integrals of the probability density function over its scope must sum to 1. The probability density function of the whole GMM is linearly added by the probability density functions of several Gaussian components, and the integral of the probability density function of each Gaussian component must be 1. Therefore, in order to make the probability density integral of the whole GMM equal to 1, each Gaussian component must be assigned a weight whose value is not greater than 1, and the sum of the weights is 1. In other words, \[\sum_{n=1}^{N}\pi_{n}=1. \tag{2}\] ### EM algorithm In order to use the maximum a posteriori probability method to determine which Gaussian distribution each pixel belongs to, we need to estimate the unknown parameters in the model. Here we show how to use the expectation maximization method (EM) to get estimates for these unknown parameters. Calculate the probability of the model \(G(x)=P(x|\Theta)\), \(P(x|\Theta)\) is the joint probability of the data \(x\) given by the parameter \(\Theta=(\theta,M,\Sigma)\) where \(\theta=(\pi_{1},\pi_{2},\ldots,\pi_{N})\), \(M=(M_{1},M_{2},\ldots,M_{N})\) and \(\Sigma=(\Sigma_{1},\Sigma_{2},\ldots,\Sigma_{N})\). As for hidden data, \(\gamma_{dn}\) is usually defined as \[\gamma_{dn}=\begin{cases}1,&\text{The d-th observation is derived from the n-th model,}\\ 0,&\text{otherwise.}\end{cases}\] So the hidden data of an observation \(x_{d}\) is \(\gamma_{d}=(\gamma_{d1},\gamma_{d2},\ldots,\gamma_{dN})\). For \(\gamma=(\gamma_{1},\gamma_{2},\ldots,\gamma_{D})\), the full likelihood function is \[P(x,\gamma|\Theta)=\prod_{n=1}^{N}\prod_{d=1}^{D}\left[\pi_{n}\phi(x_{d}|M_{n},\Sigma_{n})\right]^{\gamma_{dn}}. \tag{3}\] However, it is very difficult to directly differentiate unknown parameters above. In general, we need to convert multiple multiplications in the likelihood function into multiple additions. Then the logarithm is equal to \[\begin{split}\log(P(x,\gamma|\Theta))&=\log(\prod_{n=1 }^{N}\prod_{d=1}^{D}\left[\pi_{n}\phi(x_{d}|M_{n},\Sigma_{n})\right]^{\gamma_{dn }})\\ &=\sum_{n=1}^{N}(\sum_{d=1}^{D}\gamma_{dn}\log\pi_{n}+\sum_{d=1}^{ D}\gamma_{dn}\log(\phi(x_{d}|M_{n},\Sigma_{n})).\end{split} \tag{4}\] Because the natural logarithm function is strictly monotonically increasing, the logarithm likelihood function and the likelihood function can be maximized at the same time. Its extreme point is the estimated value of the unknown parameter in the Gaussian mixture model. Then the em algorithm can be iterated from this function. E-step: \[E(\log(P(x,\gamma|\Theta))=\sum_{n=1}^{N}(\sum_{d=1}^{D}E(\gamma_{dn})\log\pi_ {n}+\sum_{d=1}^{D}E(\gamma_{dn})\log(\phi(x_{d}|M_{n},\Sigma_{n})) \tag{5}\] To make it more concise and clear that let \[\Gamma_{dn}=E(\gamma_{dn}|x_{d},\Theta)=\frac{\pi_{n}\phi(x_{d}|M_{n},\Sigma_ {n})}{\sum_{n=1}^{N}\pi_{n}\phi(x_{d}|M_{n},\Sigma_{n})}, \tag{6}\] and \[e_{n}=\sum_{d=1}^{D}E(\gamma_{dn}). \tag{7}\] Then the step can be rewritten as \[\begin{split} Q(\Theta,\Theta^{i})&=\sum_{\gamma}P (\gamma|x,\Theta^{i})\log(P(x,\gamma|\Theta))\\ &=E_{\gamma}(\log(P(x,\gamma|\Theta)|x,\Theta^{i})\\ &=E_{\gamma|x,\Theta^{i}}(\log(P(x,\gamma|\Theta))\\ &=\sum_{n=1}^{N}(e_{n}\log\pi_{n}+\sum_{d=1}^{D}E(\gamma_{dn}) \log(\phi(x_{d}|M_{n},\Sigma_{n}))\end{split} \tag{8}\] M-step: \[\Theta^{i+1}=\arg\max_{\Theta}Q(\Theta,\Theta^{i}). \tag{9}\] Taking the derivative of \(Q(\Theta,\Theta^{i})\) yields the partial derivative of each unknown quantity, we can make its partial derivative equal to 0. Then \[\begin{split} M_{n}^{new}&=\frac{\sum_{d=1}^{D} \Gamma_{dn}x_{d}}{\sum_{d=1}^{D}\Gamma_{dn}},\\ \Sigma_{n}^{new}&=\frac{\sum_{d=1}^{D}\Gamma_{dn}(x_ {d}-M_{n})^{-1}\Sigma^{-1}(x_{d}-M_{n})}{\sum_{d=1}^{D}\Gamma_{dn}},\\ \pi_{n}^{new}&=\frac{\sum_{d=1}^{D}\Gamma_{dn}}{D}, \end{split} \tag{10}\] Thus, given an initial value, we can iterate back and forth to find the value content. It is generally known that the EM algorithm has a convergence property. Actually, from the conditional probability, we can get: \[p(x|\theta)=\frac{p(x,\gamma|\theta)}{p(\gamma|x,\theta)}, \tag{11}\] and \[\log p(x|\theta)=\log p(x,\gamma|\theta)-\log p(\gamma|x,\theta). \tag{12}\] As we set above about \(Q(\theta,\theta^{i})\), we can also let \(H(\theta,\theta^{i})=\sum_{\gamma}p(\gamma|x,\theta^{i})\log p(\gamma|x,\theta)\), which lead to \[\begin{split} Q(\theta,\theta^{i})-H(\theta,\theta^{i})& =\sum_{\gamma}p(\gamma|x,\theta^{i})\log p(x,\gamma,\theta)-\sum_ {\gamma}p(\gamma|x,\theta^{i})\log p(\gamma|x,\theta)\\ &=\sum_{\gamma}p(\gamma|x,\theta^{i})\log\frac{p(x,\gamma|\theta )}{p(\gamma|x,\theta)}\\ &=\sum_{\gamma}p(\gamma|x,\theta^{i})\log p(x|\theta)\\ &=\log p(x|\theta).\end{split} \tag{13}\] Then the iteration can be expressed as \[\begin{split}\log p(\theta,\theta^{i+1})-\log p(\theta,\theta^{i} )&=Q(\theta^{i+1},\theta^{i})-H(\theta^{i+1},\theta^{i})-(Q( \theta^{i},\theta^{i})-H(\theta^{i},\theta^{i}))\\ &=Q(\theta^{i+1},\theta^{i})-Q(\theta^{i},\theta^{i})-(H(\theta ^{i+1},\theta^{i})-H(\theta^{i},\theta^{i})),\end{split} \tag{14}\] where \(Q(\theta^{i+1},\theta^{i})-Q(\theta^{i},\theta^{i})>0\) and \[H(\theta^{i+1},\theta^{i})-H(\theta^{i},\theta^{i})=\sum_{\gamma}p(\gamma|x, \theta^{i+1})\log p(\gamma|x,\theta)-\sum_{\gamma}p(\gamma|x,\theta^{i})\log p (\gamma|x,\theta)=\log 1=0.\] So we can see that \(p(x|\theta^{i+1})>p(x|\theta^{i})\). Combine with \(p(x|\theta)\) has an upper bound \(1\), we have a lemma follow: **Lemma 1**: _As \(p(x|\theta^{i+1})>p(x|\theta^{i})\) and \(p(x|\theta)\) is bounded, there is a supremum \(A\) satisfying (1)/\(\forall i\in N^{+}:\log p(x|\theta^{i})\leq A\). (2)/\(\forall\varepsilon>0,\exists\log p(x|\theta^{i_{0}})>A-\varepsilon\). For \(i>i_{0}\), we have \(A-\varepsilon<\log p(x|\theta^{i_{0}})\leq\log p(x|\theta^{i})\leq A\) that \(|\log p(x|\theta^{i})-A|<\varepsilon\) and_ \[\lim_{i\rightarrow\infty}\log p(x|\theta^{i})=A.\] That is the true that \(\log p(x|\theta^{i})\) converges to value \(A\). ### GMM Expansion Algorithm We proposed a modeling concept called GMM expansion in our prior work. We also develop a learning algorithm under our idea of GMM expansion[27]. Fourier series has a major influence on the GMM expansion idea. Our underlying assumption is that every density may be approximately expanded by a Gaussian mixture. The component distributions can be seen as base frequencies in the Fourier expansion. This means that \(\mu,\sigma\) of the component distributions are non-parametric and do not need to be optimized. In practice, we spread \(\mu\) evenly across the dataset area. \(\Sigma\) can be thought of as a hyper-parameter that modifies the general smoothness of the GMM density. In this case, \(\pi\) is the only remaining parameter for us to optimize. It is no longer required to learn the optimum set of \(\pi,\mu,\sigma\). We focus solely on finding the best set of _pi_ by learning from the dataset. Here we briefly explain the concept of GMM expansion and the learning algorithms proposed in [27]: * \(g\left(x\right)=\sum_{n}\pi_{i}\phi_{i}\left(x\right)\) is the density of GMM; * \(\sum_{n}\pi_{i}=1\), \(\phi_{i}\left(x\right)\sim N\left(\mu_{i},\sigma\right)\), \(n\) is the numbers of normal distributions; * \(r=\frac{\text{max}\left(X\right)-\text{min}\left(X\right)}{n}\) is the interval for locating \(\mu_{i}\); * \(\mu_{i}=\text{min}\left(X\right)+i\times r\) are means for Gaussian components; * \(\sigma=t\times r\) is variance for all Gaussian components; * \(t\) is a real number hyper-parameter, usually \(1\leq t\leq 5\). \[\pi^{+1}=\pi+\frac{dL\left(k_{i}^{mid},k_{i}^{side}\right)}{d\pi}\] (15) \[\frac{dL\left(\widetilde{k_{i}^{mid},k_{i}^{side}}\right)}{d\pi}=\begin{bmatrix} \frac{\widetilde{dLoss(x_{j})}}{d\sigma_{0}}\\ \vdots\\ \frac{\widetilde{dLoss(x_{j})}}{d\pi_{n}}\end{bmatrix}=\begin{bmatrix} \widetilde{P_{f_{0}}}\left(k_{i}^{mid}\right)-\widetilde{P_{f_{0}}}\left(k_{ i}^{side}\right)\\ \vdots\\ \widetilde{P_{f_{n}}}\left(k_{i}^{mid}\right)-\widetilde{P_{f_{n}}}\left(k_{ i}^{side}\right)\end{bmatrix} \tag{16}\] where \(\widetilde{P_{g_{i}}}\left(k_{i}\right)=\int_{k_{i}}\phi_{i}\left(x\right)dx\), \(\phi_{i}\) is the density of \(i\)th component distribution, \(k_{i}^{mid}\in\left(\mu_{i}-d,\mu_{i}+d\right]\), and \(k_{i}^{side}\in\left(\mu_{i}+r,\mu_{i}+r-d\right]\) or \(k_{i}^{side}\in\left(\mu_{i}-r,\mu_{i}-r+d\right]\). A simple version of our learning algorithm is provided in algorithm 1. Initialization 1.Define n Gaussian distributions and evenly spread \(\mu\) across \(Max\left(X\right),Min\left(X\right)\); 2.Calculate r, \(r=\frac{Max(X)-Min(X)}{n}\) 3.Define hyper parameter \(\sigma\) respect to r, e.g., \(\sigma=1r,\sigma=3r\), 4.Define hyper parameter \(d\) respect to \(\sigma\), e.g., \(d=\sigma/4,d=\sigma/6\), 5.Initialize \(\pi_{1}=\pi_{2}...=\pi_{n}=1/n\) 6.Define \(k_{i}^{mid}\)_and_\(k_{i}^{side}\) 7.Approximate \(\widetilde{dL}_{i}\approx\widetilde{P_{f_{i}}}\left(k_{i}^{mid}\right)- \widetilde{P_{f_{i}}}\left(k_{i}^{side}\right)\). **foreach \(\underline{x_{i}}\)**do Find \(\mu_{i}\) which closest to \(x_{j}\); Update \(\pi_{i}^{+1}=\pi_{i}+\widetilde{dL}_{i}\) ; for all m which \(m\neq i\), \(\pi_{m}^{+1}=\pi_{m}-\frac{\widetilde{dL}_{i}}{n}\); **end** Finally, re-normalize \(\pi\)s to satisfy \(\sum\pi_{i}=1\) In previous study[27], we didn't provide our learning method a theoretical basis in mathematics. In this work, we present a novel 1 iteration learning algorithm while adhering to the same GMM expansion model structure. The mathematical explanation is clearer than in earlier work. Convergence is proven and is more clearly stated and easy to apply in practice. ## 3 1 iteration GMM expansion learning algorithm ### Algorithm In this section we shows our 1 iteration learning algorithm for our GMM set up. We also proof that our algorithm is guarantee converge to a local minimum. \[\theta^{(j)}=(\pi_{1}^{(j)},\pi_{2}^{(j)}...\pi_{n}^{(j)}),\] From (1)-(3) we define Function \(L(\theta),\) \[L(\theta)=\sum_{n=1}^{N}\sum_{d=1}^{D}P(\gamma=n|\theta)P(x_{d},\mu_{n})\] where \(P(\gamma=n|\theta)=\pi_{n}\) and \(P(x_{d},\mu_{n})=\phi(x_{d}|M_{n},\Sigma_{n})\). Because we do not update \(M_{n},and\Sigma\) is a hyper-parameter where constant for all Gaussians, the conditional probability \(\phi(x_{d}|M_{n},\Sigma_{n})\) is equivalent to \(\phi_{n}(x_{d})\). \[\frac{\partial L(\theta)}{\partial\pi_{n}}=l_{n}=\sum_{d=1}^{D}P(x_{d},\mu_{n} )=\sum_{d=1}^{D}\phi_{n}(x_{d}),\] \[\pi_{n}^{(j+1)}=\frac{\pi_{n}^{(j)}+l_{n}}{\sum_{n=1}^{N}\pi_{n}^{(j)}+l_{n}}= \frac{\pi_{n}^{(j)}+l_{n}}{1+\sum_{n=1}^{N}l_{n}}, \tag{17}\] Where \(j\) is the j step of the algorithm. This matches our previous finding in [27]. When the \(\mu\) and \(\sigma\) are fixed in the GMM, the gradient of \(\pi\) is nearly constant with respect to the dataset for many cost functions, including likelihood and the suggested function \(L(\theta)\). Initialization 1.Define n Gaussian distributions and evenly spread \(\mu\) across \(\max\left(X\right),\min\left(X\right)\); 2.Calculate r, \(r=\frac{\max\left(X\right)-\min\left(X\right)}{n}\) 3.Define hyper parameter \(\sigma\) respect to r, e.g., \(\sigma=1r,\sigma=3r\),. If in higher dimensional cases, covariance matrix \(\Sigma\) set to be identity matrix * \(\sigma\). 4.Initialize \(\pi_{1}=\pi_{2}...=\pi_{n}=1/n\) 5.Calculate (17) 6.Finally, re-normalize \(\pi\)s to satisfy \(\sum\pi_{i}=1\) **Algorithm 2** Proposed Learning Method ### Theoretical Analysis The following Lemma captures the relationship of \(\pi\) and data base on the idea of GMM expansion. **Lemma 2**: _Assume the following condition are satisfied: (1) Define \(N\) Gaussian Unit \(\phi_{1},...\phi_{N}\) and each \(\phi_{n}\sim N(\mu_{n},\Sigma)\). (2) Observed Dataset X, and \(r=(\max(X)-\min(X))/N,\mu_{n}=\min(X)+r*n\). \(\Sigma\leq\alpha\) which the same for all \(\phi_{n}\) and small enough that satisfy \(\phi_{n}(x=\mu_{n})>1.0\). (3)Define N \(\pi_{n}\) where \(\pi_{1}^{(0)}=\pi_{2}^{(0)}...=\pi_{N}^{(0)}=1/N\). Denote that \([\pi_{1}^{(j)}...,\pi_{n}^{(j)}]=\theta^{j}\). Gaussian Mixture distribution density function denoted as \(G(x|\theta)\)_ _(4)Under condition (1)-(3), learned \(\pi\) from EM algorithm at the first step is denoted as \(\pi_{0}^{EM(1)}...\pi_{n}^{EM(1)}\)_ _(5) \(\pi_{n}^{(j)}=\frac{\sum_{d=1}^{D}\phi_{n}(x_{d})}{\sum_{n=1}^{N}\sum_{d=1}^{ D}\phi_{n}(x_{d})}\)_ _The following equation hold:_ \[\pi_{n}^{(j)}-\pi_{n}^{EM(1)}<\epsilon \tag{18}\] _With Lemma.1, we have:_ \[\sum_{x=d}^{D}\log(G(x|\theta^{(j)}))>\sum_{x=d}^{D}\log(G(x|\theta^{(0)})) \tag{19}\] #### 3.2.1 The proof of Lemma At (17), we can derive that: \[\pi_{n,j+1}=\frac{\pi_{n,j}}{1+\sum_{n=1}^{N}l_{n}}+\frac{l_{n}}{1+\sum_{n=1} ^{N}l_{n}}, \tag{20}\] Because we initialize \(\mu_{n}\) across the data space evenly, when the number of Gaussian units is large and the variance is small, it is reasonable to assume that: 1. For any x in dataset, we can find at least 1 Gaussian unit with a mean close to that data point. 2. When \(\sigma\) decreases, \(\phi(x,\mu,\sigma)\) increases. Together with assumption 1, we can assume that for every data point, \[l_{n}=\sum_{d=1}^{D}P(x_{d},\mu_{n})=\sum_{d=1}^{D}\phi_{n}(x_{d})>1.0, \tag{21}\] (e.g.\(\phi(x=0,\mu=0,\sigma=0.35)=1.329\).) Together with (17) and (20), we can conclude that: \[\frac{l_{n}}{1+\sum_{n=1}^{N}l_{n}}\leq\pi_{n,j+1}\leq\frac{1}{1+N}+\frac{l_{n}}{ 1+\sum_{n=1}^{N}l_{n}} \tag{22}\] When N is large, our algorithm become less and less sensitive to the initial values of \(\pi\), and approximately equal to \(\frac{l_{n}}{1+\sum_{n=1}^{N}l_{n}}\). Under this condition, our method is a one iteration method where we can perform (17) for update or calculate: \[\pi_{n}^{Our(j+1)}\approx\frac{l_{n}}{\sum_{n=1}^{N}l_{n}} \tag{23}\] It is also important to discuss how well this estimation algorithm perform. By taking the same approach as EM algorithm, we can proof that we also share the same theoretical guarantees as EM algorithm does. Notice that in EM algorithm: \[Q^{*}(\theta,\theta^{i-1})=E(\log(W(x,\gamma|\theta))=\sum_{\gamma}p(\gamma|x,\theta^{i-1})\log(\gamma_{i}) \tag{24}\] \[P(\gamma=n|x_{d},\theta)=\frac{\pi_{n}\phi_{n}(x_{d})}{\sum_{n=1}^{N}\pi_{n} \phi_{n}(x_{d})}=\frac{\pi_{n}\phi_{n}(x_{d})}{G(x_{d},\theta)} \tag{25}\] \[P(\gamma=n|X,\theta)=\sum_{d=1}^{D}\frac{\pi_{n}\phi_{n}(x_{d})}{G(x_{d}, \theta)} \tag{26}\] Because we equally initialise \(\pi\) and evenly place the \(\mu\) across the data space, the density values of initial GMM almost the same across the data domain which shows in Fig.1. It is reasonable to derive that: \[\pi_{1}^{(0)}=\pi_{2}^{(0)}...\pi_{N}^{(0)}=1/N,\] \[G(x_{1},\theta^{(0)})\approx G(x_{2},\theta^{(0)})\approx...G(x_ {D},\theta^{(0)})=k,\] \[P(\gamma=n|X,\theta^{0})=\frac{\pi_{n}^{(0)}}{G(x_{d}|\theta^{(0)})}\sum_{d=1 }^{D}\phi_{n}(x_{d})=\frac{\pi_{n}^{(0)}}{G(x_{d},\theta^{(0)})}l_{n}, \tag{27}\] Base on EM algorithm, we have following property where: \[\pi_{n}^{EM(j)}=\frac{1}{N}P(\gamma=n|X,\theta^{(j-1)})=\arg\max_{\theta}(Q( \theta,\theta^{j-1})) \tag{28}\] Put (28) into (27) along with the initial \(\pi\) and \(G(x,\theta)\), we derive: \[\pi_{n}^{EM(1)}=N\frac{\pi_{n}^{(0)}}{G(x_{d},\theta^{(0)})}l_{n}\approx\frac {1}{k}l_{n} \tag{29}\] \[\frac{\pi_{n}^{EM(1)}}{\sum_{n=1}^{N}\pi_{n}^{EM(1)}}=\frac{\frac{1}{k}l_{n}} {\sum_{n=1}^{N}\frac{1}{k}l_{n}}=\frac{l_{n}}{\sum_{n=1}^{N}l_{n}}=\pi_{n}^{EM( 1)} \tag{30}\] From (23), we conclude that: \[\pi_{n}^{Our(j+1)}\approx\pi_{n}^{EM(1)}=\frac{l_{n}}{\sum_{n=1}^{N}l_{n}} \tag{31}\] The proof is completed. This proof shows that our estimation shares the same theoretical guarantee that the likelihood of learning GMM guarantees a better result \(\log(G(X|\theta_{1}))\geq\log(G(X|\theta_{0}))\). In the next section, we use numerical experiments to compare our algorithm's efficiency with the EM algorithm. ## 4 Numerical Experiments In this section, We ran a number of tests to validate our suggested approach for learning GMM parameters and compare it with the conventional EM algorithm. Experiments in both one and two dimensions have been carried out. ### Metrics-Interval Probability Error Instead of KL-divergence or Wasserstein distance, we use a simple metric that we call interval probability error (IPE) to measure the difference between two distributions. We split the data space equally into \(n\) intervals denoted as \(\omega_{i}\). The purpose of this metric is to give a straight-forward and yet easy-to-calculate method to measure the difference between two densities. \[\text{IPE}=\sum_{i=1}^{n}\mid\int_{\omega_{i}}f\left(x\right)dx-\int_{\omega_{i }}g\left(x\right)dx\mid=\sum_{i=1}^{n}\mid P_{f}\left\{\omega_{i}\right\}-P_{g }\left\{\omega_{i}\right\}\mid, \tag{32}\] where \(f(x)\) is our target distribution and \(g(x)\) is the approximate distribution. In our case, \(g(x)\) is the Gaussian mixture distribution. Density is rarely what we are ultimately after in most real-world scenarios. Probability is more comprehensive than density in comparison. IPE is arguably a better metric to assess the accuracy of our approximation in terms of probability than density. It has several benefits to calculate IPE instead of KL-divergence or Wasserstein distance. 1. It is easy to calculate. 2. The fact that this function is bound by \(0\leq IPE\leq 2\). The accuracy of approximation can be easily evaluated. ### Test Results We will demonstrate the differences between the suggested one-iteration approach and the EM algorithm in this section. Results from experiments in both one and two dimensions are illustrated. #### 4.2.1 Graphical Comparison A density plot comparison of the estimation results allows access to the overall geometry and briefly illustrates the estimation accuracy. Both one and two-dimensional cases are shown as follows. Figure 1: \(G(x|\theta)\) with equally initialised \(\theta\) In Figure.2, the subplot in (b) demonstrate the approximation using our one-iteration method, whereas the four subplots in (a) shows the approximations using the EM algorithm with different initial settings. The target density in this numerical example is produced by mixing four normal distributions. In subplot (a) shows 4 EM estimations by different initialisation and parameters selection. 2 Gaussian mixtures are used in the top left plot, 4 in the top right, 6 in the bottom left, and 10 in the bottom right. Top left demonstrates that a significant amount of information will be lost if we use Gaussian units that are fewer than all of the peaks present in the target density. EM algorithm is initialization-sensitive as well. We show this in the top right plot, where we initialize parameters randomly across data domain. The learning result is stuck in local and fails to find the appropriate direction for optimization[9]. A appropriate initialization and the proper number of Gaussian units are used to estimate the lower two subplots in (a). It proves that adding more Gaussian units to an EM algorithm does not enhance performance as long as there exist Gaussian units that could cover the target modality. In subplot (b), it demonstrates that our approach produces outcomes that are comparable to the best outcomes that EM was capable of. Our technique has the advantage that it is unaffected by the initialization or number of Gaussian units. Target distribution in Figure.2 is a relatively simple cases. When target distributions are more complex for instance a mixture of normal distribution, uniform distribution and Laplace distribution, the differences between the two methods are more stark. Figure.3 shows our results. If the parameters of EM are not set up carefully, it fails to capture the target density modality, whereas our method easily achieves a good estimation that is able to capture most of the modality features. This is one of the main benefits of our algorithm: it is robust and not sensitive to initialization. In the 2-dimensional scenario shown in Figure.4, Our method yields superior results and allows us to capture the majority of the target density's detail without having to worry about initialization. Comparing to EM algorithm, initialization of means, variances and covariance of EM algorithms are extremely demanding. ### Numerical Comparison-IPE Due to the convergence of our algorithm, the iterative update of \(\pi_{n}\) does not change after the first step without updating the means and variances, so we only need 1 iteration to obtain the optimal solution. Table1 demonstrates that our new approach can produce a lesser IPE error and a better match for the data. Using more than 50 fitting tests of randomly generated distributions, we calculate the mean IPE error for each method. We randomly Figure 2: EM VS Proposed Method: Fitting Gaussian Mixture Distribution generate 1 dimensional mixture distributions with normal distributions and uniform distributions as target distribution. All target distributions are at least have 6 component distributions. Each target distribution sample 2000 data points as dataset for learning GMMs. In our previous work[27], our experiments shows that 200 units of GMM perform good effectiveness and efficiency. In this test, we believe that over 200 units are not necessary. In summary, our algorithm carrying following benefit compare to EM algorithm: * 1. Simplicity: We do not need to think about the initial value selection issue because our model is not initialization-sensitive. The conventional EM algorithm depends heavily on its initial value choice; if the initial value is chosen at random, the process will either fail or find the incorrect local optimal solution. The calculating process for this proposed 1 iteration algorithm is straightforward, and the initialization of our model is straightforward and same for every situation. * 2. Generality: We consider our model to be a general model. The reason is that we experimentally shows our method can approximates a large set of distributions and perform better than EM. * 3.Robust: Theoretically, we have evidence that the likelihood in our one-iteration method will be better, and the experiment shows that the IPE loss is less than EM. It's important to note that we find our approach to be more stable than the EM algorithm during the training process. When computing the variance using (10), it is \begin{table} \begin{tabular}{l c c c c} \hline algorithm & Gaussian Unit & Initialize \(\pi\) & Iteration & IPE(average 50 trail) \\ \hline Proposed 1-iteration method & 200 & Evenly across & 1 & 0.1835880213316326 \\ EM & 200 & Evenly across & 5 & 0.22858647422658074 \\ EM & 50 & Evenly across & 5 & 0.2303729611966345 \\ EM & 10 & Evenly across & 5 & 0.2851425355507268 \\ EM & 2 & Evenly across & 5 & 0.7026589181688097 \\ \hline \end{tabular} \end{table} Table 1: results of two algorithm. Figure 3: EM VS Proposed Method: Fitting Mixture Multiple Types of Continuous Distribution possible to have a result of 0. A Gaussian density function cannot have zero variance, hence zero variance will prevent the algorithm from operating. This will make it not stable to run the EM algorithm. But this did not occur in our method. ## 5 Neural Network and GMM Based Generator Latent variables in Autoencoder play crucial role in machine learning, [14; 39; 51; 12; 26]. There are many different ways to manipulate latent variables. Variational Autoencoder [19] maps the input variable to a latent space that corresponds to the parameters of a variational distribution. Generative adversarial networks [12] use noise variables as input space. Latter on [23] embeds the input latent code into an intermediate latent space. VQ-VAE [35; 46] applies the vector quantization method to learn discrete latent representation. Latent diffusion models [37] use diffusion processes in pairs with VQ-VAE produce outstanding text to image generation. All these excellent studies point out that latent variables are one of the most important issues for achieving good generation in generative models. In Kolouri [22], they trained an adversarial deep convolutional autoencoder, then learned GMM for latent variable distribution to generate random samples in the embedding space. GMM samples were passed through the decoder to generate synthetic images. We carried out the same experiments, and our learning method shows the same generational quality[27]. Non-Gaussian diffusion model is investigated in [29]. Together with VQ-VAE and latent diffusion model, we have certain degree of evidence that the distribution of latent variables are likely to be non-Gaussians. Inspired by VQ-VAE together will diffusion model and style-GAN, we present a GMM embedding technique to manipulate the latent space's attributes. Figure 4: EM VS Proposed Method: 2 Dimension. ### Cardioid and Inverse problem With the concept of GMM expansion, we can directly utilize neural networks to map any distribution within a multivariate Gaussian distribution with zero means and an identity covariance matrix. We discovered this by learning a cardioid synthetic dataset. For every point of x in the cardioid, it has 2 values of y and vice versa. This is why inverse problems occur while the inverse function of \(f^{-1}\left(y\right)\) is not unique. In Figure.5, plot 1 is the classic cardioid function. Figure.5 plot 2 is our target dataset. Instead of a simple Gaussian noise, we give both x and y a mixture distribution, where the mixture distribution is constructed by a Gaussian distribution with mean 2.0 and 0.1 variance and a Uniform distribution with [-0.3,-0.1]. These two distributions are mixed with a probability of 0.5. Classic MLP approach to find the shortest distance of x map to y will have a difficult time handling this problem unless carefully pair each input x with 2 output y. Even though we have carefully paired each input x with 2 outputs, by adding noise into the data, this data input-output becomes difficult to match. Also, the information of the variance will lost. GMM is one of the best solutions for this problem. A TensorFlow-probability example shows that changing the output layer into GMM layers and optimizing it with log-likelihood could solve this problem easily. Based on our proposed 1 iteration GMM learning method, we can change to model output have make a great improvement in fitting. Figure.6 summarizes our methodology, outcomes, and head-to-head comparison with the conventional approach. Both neural networks are trained over 200 iterations using a single hidden feedforward network made up of 100 linear units using relu activation. The outcome demonstrates that our approach captures the overall structure more accurately than the conventional way. The data we sampled from learned GMM in Figure.7 demonstrates that our outcome is remarkably close to the original dataset after adding one more hidden layer. This shows the potential of our method, and the GMM expansion concept could improve the accuracy of neural networks. Additionally, latent variable embedding can be done using our method. The following sections provide examples of the technique. Figure 5: Cardioid ### GMM based generator The Gaussian distribution is without a doubt the most popular distribution in machine learning due to reliable central limit theorem and well-studied features. From variational Autoencoder, GAN, to the latest diffusion model in neural networks and many other models like the Gaussian Process. However, some recent advancements in neural networks are moving away from the Gaussian. Latent diffusion model [37], VQ-VAE[46] and Style-GAN[23] are great examples. Both of them provide a significant way to manipulate latent variables and produce a huge impact on image generation. All these studies show that the distribution of latent space is very unlikely to be Gaussian. The latent diffusion model diffuses latent \(Z\to W\sim N(0,1)\to Z\). Style-Gan[23] map latent \(Z\) to \(W\) controls the generator through adaptive instance normalization (AdaIN) at each convolution layer. Gaussian noise is added after each convolution. All these studies point to the direction that latent space or embedding space is not Gaussian. Most studies aim for a latent space that consists of linear subspace, each of which controls one factor of variation. Our study focuses on directly using GMM to learn subspace distribution. \[\text{Decoder}(z)=y+\epsilon, \tag{33}\] \[Z\sim\text{Gaussian Mixture Distribution}(\overrightarrow{\pi}, \overrightarrow{\mu},\overrightarrow{\Sigma}) \tag{34}\] In (33), the embedding space \(Z\) is not linear. Each sample of \(Z\) represents a unique mapping from \(z\) to \(y\). Instead of linearly controlling each parameter in \(z\) for a factor of variation, we could control in \(z\) by random sampling or based on the Gaussian Mixture Distribution. Figure 6: Model Comparison #### 5.2.1 Embedding with GMM vs Nomral vs GMM + Normal To determine whether Gaussian mixture distribution is preferable to a standard Gaussian, we examine 3 different embedding types. The variable \(Z\) is made up of random samples that are fed straight into the original GAN. The generator is built by transpose convolution layers with input dimension \([1x1x100]\). Convolutional layer transposition with an input dimension of \([1x1x100]\) is used to create the generator. These studies make use of minimalist datasets, with mean square error loss as the loss function. We want to directly evaluate embedding efficiency by randomly mapping images into randomly chosen latent samples, therefore the discriminator is not being employed. \[\begin{bmatrix}z_{0}\\ \cdot\\ \cdot\\ z_{n}\end{bmatrix}=Z, \tag{35}\] \[(1)z_{i}\sim N(0,1),\] (36) \[(2)z_{i}\sim GMM(\theta_{i}),\] (37) \[(3)[z_{0}...z_{n/2}]\sim N(0,1)\text{ and }[z_{n/2}...z_{n}]\sim GMM( \theta_{i}) \tag{38}\] In (35), we show that how \(Z\) is constructed. In (1), \(z_{i}\) are all sampled in Gaussian noise as GAN does. In (2), all \(z_{i}\) are sampled by randomly generated Gaussian mixture distributions which have at least 2 peaks. In (3), the first half of the \(z_{i}\) follows Gaussian distribution and the second half of the \(z_{i}\) are from Gaussian mixture distributions. The outcomes of our experiment are shown in Table 2. We train a generator for 50 epochs as a single trail using a random sample of \(Z\). We train 30 times for each type of distribution and compute the mean and standard deviation of the loss. It is obvious that by utilizing a Gaussian Mixture rather than a normal distribution, we have smaller loss and a smaller standard deviation. The best outcome is achieved when using a Gaussian mixing distribution along with a normal distribution. The standard deviation is better than the normal distribution while slightly greater than the Gaussian Mixture distribution. This supports the argument that we made for the benefits of the Gaussian mixed Figure 7: (left)Original Data Distribution. (Right)Approximation with proposed method and 2 Feed Forward Layers distribution of latent variables or embedding for neural networks. It also explains why non-Gaussian approaches are taken by the latent diffusion model, style-GAN, and VQ-VAE. #### 5.2.2 Embedding with GMM and image generation In this section we examine whether a neural network can produce meaningful images based on latent variables that sampled from Gaussian mixture distributions. Our experiments using the Minist dataset and our embedding method are shown in Fig.8. \(Z=[Z_{0},Z_{1},Z_{2}..Z_{10}]\) is divided into data classes. Each \(Z_{i}\) represents a digit and 20 units for each \(Z_{i}\). Each unit in \(Z_{i}\) are random samples drawn from a mixture distribution. Input's \(Z_{i}\) for unrelated classes will be set to zeros. All Gaussian mixture distributions have at least two peaks. Depending on the number of peaks, each \(Z_{i}\) have at least \(2^{20}\) unique combination for embedding. Mean square error loss is applied. Appendix6 shows random samples from trained neural network. Each class has a clear feature construction and separation between each class is clear. This experiment demonstrates that neural networks can adapt to the GMM latent space and produce meaningful generation regardless the form of Gaussian Mixture distribution. It also suggests that we can benefit from random sampling for feature variations. \begin{table} \begin{tabular}{l c c c c} \hline Distribution & Numbers of \(z_{i}\) & Epochs & Average Loss & Standard deviation of Loss \\ \hline Normal & 100 & 50 & 0.09433 & 0.00154 \\ Gaussian Mixture & 100 & 50 & 0.09190 & 0.00068 \\ Gaussian Mixture and Normal & 100 & 50 & 0.09055 & 0.00090 \\ \hline \end{tabular} \end{table} Table 2: Comparison of sampling \(Z\) with 3 different method Figure 8: GMM Base Generator ## 6 Conclusions and Future Work Based on both our results and previous work[27], it is becoming clear that the idea of GMM expansion and our 1 iteration learning algorithm can be a reliable method to learn any distributions. It is better than EM algorithm in terms of simplicity and accuracy. Theoretical proof and experiments shows that our algorithm are reliable and robust. In the application with neural network, a mixture uncertainty cardioid example shows that the idea of GMM expansion are more suitable for neural network. In previous work we demonstrate GMM can learn latent distribution in encoder decoder architecture. In this work, we further investigate Gaussian mixture distribution embedding for simple generator architecture. GMM stand the test for learning the latent space as well as used as embedding. We expect GMM for directly define intermediate latent space or any GMM based embedding will be able to develop quality large model which we can benefit from random sampling for feature variation. It provide interesting development for future work.
2310.18703
Detangling the role of climate in vegetation productivity with an explainable convolutional neural network
Forests of the Earth are a vital carbon sink while providing an essential habitat for biodiversity. Vegetation productivity (VP) is a critical indicator of carbon uptake in the atmosphere. The leaf area index is a crucial vegetation index used in VP estimation. This work proposes to predict the leaf area index (LAI) using climate variables to better understand future productivity dynamics; our approach leverages the capacities of the V-Net architecture for spatiotemporal LAI prediction. Preliminary results are well-aligned with established quality standards of LAI products estimated from Earth observation data. We hope that this work serves as a robust foundation for subsequent research endeavours, particularly for the incorporation of prediction attribution methodologies, which hold promise for elucidating the underlying climate change drivers of global vegetation productivity.
Ricardo Barros Lourenço, Michael J. Smith, Sylvia Smullin, Umangi Jain, Alemu Gonsamo, Arthur Ouaknine
2023-10-28T13:04:30Z
http://arxiv.org/abs/2310.18703v1
Detangling the role of climate in vegetation productivity with an explainable convolutional neural network ###### Abstract Forests of the Earth are a vital carbon sink while providing an essential habitat for biodiversity. Vegetation productivity (VP) is a critical indicator of carbon uptake in the atmosphere. The leaf area index is a crucial vegetation index used in VP estimation. This work proposes to predict the leaf area index (LAI) using climate variables to better understand future productivity dynamics; our approach leverages the capacities of the V-Net architecture for spatiotemporal LAI prediction. Preliminary results are well-aligned with established quality standards of LAI products estimated from Earth observation data. We hope that this work serves as a robust foundation for subsequent research endeavours, particularly for the incorporation of prediction attribution methodologies, which hold promise for elucidating the underlying climate change drivers of global vegetation productivity. ## 1 Introduction Climate change alters vegetation productivity [42; 8; 30] with significant implications for the Earth's climatic and biological systems. In particular, elevated temperatures have contributed to advanced events such as changing the growing season of plants [9] and delaying leaf unfolding and leaf senescence [2; 7; 9]. These impacts, especially apparent in high-latitude countries, indicate changes in ecosystem functioning [12; 26; 27; 37]. It results in various feedback mechanisms affecting the Earth's physical systems such as changing surface reflectivity (albedo) and energy balance [28; 31; 38] while also inducing local scale disturbances in plant-pollinator interactions [12]. Studies on VP are related to phenology, the former focusing on the estimation of global vegetation production [30], while the latter on the determination of stages of plant development [29]. For instance, the total rate of carbon photosynthesized by plants (over time, in an area) is characterized as gross primary productivity (GPP) [17], a form of VP that is a critical indicator of carbon uptake of the atmosphere. Remote sensing observations are widely used to create vegetation indexes (VI) products, such as the normalized difference vegetation index (NDVI), fraction of absorbed photosynthetically active radiation (/APAR), and the leaf area index (LAI); the latter being one of the most important products used to estimate global GPP [30; 17]. This study proposes to predict LAI using climate variables to better estimate and understand the impact of climate change on vegetation productivity worldwide. Since climate factors directly influence plant productivity [30], it is still not yet clear how their dynamics affects vegetation health and growth (VP), and thus the LAI index [42; 30; 24; 10]. Successfully predicting LAI using climate variables would open up opportunities for investigating relationships between climate trends and anomalies with vegetation productivity. As a consequence, it will motivate experiments to better quantify the effects of climate forcings on carbon uptake [30]. These same shifts on vegetation dynamics have a significant impact on global albedo [5]. Therefore, this work could also drive the characterization and quantification of the bidirectional relationships between climate and LAI for many applications other than VP, for instance, vegetation growth causing water depletion in soil, which in turn increases local temperature through surface heating [39; 40]. The related work on vegetation productivity applications will be detailed in Section 2. The dataset used and the proposed method for LAI prediction will be presented in Section 3. Finally, Section 4 will detail preliminary results and future research opportunities. ## 2 Related work Mapping and understanding the relationship between vegetation dynamics and climate change has long been a well-established research challenge in global climate change communities. This is often done through ground measurements [4; 34; 32; 35; 15] or process-based models [3; 20]. The challenge still remains since no existing ground measurements are representative enough of global vegetation with long time-series measurements [29; 30; 17]. On the other hand, process-based models are too simplistic to reproduce complex global observed vegetation changes, and, at the same time, detangle the correlated roles of climate and other global change agents on LAI dynamics. ## 3 Data and method DatasetEarth observation data have been used in the format of ground-validated gridded products. The proposed target to predict is the global inventory monitoring and modeling system - third generation (GIMMS 3g) LAI product [41]. The following climate covariates have been considered as input features to tackle the proposed task: cloud cover, precipitation rate, air temperature, and frequency of wet days from the climatic research unit gridded time series (CRU-TS) dataset [11]; incoming solar radiation from the atmospheric forcing data for the community land model (CRUNCEP) dataset [36]; albedo from global land surface satellite (GLASS) [18]; and soil moisture from global land evaporation Amsterdam model (GLEAM) [21]. The dataset has been formatted to a monthly, half-degree global coverage from January 1982 to December 2015. It has been aggregated, when necessary, and saved in a netCDF format compliant with an Xarray [13] dataset structure [1]. The test set is defined as the most recent 16 months of the time series and the training set contains the remaining 380 months. MethodThe proposed experiment integrates a V-Net [22] taking as input a 4D array with latitude, longitude, and time axes, for every channel. This way, both spatial and temporal representations are learned using 3D convolutions while preserving information between the encoder and the decoder with its skip connections. The model is trained using the past climate covariate time series to predict the LAI while reconstructing and predicting the future climate covariates. The input features are shifted on the time axis, using a lag of one month, so that the model reconstructs a climate covariate set of 15 months while predicting one month ahead in the future. The training process includes batch of 4 tensors, each one of size \(360\times 720\times 16\times 7\), including the entire globe (\(360\times 720\)), as a time series of 16 months, with all seven climate covariates. These tensors are randomly built over the training set considering the 380-month period, separated from the 16-month test set. The model predicts a tensor of size \(360\times 720\times 16\times 8\), including a climate covariate reconstruction of 15 months, a one month ahead prediction of these covariates and a LAI prediction of the considered 16 months. It aims at learning spatiotemporal correlations between climate covariates and LAI while having a robust reconstruction of climate phenomena. The data are preprocessed with min-max normalization, and empty values (derived from Xarray data masking) have been replaced with -1 values. The proposed model has been trained for 73000 iterations to minimize a Huber loss function [14] using the Adam optimizer [16]. Our code used for this experiment and the pretrained model are publicly available1. Footnote 1: Links will be provided if the article is accepted. ## 4 Preliminary Results and Future Work Preliminary results on the test set are illustrated in Figure 1. The presented scores are in line with acceptable errors of earth observation products, ranging in \(\pm 0.5\) LAI [6]. A qualitative result is also illustrated in Figure 2 showing the reconstruction capacities of the model. It depicts the ability of the model to predict both LAI variability and general anomalies with less in a day of training on a single NVIDIA A100 GPU. The perspectives of this proposal could extend the time series range of the predictions, including a sensitivity study on the effects of feature lags on the predictions. An attribution study could be conducted to understand the contribution of the climate covariates on the LAI predictions. To this purpose, the global feature attribution and the local pixel attribution methods could be considered [23]. The subsequent work on eXplainable AI (XAI) feature attribution methods will attempt to score individual predictions considering each feature according to their contribution to the final prediction. The SHAP method (SHapley Additive exPlanations - [19]) could be used for local explanations while providing a global score for the model. Local pixel attribution methods, such as GradCAM [33], would also be well suited to our proposed method to highlight relevant climate covariates with respect to the gradient of the model weights. Considering accurate LAI predictions, the proposed Figure 1: Test scores of the fully trained model on the test set, after 73000 iterations. The green line shows the average error, and the orange is a linear regression. It illustrates the Root Mean Squared Error (RMSE) between the predicted and target LAI. The reported mean RMSE is 0.03 and the standard deviation is 0.006 for a normalized LAI between -1 and 1 (for LAI ranging from 0 to 7). This represents a normalized RMSE LAI of 0.04 (for two standard deviations). In an extreme scenario of \(\text{LAI}=7\) (the maximum value in our dataset) this represents a RMSE of 0.3, which is well in line with acceptable errors for earth observation products, ranging in \(\pm 0.5\) LAI [6]. Figure 2: Comparison between a true one-month ahead observation (left column) and its prediction (right) from the test set. The model provides an accurate reconstruction, with all major spatial patterns being well represented. Image in Cividis palette [25], with zero LAI values in blue, and maximum (\(\text{LAI}=7\)) in yellow. XAI methods could be able to untangle the factors driving global vegetation productivity and their relationships with global climate change. This work was supported by the Climate Change AI Summer School (in-person cohort), and through usage of cloud computing credits provided by Denvr Dataworks. We acknowledge the support of the Natural Sciences and Engineering Research Council of Canada (NSERC), through its NSERC Alliance program (Application: ALLRP 566310-21) and the Canada Research Chair program (CRC-2019-00139). We also acknowledge the support of the McMaster University Centre for Climate Change Research Seed Fund. This work was developed in part with usage of the facilities of the Shared Hierarchical Academic Research Computing Network (SHARCNET), Calcul Quebec, and the Digital Research Alliance of Canada through its Research Allocation Competition, under the 2023 Resources for Research Groups process "National carbon flux estimation system for forest ecosystems of Canada" (ID 4715).
2303.10267
Synchronization of Memristive FitzHugh-Nagumo Neural Networks
A new mathematical model of neural networks described by diffusive FitzHugh-Nagumo equations with memristors and linear synaptic coupling is proposed and investigated. The existence of absorbing set for the solution semiflow in the energy space is proved and global dynamics of the memristive neural networks are dissipative. Through uniform estimates and maneuver of integral inequalities on the interneuron difference equations, it is shown that exponential synchronization of the neural network at a uniform convergence rate occurs if the coupling strength satisfies a threshold condition explicitly expressed by the system parameters, which is illustrated by an example and numerical simulation experiments.
Yuncheng You, Jing Tian, Junyi Tu
2023-03-17T22:32:41Z
http://arxiv.org/abs/2303.10267v1
# Synchronization of memristive FitzHugh-Nagumo neural networks ###### Abstract. A new mathematical model of neural networks described by diffusive FitzHugh-Nagumo equations with memristors and linear synaptic coupling is proposed and investigated. The existence of absorbing set for the solution semiflow in the energy space is proved and global dynamics of the memristive neural networks are dissipative. Through uniform estimates and maneuver of integral inequalities on the interneuron difference equations, it is shown that exponential synchronization of the neural network at a uniform convergence rate occurs if the coupling strength satisfies a threshold condition explicitly expressed by the system parameters, which is illustrated by an example and numerical simulation experiments. Key words and phrases:Memristive FitzHugh-Nagumo equations, dissipative dynamics, exponential synchronization, coupling strength, neural network 2010 Mathematics Subject Classification: 35B40, 35B41, 35K55, 37L30, 92B20 ## 1. Introduction Recently the global dynamics and exponential synchronization of the neural networks modeled by the diffusive Hindmarsh-Rose equations with memristors were proposed and studied by the first author in [37, 38]. In this paper, we shall consider a new mathematical model of neural networks described by the diffusive FitzHugh-Nagumo equations with memristors and linear synaptic interneuron coupling. Let a network of \(m\) fully coupled memristive neuron cells be denoted by \(\mathcal{NW}=\{\mathcal{N}_{i}:i=1,2,\cdots,m\}\), where \(m\geq 2\) is a positive integer, which is described by the following model of memristive and diffusive FitzHugh-Nagumo (FHN) equations. Each neuron \(\mathcal{N}_{i},1\leq i\leq m\), in this network is presented by the differential equations: \[\begin{split}&\frac{\partial u_{i}}{\partial t}=\eta\Delta u_{i}+f(u_{ i},x)-\sigma w_{i}+J-k\tanh(\rho_{i})u_{i}+\sum_{j=1}^{m}P(u_{j}-u_{i}),\\ &\frac{\partial w_{i}}{\partial t}=au_{i}+c-bw_{i},\\ &\frac{\partial\rho_{i}}{\partial t}=qu_{i}-r\rho_{i},\end{split} \tag{1.1}\] for \(t>0\), \(x\in\Omega\subset\mathbb{R}^{n}\) (\(n\leq 3\)), where \(\Omega\) is a bounded domain with locally Lipschitz continuous boundary \(\partial\Omega\). In the membrane potential \(u_{i}\)-equations, the nonlinear term \(k\tanh(\rho_{i})u_{i}\) presents the memristive coupling effect [24, 33, 36], where \(\rho_{i}(t,x)\) stands for the memductance of the memristor and \(\tanh(\rho_{i})\) is the the electromagnetic induction flux with its coupling strength coefficient \(k\). In this system, the fast excitatory variable \(u_{i}(t,x)\) refers to the transmembrane electrical potential of a neuron cell and the slow recovering variable \(w_{i}(t,x)\) represents the integrated ionic current across the neuron membrane. The network neuron coupling terms are assumed to be linear with a common strength coefficient \(P\) in the membrane potential equation. We impose the homogeneous Neumann boundary condition \[\frac{\partial u_{i}}{\partial\nu}(t,x)=0,\quad\text{for}\;\;t>0,\;x\in \partial\Omega,\quad 1\leq i\leq m. \tag{1.2}\] The initial states of the system (1.1) will be denoted by \[u_{i}^{0}(x)=u_{i}(0,x),\;w_{i}^{0}(x)=w_{i}(0,x),\;\rho_{i}^{0}=\rho_{i}(0,x),\;\;1\leq i\leq m. \tag{1.3}\] The following Assumption is made on the scalar function \(f\in C^{1}(\mathbb{R}\times\Omega)\): \[\begin{split}& f(s,x)s\leq-\lambda|s|^{4}+\varphi(x),\quad s \in\mathbb{R},\;x\in\Omega,\\ &\frac{\partial f}{\partial s}(s,x)\leq\beta,\quad s\in\mathbb{R },\;x\in\Omega,\end{split} \tag{1.4}\] where \(\lambda\) and \(\beta\) are positive constants, \(\varphi\in L^{2}(\Omega)\) is a given function. Note that the prototype nonlinear homogeneous function \(f(s)=s(s-\kappa)(1-s)\) with \(\kappa>0\) in the original FitzHugh-Nagumo equations [9] satisfies the properties (1.4), in particular, \[\begin{split}& f(s)s=-s^{4}+(1+\kappa)s^{3}-\kappa s^{2}\leq- \frac{1}{4}s^{4}+\frac{1}{4}(1+\kappa)^{4},\\ & f^{\,\prime}(s)=-3s^{2}+2(1+\kappa)s-\kappa\leq\frac{1}{3}(1+ \kappa)^{2}-\kappa\leq\beta=\frac{1}{3}(1+\kappa)^{2}.\end{split}\] All the parameters \(\eta,\sigma,k,a,c,b,q,r\), and \(P\) can be any positive constants, while the reference membrane potential \(J\) can be any real number constant. Typical models of neuron dynamics are four-dimensional Hodgkin-Huxley equations [12], two-dimensional FitzHugh-Nagumo equations [9], and three-dimensional Hindmarsh-Rose equations [11], which originally consist of ordinary differential equations without memristors and characterize the periodic firing-bursting dynamics for neurons and nerve systems. Analysis through Hopf bifurcations and energy or Hamiltonian methods with semi-numerical simulations are the main approaches to show many solution patterns and collective synchronization behavior [6, 14, 20, 39]. Global dynamics and synchronization of ensemble neurons and neural networks modeled by partly diffusive Hindmarsh-Rose equations and FitzHugh-Nagumo equations have been studied by the authors' group in recent years [20, 21, 25, 26]. These models are hybrid differential equations and reflect the structural feature of neuron cells, which contain short-branch dendrites receiving incoming signals and long-branch axons propagating and transmitting outgoing signals through synapses. The concept of memristor was coined by Chua [4] to describe the effect of electromagnetic flux on moving electric charges. Physical and generic memristive systems initially reported in [5, 30] attracted broad scientific interests in the recent decade, especially recognized in biological neuron models and artificial intelligence computing [1, 7, 15, 17, 29, 31] as a new type (other than electrical and chemical) synapsis or as an ideal component which has the nonvolatile properties and can process dynamically memorized signal information to exhibit more complex or chaotic dynamics in neural networks. Memristor-based mathematical models now penetrate many fields with applications to image encryption, DNA sequences operation, brain criticality, cell physiology, cybersecurity, and quantum computers, cf. [17, 18, 23, 28, 29, 33, 34]. The researches on memristive FitzHugh-Nagumo and Hindmarsh-Rose neural networks in ordinary differential equations have been expanding in the recent decade, cf. [1, 8, 16, 24, 40] and many references therein. Various synchronization results with memristive effect of these models are achieved [10, 13, 19, 22, 31, 32, 35] mainly by the methods of generalized Hamiltonian functions, Lyapunov exponents, and the computational algebra with numerical simulations. In this work we shall rigorously prove a threshold condition on the neuron coupling strength \(P\) to ensure an exponential synchronization of the memristive neural networks (1.1) through the approach of dissipative dynamical analysis and sharp uniform estimates, which can be extended to study complex or artificial neural networks. ## 2. **Formulation and Preliminaries** Define two Hilbert spaces of functions: \[E=[L^{2}(\Omega,\mathbb{R}^{3})]^{m}\quad\text{and}\quad\Pi=[H^{1}(\Omega) \times L^{2}(\Omega,\mathbb{R}^{2})]^{m}\] where \(H^{1}(\Omega)\) is a Sobolev space. Call \(E\) the energy space and \(\Pi\) the regular space. The norm and inner-product of \(L^{2}(\Omega)\) or \(E\) will be denoted by \(\|\,\cdot\,\|\) and \(\langle\,\cdot,\cdot\,\rangle\), respectively. We use \(|\,\cdot\,|\) to denote a vector norm or a set measure in \(\mathbb{R}^{n}\). The initial-boundary value problem (1.1)-(1.3) can be formulated into an initial value problem of the evolutionary equation: \[\begin{split}&\frac{\partial g}{\partial t}=Ag+F(g),\,\,\,t>0,\\ & g(0)=g^{0}\in E.\end{split} \tag{2.1}\] The unknown function is a column vector \(g(t)=\operatorname{col}\,(g_{1}(t),g_{2}(t),\cdots,g_{m}(t))\), where \[g_{i}(t)=\operatorname{col}\,(u_{i}(t,\cdot),\,w_{i}(t,\cdot),\,\rho_{i}(t, \cdot)),\quad 1\leq i\leq m,\] characterizes the dynamics of the neuron \(\mathcal{N}_{i}\). The initial data function in (2.1) is \[g(0)=g^{0}=\operatorname{col}\,(g_{1}^{0},\,g_{2}^{0},\cdots,g_{m}^{0})\quad \text{where}\;\;g_{i}^{0}=\operatorname{col}\,(u_{i}^{0},\,w_{i}^{0},\,\rho_{i} ^{0}),\;1\leq i\leq m.\] The energy norm \(\|g(t)\|\) of the solution for the evolutionary equation (2.1) in the space \(E\) is given by \[\|g(t)\|^{2}=\sum_{i=1}^{m}\|g_{i}(t)\|^{2}=\sum_{i=1}^{m}\left(\|u_{i}(t)\|^{ 2}+\|w_{i}(t)\|^{2}+\|\rho_{i}(t)\|^{2}\right).\] The closed linear operator \(A\) in (2.1) is defined by \(A=\operatorname{diag}\,(A_{1},A_{2},\cdots,A_{m})\), where \[A_{i}=\begin{pmatrix}\eta\Delta&0&0\\ 0&-bI&0\\ 0&0&-rI\end{pmatrix}:\mathcal{D}(A)\to E,\quad i=1,2,\cdots,m, \tag{2.2}\] with the domain \(\mathcal{D}(A)=\{g\in[H^{2}(\Omega)\times L^{2}(\Omega,\mathbb{R}^{2})]^{m}: \partial u_{i}/\partial\nu=0,\,1\leq i\leq m\}\), is the generator of the \(C_{0}\)-semigroup \(\{e^{At}\}_{t\geq 0}\) on the space \(E\) and \(I\) is the identity operator. By the fact that \(H^{1}(\Omega)\hookrightarrow L^{6}(\Omega)\) is a continuous imbedding for space dimension \(n\leq 3\) and by the Assumption (1.4), the nonlinear mapping \[F(g)=\begin{pmatrix}f(u_{1},x)-\sigma w_{1}+J-k\tanh(\rho_{1})u_{1}+\sum_{j=1 }^{m}P(u_{j}-u_{1})\\ au_{1}+c\\ qu_{1}\\ \vdots\\ f(u_{m},x)-\sigma w_{m}+J-k\tanh(\rho_{m})u_{m}+\sum_{j=1}^{m}P(u_{j}-u_{m}) \\ au_{m}+c\\ qu_{m}\end{pmatrix}:\Pi\longrightarrow E \tag{2.3}\] is a locally Lipschitz continuous mapping. In this work we shall consider the weak solutions [3, Section XV.3] of this initial value problem (2.1). **Definition 2.1**.: A \(3m\)-dimensional vector function \(g(t,x)\), where \((t,x)\in[0,\tau]\times\Omega\), is called a weak solution to the initial value problem of the evolutionary equation (2.1), if the following two conditions are satisfied: (i) \(\frac{d}{dt}\langle g,\xi\rangle=\langle Ag,\xi\rangle+\langle F(g),\xi\rangle\) is satisfied for a.e. \(t\in[0,\tau]\) and any \(\xi\in E^{*}=E\). (ii) \(g(t,\cdot)\in C([0,\tau];E)\cap C^{1}((0,\tau);E)\) and \(g(0)=g^{0}\). Here \(E^{*}\) is the dual space of the Hilbert space \(E\). The following proposition can be proved by the Galerkin approximation method [3] with the regularity property [27] of the parabolic operator semigroup \(e^{At}\). **Proposition 2.2**.: _For any initial state \(g^{0}\in E\), there exists a unique weak solution \(g(t;g^{0}),\,t\in[0,\tau]\), for some \(\tau>0\) may depending on \(g^{0}\), of the initial value problem (2.1) formulated from the memristive FitzHugh-Nagumo equations (1.1). The weak solution \(g(t;g^{0})\) continuously depends on the initial data and satisfies_ \[g\in C([0,\tau];E)\cap C^{1}((0,\tau);E)\cap L^{2}((0,\tau);\Pi). \tag{2.4}\] _Moreover, for any initial state \(g^{0}\in E\), the weak solution \(g(t;g^{0})\) becomes a strong solution for \(t\in(0,\tau)\), which has the regularity_ \[g\in C((0,\tau];\Pi)\cap C^{1}((0,\tau);\Pi). \tag{2.5}\] An infinite dimensional dynamical systems [3, 27] for time \(t\geq 0\) only is called a semiflow. Absorbing set defined below is the key concept to characterize dissipative dynamics of a semiflow. **Definition 2.3**.: Let \(\{S(t)\}_{t\geq 0}\) be a semiflow on a Banach space \(\mathscr{X}\). A bounded set \(B^{*}\) of \(\mathscr{X}\) is called an absorbing set of this semiflow, if for any given bounded set \(B\subset\mathscr{X}\) there exists a finite time \(T_{B}\geq 0\) depending on \(B\), such that \(S(t)B\subset B^{*}\) for all \(t>T_{B}\). The semiflow is called dissipative if there exists an absorbing set. The Young's inequality in a generic form will be used throughout this paper: For any two positive numbers \(x\) and \(y\), if \(\frac{1}{p}+\frac{1}{q}=1\) and \(p>1,q>1\), one has \[x\,y\leq\frac{1}{p}\varepsilon x^{p}+\frac{1}{q}C(\varepsilon,p)\,y^{q}\leq \varepsilon x^{p}+C(\varepsilon,p)\,y^{q},\quad C(\varepsilon,p)=\varepsilon^{ -q/p}, \tag{2.6}\] where constant \(\varepsilon>0\) can be arbitrarily small. In Section 4, the Gagliardo-Nirenberg interpolation inequalities [27, Theorem B.3] will be used in a crucial step to prove the main result on exponential synchronization of the memristive neural networks. ## 3. **Dissipative Dynamics of Memristive FitzHugh-Nagumo Semiflow** In this section, we shall prove the global existence of weak solutions in time for the initial value problem (2.1) to establish a solution semiflow of the memristive FitzHugh-Nagumo neural network modeled by (1.1). Then we show the dissipative dynamics in terms of the existence of an absorbing set of this semiflow in the state spaces \(E\). **Theorem 3.1**.: _For any initial state \(g^{0}\in E\), there exists a unique global weak solution in time, \(g(t;g^{0})=\operatorname{col}\left(u_{i}(t),w_{i}(t),\rho_{i}(t):1\leq i\leq m\right),\,t\in[0,\infty)\), to the initial value problem (2.1) of the memristive FitzHugh-Nagumo equations (1.1) for the neural network \(\mathcal{N}\mathcal{N}\)._ Proof.: Conduct the \(L^{2}\) inner-products of the \(u_{i}\)-equation with \(C_{1}u_{i}(t,x)\) for \(1\leq i\leq m\), with the scaling constant \(C_{1}>0\) to be chosen later. Then sum them up to get \[\begin{split}&\frac{C_{1}}{2}\frac{d}{dt}\sum_{i=1}^{m}\|u_{i}\|^{2}+C _{1}\eta\,\sum_{i=1}^{m}\|\nabla u_{i}\|^{2}=-C_{1}P\,\sum_{i=1}^{m}\sum_{j=1}^ {m}\int_{\Omega}(u_{i}-u_{j})^{2}\,dx\\ &+C_{1}\sum_{i=1}^{m}\int_{\Omega}(f(u_{i},x)u_{i}-\sigma u_{i}w_ {i}+Ju_{i}-k\tanh(\rho_{i})u_{i}^{2})\,dx\\ \leq&\,C_{1}\sum_{i=1}^{m}\int_{\Omega}\left[-\lambda |u_{i}|^{4}+|\varphi(x)|-\sigma u_{i}w_{i}+Ju_{i}+k|\tanh(\rho_{i})|u_{i}^{2} \right]dx\\ \leq&\,C_{1}\sum_{i=1}^{m}\int_{\Omega}\left[- \lambda u_{i}^{4}+|\varphi(x)|+\frac{1}{2}\left(\lambda u_{i}^{2}+\frac{\sigma ^{2}}{\lambda}w_{i}^{2}\right)+\frac{1}{2}\left(\frac{J^{2}}{\lambda}+\lambda u _{i}^{2}\right)+ku_{i}^{2}\right]dx\\ =&\,C_{1}\sum_{i=1}^{m}\int_{\Omega}((\lambda+k)u_{ i}^{2}-\lambda u_{i}^{4})\,dx+\frac{C_{1}\sigma^{2}}{2\lambda}\sum_{i=1}^{m} \|w_{i}\|^{2}+C_{1}m\left(\|\varphi\|_{L^{1}}+\frac{J^{2}}{2\lambda}|\Omega| \right)\\ \leq&\,-\frac{1}{2}C_{1}\lambda\sum_{i=1}^{m}\int_{ \Omega}u_{i}^{4}(t,x)\,dx+\frac{C_{1}\sigma^{2}}{2\lambda}\sum_{i=1}^{m}\|w_{ i}\|^{2}\\ &\,+C_{1}m\left(\|\varphi\|\|\Omega|^{1/2}+\frac{1}{2\lambda}(( \lambda+k)^{2}+J^{2})|\Omega|\right),\end{split} \tag{3.1}\] where the Gauss divergence theorem and the Assumption (1.4) are used. In the last step above, we notice that \((\lambda+k)u_{i}^{2}\leq\frac{(\lambda+k)^{2}}{2\lambda}+\frac{\lambda}{2}u_{i} ^{4}\). Then summing up the \(L^{2}\) inner-products of the \(w_{i}\)-equations with \(w_{i}(t,x)\) for \(1\leq i\leq m\), by Young's inequality (2.6), we get \[\begin{split}&\frac{1}{2}\frac{d}{dt}\sum_{i=1}^{m}\|w_{i}\|^{2}= \sum_{i=1}^{m}\int_{\Omega}(au_{i}w_{i}+cw_{i}-bw_{i}^{2})\,dx\\ \leq&\,\sum_{i=1}^{m}\int_{\Omega}\left[\left(\frac{ a^{2}}{b}u_{i}^{2}+\frac{1}{4}b\,w_{i}^{2}\right)+\left(\frac{c^{2}}{b}+\frac{1}{4 }b\,w_{i}^{2}\right)-b\,w_{i}^{2}\right]dx\\ =&\,\sum_{i=1}^{m}\frac{a^{2}}{b}\int_{\Omega}u_{i}^{ 2}(t,x)\,dx-\frac{b}{2}\sum_{i=1}^{m}\|w_{i}\|^{2}+\frac{mc^{2}}{b}|\Omega|. \end{split} \tag{3.2}\] Next, we sum up the \(L^{2}\) inner-products of the \(\rho_{i}\)-equations with \(\rho_{i}(t,x),1\leq i\leq m\), to obtain \[\frac{1}{2}\frac{d}{dt}\sum_{i=1}^{m}\|\rho_{i}\|^{2}=\sum_{i=1}^{m}\int_{ \Omega}(qu_{i}\rho_{i}-r\rho_{i}^{2})\,dx\leq\frac{q^{2}}{2r}\sum_{i=1}^{m}u_{ i}^{2}(t,x)\,dx-\frac{r}{2}\sum_{i=1}^{m}\|\rho_{i}\|^{2}. \tag{3.3}\] Now add the above three inequalities. We come up with \[\begin{split}&\frac{1}{2}\frac{d}{dt}\sum_{i=1}^{m}\left(C_{1}\|u_{i} \|^{2}+\|w_{i}\|^{2}+\|\rho_{i}\|^{2}\right)+C_{1}\eta\sum_{i=1}^{m}\|\nabla u_ {i}\|^{2}+C_{1}P\sum_{i=1}^{m}\sum_{j=1}^{m}\int_{\Omega}(u_{i}-u_{j})^{2}dx\\ \leq&-\sum_{i=1}^{m}\int_{\Omega}\left(\frac{1}{2}C_ {1}\lambda u_{i}^{4}-\left(\frac{a^{2}}{b}+\frac{q^{2}}{2r}\right)u_{i}^{2} \right)dx+\sum_{i=1}^{m}\left(\frac{C_{1}\sigma^{2}}{2\lambda}-\frac{b}{2} \right)\|w_{i}\|^{2}-\frac{r}{2}\sum_{i=1}^{m}\|\rho_{i}\|^{2}\\ &+C_{1}m\left(\|\varphi\|\|\Omega|^{1/2}+\frac{1}{2\lambda}(( \lambda+k)^{2}+J^{2})|\Omega|\right)+\frac{mc^{2}}{b}|\Omega|,\quad t\in I_{ max}=[0,T_{max}),\end{split} \tag{3.4}\] where \(I_{max}\) is the maximal existence interval of a weak solution. Now we can choose the scaling constant to be \[C_{1}=\frac{b\lambda}{2\sigma^{2}}\quad\text{so that}\quad\frac{C_{1}\sigma^{2} }{2\lambda}-\frac{b}{2}=-\frac{b}{4}\,. \tag{3.5}\] With this choice, from (3.4) it follows that \[\begin{split}&\frac{1}{2}\frac{d}{dt}\sum_{i=1}^{m}\left(C_{1}\|u_{i} \|^{2}+\|w_{i}\|^{2}+\|\rho_{i}\|^{2}\right)+C_{1}\eta\sum_{i=1}^{m}\|\nabla u _{i}\|^{2}+\frac{b}{4}\sum_{i=1}^{m}\|w_{i}\|^{2}+\frac{r}{2}\sum_{i=1}^{m}\| \rho_{i}\|^{2}\\ &+\sum_{i=1}^{m}\int_{\Omega}\left(\frac{1}{2}C_{1}\lambda u_{i}^ {4}-\left(\frac{a^{2}}{b}+\frac{q^{2}}{2r}\right)u_{i}^{2}\right)dx+C_{1}P\sum _{i=1}^{m}\sum_{j=1}^{m}\int_{\Omega}(u_{i}-u_{j})^{2}\,dx\\ \leq& C_{1}m\|\varphi\|^{2}+m\left(C_{1}+\frac{C_{1}} {2\lambda}((\lambda+k)^{2}+J^{2})+\frac{c^{2}}{b}\right)|\Omega|,\quad t\in I _{max}=[0,T_{max}).\end{split} \tag{3.6}\] By completing square and (3.5), we have \[\begin{split}&\sum_{i=1}^{m}\int_{\Omega}\left[\frac{1}{2}C_{1} \lambda u_{i}^{4}-\left(\frac{a^{2}}{b}+\frac{q^{2}}{2r}\right)u_{i}^{2}\right] dx\\ =&\sum_{i=1}^{m}\left(\frac{a^{2}}{b}+\frac{q^{2}}{2r }\right)\|u_{i}\|^{2}+\sum_{i=1}^{m}\int_{\Omega}\left[\frac{b\lambda^{2}}{4 \sigma^{2}}u_{i}^{4}-2\left(\frac{a^{2}}{b}+\frac{q^{2}}{2r}\right)u_{i}^{2} \right]dx\\ =&\sum_{i=1}^{m}\left(\frac{a^{2}}{b}+\frac{q^{2}}{2r }\right)\|u_{i}\|^{2}+\sum_{i=1}^{m}\int_{\Omega}\left[\frac{\sqrt{b}\lambda}{ 2\sigma}u_{i}^{2}-\frac{2\sigma}{\sqrt{b}\lambda}\left(\frac{a^{2}}{b}+\frac{ q^{2}}{2r}\right)\right]^{2}dx\\ &-\frac{4m\sigma^{2}}{b\lambda^{2}}\left[\frac{a^{2}}{b}+\frac{q ^{2}}{2r}\right]^{2}|\Omega|\geq\sum_{i=1}^{m}\left(\frac{a^{2}}{b}+\frac{q^{ 2}}{2r}\right)\|u_{i}\|^{2}-\frac{4m\sigma^{2}}{b\lambda^{2}}\left[\frac{a^{2} }{b}+\frac{q^{2}}{2r}\right]^{2}|\Omega|.\end{split} \tag{3.7}\] Substitute (3.7) in (3.6). It yields the inequality \[\begin{split}&\frac{1}{2}\frac{d}{dt}\sum_{i=1}^{m}\left(C_{1}\|u_{i} \|^{2}+\|w_{i}\|^{2}+\|\rho_{i}\|^{2}\right)+C_{1}\eta\sum_{i=1}^{m}\|\nabla u_ {i}\|^{2}+C_{1}P\sum_{i=1}^{m}\sum_{j=1}^{m}\int_{\Omega}(u_{i}-u_{j})^{2}\,dx \\ &+\sum_{i=1}^{m}\left(\frac{a^{2}}{b}+\frac{q^{2}}{2r}\right)\|u_ {i}\|^{2}+\frac{b}{4}\sum_{i=1}^{m}\|w_{i}\|^{2}+\frac{r}{2}\sum_{i=1}^{m}\| \rho_{i}\|^{2}\\ \leq&\,C_{1}m\|\varphi\|^{2}+m\left[C_{1}+\frac{C_{1 }}{2\lambda}((\lambda+k)^{2}+J^{2})+\frac{c^{2}}{b}+\frac{4\sigma^{2}}{b \lambda^{2}}\left[\frac{a^{2}}{b}+\frac{q^{2}}{2r}\right]^{2}\right]|\Omega|, \quad t\in I_{max}.\end{split} \tag{3.8}\] Denote by \[C_{2}=C_{1}+\frac{C_{1}}{2\lambda}((\lambda+k)^{2}+J^{2})+\frac{c^{2}}{b}+ \frac{4\sigma^{2}}{b\lambda^{2}}\left[\frac{a^{2}}{b}+\frac{q^{2}}{2r}\right] ^{2}. \tag{3.9}\] Then (3.8) gives rise to the Gronwall-type differential inequality \[\begin{split}&\frac{d}{dt}\sum_{i=1}^{m}\left[C_{1}\|u_{i}\|^{2}+\|w_{i} \|^{2}+\|\rho_{i}\|^{2}\right]+\mu\sum_{i=1}^{m}\left[C_{1}\|u_{i}\|^{2}+\|w_{i }\|^{2}+\|\rho_{i}\|^{2}\right]\\ \leq&\,\frac{d}{dt}\sum_{i=1}^{m}\left[C_{1}\|u_{i}\| ^{2}+\|w_{i}\|^{2}+\|\rho_{i}\|^{2}\right]+2\sum_{i=1}^{m}\left[\left(\frac{a^ {2}}{b}+\frac{q^{2}}{2r}\right)\|u_{i}\|^{2}+\frac{b}{4}\|w_{i}\|^{2}+\frac{r} {2}\|\rho_{i}\|^{2}\right]\\ \leq&\,2C_{1}m\|\varphi\|^{2}+2C_{2}m|\Omega|,\quad \text{for}\;\;t\in I_{max}=[0,T_{max}),\end{split} \tag{3.10}\] where \[\mu=\min\,\left\{\frac{2a^{2}}{b}+\frac{q^{2}}{r},\;\frac{b}{2},\;r\right\}.\] We can solve the differential inequality (3.10) to obtain the following bounding estimate of all the weak solutions on the maximal existence time interval \(I_{max}\), \[\begin{split}&\|g(t,g^{0})\|^{2}=\sum_{i=1}^{m}\|g_{i}(t,g_{i}^{0}) \|^{2}=\sum_{i=1}^{m}\left(\|u_{i}(t)\|^{2}+\|w_{i}(t)\|^{2}+\|\rho_{i}(t)\|^{ 2}\right)\\ \leq&\,\frac{\max\{C_{1},1\}}{\min\{C_{1},1\}}e^{- \mu\,t}\|g^{0}\|^{2}+\frac{2m}{\mu\min\{C_{1},1\}}\left(C_{1}\|\varphi\|^{2}+C_ {2}|\Omega|\right),\quad t\in[0,\infty).\end{split} \tag{3.11}\] Here it is shown that \(I_{max}=[0,\infty)\) for every weak solution \(g(t,g^{0})\) because it will never blow up at any finite time. Therefore, for any initial state \(g^{0}=(g_{1}^{0},\cdots,g_{m}^{0})\in E\), there exists a unique global weak solution in time \(t\in[0,\infty)\) of the initial value problem (2.1) for this memristive neural network model (1.1) in the space \(E\) Based on the global existence of weak solutions shown in Theorem 3.1, we define the solution semiflow \(\{S(t):E\to E\}_{t\geq 0}\) of the memristive and diffusive FitzHugh-Nagumo equations (1.1) to be \[S(t):g^{0}\longmapsto g(t;g^{0})=\operatorname{col}\left(u_{i}(t,\cdot),w_{i}(t,\cdot),\rho_{i}(t,\cdot):1\leq i\leq m\right),\quad t\geq 0.\] We call this semiflow \(\{S(t)\}_{t\geq 0}\) the _memristive FitzHugh-Nagumo neural network semiflow_ generated by the neural network model equations (1.1). The next theorem shows that the memristive FitzHugh-Nagumo neural network semiflow \(\{S(t)\}_{t\geq 0}\) is a dissipative dynamical system in the state space \(E\). **Theorem 3.2**.: _There exists a bounded absorbing set for the memristive FitzHugh-Nagumo neural network semiflow \(\{S(t)\}_{t\geq 0}\) in the state space \(E\), which is the bounded ball_ \[B^{*}=\{h\in E:\|h\|^{2}\leq K\}. \tag{3.12}\] _Here the constant_ \[K=1+\frac{2m}{\mu\min\{C_{1},1\}}\left(C_{1}\|\varphi\|^{2}+C_{2}|\Omega| \right), \tag{3.13}\] _where the constants \(C_{1}\) and \(C_{2}\) are given in (3.5) and (3.9)._ Proof.: This is the consequence of the global uniform estimate (3.11) shown in the proof of Theorem 3.1, which implies that \[\limsup_{t\to\infty}\|g(t;g^{0})\|^{2}=\limsup_{t\to\infty}\,\sum_{i=1}^{m}\|g _{i}(t;g_{i}^{0})\|^{2}<K \tag{3.14}\] for all weak solutions of (2.1) with any initial data \(g^{0}\) in \(E\). Moreover, for any given bounded set \(B=\{h\in E:\|h\|^{2}\leq L\}\) in \(E\), there exists a finite time \[T_{B}=\frac{1}{\mu}\log^{+}\left(L\,\frac{\max\{C_{1},1\}}{\min\{C_{1},1\}}\right)\] such that all the solution trajectories started at the initial time \(t=0\) from the set \(B\) will permanently enter the bounded ball \(B^{*}\) shown in (3.12) for \(t>T_{B}\). Therefore, the bounded ball \(B^{*}\) is an absorbing set in \(E\) for the semiflow \(\{S(t)\}_{t\geq 0}\) so that this memristive FitzHugh-Nagumo neural network semiflow is dissipative. We shall further prove an ultimate uniform bound of the membrane potential functions \(\{u_{i}(t,x):1\leq i\leq m\}\) for all the weak solutions in the higher-order integrable space \(L^{4}(\Omega)\), which paves the way for the attempt to achieve the memristive neural network synchronization in the next section. **Theorem 3.3**.: _There exists a constant \(Q>0\) such that for any initial data \(g^{0}\in E\), the \(u_{i}(t)\) components, \(1\leq i\leq m\), of the weak solution \(g(t;g^{0})=(g_{1}(t),\cdots,g_{m}(t))\) of the initial value problem (2.1) for the memristive FitzHugh-Nagumo neural network \(\mathcal{NW}\) satisfies the absorbing property in the space \(L^{4}(\Omega)\),_ \[\limsup_{t\to\infty}\,\sum_{i=1}^{m}\|u_{i}(t)\|_{L^{4}}^{4}<1+Q. \tag{3.15}\] Proof.: Take the \(L^{2}\) inner-product of the \(u_{i}\)-equation in (1.1) with \(u_{i}^{3}(t),1\leq i\leq m\), and sum them up. By the boundary condition (1.2) and Assumption (1.4), we get \[\begin{split}&\frac{1}{4}\,\frac{d}{dt}\sum_{i=1}^{m}\|u_{i}(t)\|_{L^ {4}}^{4}+3\eta\sum_{i=1}^{m}\|u_{i}\nabla u_{i}\|_{L^{2}}^{2}\\ &+P\sum_{i=1}^{m}\sum_{j=1}^{m}\int_{\Omega}(u_{i}-u_{j})^{2}(u_ {i}^{2}+u_{i}u_{j}+u_{j}^{2})\,dx\\ &=\sum_{i=1}^{m}\int_{\Omega}(f(u_{i},x)u_{i}^{3}-\sigma u_{i}^{ 3}w_{i}+Ju_{i}^{3}-k\tanh(\rho_{i})u_{i}^{4})\,dx\\ &\leq\sum_{i=1}^{m}\int_{\Omega}(-\lambda u_{i}^{6}+u_{i}^{2} \varphi(x)-\sigma u_{i}^{3}w_{i}+Ju_{i}^{3}+ku_{i}^{4})\,dx,\quad t>0.\end{split} \tag{3.16}\] By Cauchy inequality, it is seen that \[u_{i}^{2}\varphi(x)-\sigma u_{i}^{3}w_{i}+Ju_{i}^{3}\leq\frac{1}{6}\lambda u_ {i}^{4}+\frac{1}{3}\lambda u_{i}^{6}+\frac{6}{\lambda}\left(\varphi^{2}(x)+ \sigma^{2}|w_{i}(t,x)|^{2}+J^{2}\right). \tag{3.17}\] Using Young's inequality (2.6), \[ku_{i}^{4}\leq\frac{1}{3}\left(\frac{16\,k^{3}}{\lambda^{2}}\right)+\frac{2}{ 3}\left(\frac{\lambda}{4}u_{i}^{6}\right)\leq\frac{6k^{3}}{\lambda^{2}}+\frac {1}{6}\lambda u_{i}^{6}. \tag{3.18}\] Note that \(\sum_{i=1}^{m}\sum_{j=1}^{m}(u_{i}-u_{j})^{2}(u_{i}^{2}+u_{i}u_{j}+u_{j}^{2})\geq 0\) always holds and \[u_{i}^{4}\leq\frac{1}{3}+\frac{2}{3}u_{i}^{6}\leq 1+u_{i}^{6},\] so that \[-\frac{1}{2}{u_{i}}^{6}\leq\frac{1}{2}-\frac{1}{2}{u_{i}}^{4}, \tag{3.19}\] From (3.16) wherein we successively use the above inequalities (3.17), (3.18), (3.19) and (3.14), it follows that \[\frac{1}{4}\,\frac{d}{dt}\sum_{i=1}^{m}\|u_{i}(t)\|_{L^{4}}^{4}+3\eta \sum_{i=1}^{m}\|u_{i}\nabla u_{i}\|^{2}\] \[\leq\sum_{i=1}^{m}\left(\lambda\int_{\Omega}\left(\frac{1}{6}u_{i} ^{4}-\frac{1}{2}u_{i}^{6}\right)dx+\frac{6\sigma^{2}}{\lambda}\|w_{i}(t)\|^{2} \right)+\frac{6m}{\lambda}\left(\|\varphi\|^{2}+\left(J^{2}+\frac{k^{3}}{ \lambda}\right)|\Omega|\right)\] \[\leq\sum_{i=1}^{m}\left(-\frac{\lambda}{3}\int_{\Omega}u_{i}^{4} \,dx+\frac{6\sigma^{2}}{\lambda}\|w_{i}(t)\|^{2}\right)+\frac{m\lambda}{2}| \Omega|+\frac{6m}{\lambda}\left(\|\varphi\|^{2}+\left(J^{2}+\frac{k^{3}}{ \lambda}\right)|\Omega|\right)\] \[\leq-\frac{\lambda}{3}\sum_{i=1}^{m}\|u_{i}(t)\|_{L^{4}}^{4}+ \frac{6\sigma^{2}}{\lambda}K+m\left[\frac{6}{\lambda}\|\varphi\|^{2}+\left( \frac{\lambda}{2}+\frac{6}{\lambda}J^{2}+\frac{6}{\lambda^{2}}k^{3}\right)| \Omega|\right],\;\;t>0. \tag{3.20}\] Consequently, with the non-negative gradient term removed, (3.20) shows that \[\frac{d}{dt}\sum_{i=1}^{m}\|u_{i}(t)\|_{L^{4}}^{4}+\frac{4\lambda }{3}\sum_{i=1}^{m}\|u_{i}(t)\|_{L^{4}}^{4} \tag{3.21}\] \[\leq\frac{24\sigma^{2}}{\lambda}K+m\left[\frac{24}{\lambda}\| \varphi\|^{2}+\left(2\lambda+\frac{24}{\lambda}J^{2}+\frac{24}{\lambda^{2}}k^ {3}\right)|\Omega|\right],\quad t>0.\] By the parabolic regularity stated in Proposition 2.2, for any weak solution \(g(t;g^{0})\) one has \(u_{i}(1)\in H^{1}(\Omega)\subset L^{4}(\Omega)\) for \(1\leq i\leq m\). Then the second statement in Proposition 2.2 shows that any weak solution has the regularity \[\sum_{i=1}^{m}u_{i}(t)\in C([1,\infty),H^{1}(\Omega))\subset C([1,\infty),L^{ 4}(\Omega)).\] Apply the Gronwall inequality to (3.21). It results in the bounding estimate of all the \(u_{i}(t)\) components in the space \(L^{4}(\Omega)\) as follows: \[\sum_{i=1}^{m}\|u_{i}(t)\|_{L^{4}}^{4}\leq e^{-\frac{4\lambda}{3}(t-1)}\sum_{ i=1}^{m}\|u_{i}(1)\|_{L^{4}}^{4}+Q,\quad\text{for}\;\,t\geq 0, \tag{3.22}\] where the constant \(Q\) is independent of any initial data and given by \[Q=\frac{18\,\sigma^{2}}{\lambda^{2}}K+m\left[\frac{18}{\lambda^{2}}\|\varphi \|^{2}+\left(\frac{3}{2}+\frac{18}{\lambda^{2}}J^{2}+\frac{18}{\lambda^{3}}k^ {3}\right)|\Omega|\right]. \tag{3.23}\] Therefore, the claim (3.15) of this theorem is proved. ## 4. **Synchronization of Memristive FitzHugh-Nagumo Neural Networks** In this section, we shall prove the main result on the exponential synchronization of the memristive FitzHugh-Nagumo neural networks described by (1.1) in the state space \(E\). This result provides a sufficient quantitative threshold condition for the neuron coupling strength to reach the neural network synchronization. **Definition 4.1**.: For a model evolutionary equation of a neural network called NW such as (2.1) formulated from the memristive and diffusive FitzHugh-Nagumo equations (1.1), we define the asynchronous degree of this neural network in a state space (as a Banach space) \(Z\) to be \[deg_{s}\left(\mathrm{NW}\right)=\sum_{1\,\leq i\,<j\,\leq\,m}\left\{\sup_{g_{ i}^{0},\,g_{j}^{0}\,\in\,Z}\,\left\{\limsup_{t\to\infty}\,\|g_{i}(t;g_{i}^{0})-g_{j}(t; g_{j}^{0})\|_{Z}\right\}\right\}\] where \(g_{i}(t)\) and \(g_{j}(t)\) are any two solutions of the model equation with the initial states \(g_{i}^{0}\) and \(g_{j}^{0}\) for two neurons \(\mathcal{N}_{i}\) and \(\mathcal{N}_{j}\) in the network. The neural network is said to be asymptotically synchronized if \[deg_{s}\left(\mathrm{NW}\right)=0.\] If the asymptotic convergence to zero of the difference norm above for any two neurons in the network admits a uniform exponential rate, then the neural network is called exponentially synchronized. Introduce the neuron difference functions: For \(i,j=1,\cdots,m\), we define \[U_{ij}(t,x)=u_{i}(t,x)-u_{j}(t,x),\,W_{ij}(t,x)=w_{i}(t,x)-w_{j}(t,x),\,R_{ij} (t,x)=\rho_{i}(t,x)-\rho_{j}(t,x).\] Given any initial state \(g^{0}=\mathrm{col}\left(g_{1}^{0},\cdots,g_{m}^{0}\right)\) in the space \(E\), the difference between any two solutions of (2.1) associated with two neurons \(\mathcal{N}_{i}\) and \(\mathcal{N}_{j}\) in the network is what we consider: \[g_{i}(t,g_{i}^{0})-g_{j}(t,g_{j}^{0})=\mathrm{col}\left(U_{ij}(t,\cdot),W_{ij }(t,\cdot),R_{ij}(t,\cdot)\right),\quad t\geq 0.\] By subtraction of the three governing equations for the \(j\)-th neuron from the corresponding equations for the \(i\)-th neuron in (1.1), we obtain the following differencing FitzHugh-Nagumo equations. For \(i,j=1,\cdots,m\), \[\frac{\partial U}{\partial t}=\eta\Delta U+f(u_{i},x)-f(u_{j},x)-\sigma W-k( \tanh(\rho_{i})u_{i}-\tanh(\rho_{j})u_{j})-mPU,\] \[\frac{\partial W}{\partial t}=aU-bW, \tag{4.1}\] \[\frac{\partial R}{\partial t}=qU-rR.\] Here we can simply write \(U(t,x)=U_{ij}(t,x),W(t,x)=W_{ij}(t,x),R(t,x)=R_{ij}(t,x)\) and further \(U(t)=U(t,\cdot),W(t)=W(t,\cdot),R(t)=R(t,\cdot)\) for notational convenience. The following exponential synchronization theorem is the main result of this paper. **Theorem 4.2**.: _For the memristive FitzHugh-Nagumo neural network \(\mathcal{NW}\) with the model (1.1)-(1.4), If the following threshold condition is satisfied by the coupling strength coefficient \(P\),_ \[P>\Gamma. \tag{4.2}\] _Here the threshold \(\Gamma\) is defined to be_ \[\Gamma=\frac{1}{m}\left(\beta+k+\frac{1}{2b}|a-\sigma|^{2}+\frac{q^{2}}{r}+ \frac{C^{*4}\,k^{8}(1+Q)^{2}}{\eta^{3}\,r^{4}}\right),\] _where the constant \(Q\) is given in (3.23) and the constant \(C^{*}\) is the coefficient in the Gagliardo-Nirenberg inequality (4.8), then the neural network \(\mathcal{NW}\) is exponentially synchronized in the state space \(E\) at a uniform exponential rate \(\alpha(P)\):_ \[\alpha(P)=\min\left\{b,\,r,\,\left[2mP-2\left(\beta+k+\frac{1}{2b}|a-\sigma|^{ 2}+\frac{q^{2}}{r}+\frac{C^{*4}\,k^{8}(1+Q)^{2}}{\eta^{3}\,r^{4}}\right) \right]\right\}. \tag{4.3}\] Proof.: The proof will go through two steps. Step 1. Take the \(L^{2}\) inner-products of the first equation in (4.1) with \(U(t)\), the second equation in (4.1) with \(W(t)\), and the third equation in (4.1) with \(R(t)\). Then sum them altogether and use the Assumption (1.4) to get \[\begin{split}&\frac{1}{2}\frac{d}{dt}(\|U(t)\|^{2}+\|W(t)\|^{2}+\|R(t) \|^{2})+\eta\|\nabla U(t)\|^{2}+b\,\|W(t)\|^{2}+r\|R(t)\|^{2}\\ =&\int_{\Omega}(f(u_{i},x)-f(u_{j},x))U\,dx+\int_{ \Omega}[(a-\sigma)UW+qUR]\,dx\\ &-\int_{\Omega}k(\tanh(\rho_{i})u_{i}-\tanh(\rho_{j})u_{j})U]\, dx-mP\|U(t)\|^{2}\\ \leq&\int_{\Omega}\frac{\partial f}{\partial s}\left( \ell u_{i}+(1-\ell)u_{j},x\right)U^{2}\,dx+\int_{\Omega}[(a-\sigma)UW+qUR]\,dx \\ &-k\int_{\Omega}\left[\operatorname{sech}^{2}(\xi\rho_{i}+(1-\xi )\rho_{j})R\,u_{i}U+\tanh(\rho_{j})U^{2}\right]dx-mP\|U(t)\|^{2}\\ \leq&\,\beta\|U\|^{2}+\int_{\Omega}[(a-\sigma)UW+qUR ]\,dx-k\int_{\Omega}Ru_{j}U\,dx+(k-mP)\|U\|^{2},\end{split} \tag{4.4}\] where the properties \(|\tanh(\rho_{j})|\leq 1\) and \(\operatorname{sech}^{2}(\xi\rho_{i}+(1-\xi)\rho_{j})\leq 1\) for the hyperbolic functions and \(\xi,\ell\in[0,1]\) are used. Next we have to treat the two integral terms on the right-hand side of the differential inequality (4.4). By the Young's inequality (2.6), we have \[\int_{\Omega}[(a-\sigma)UW+qUR]\,dx\] \[\leq\int_{\Omega}\left[\frac{b}{2}W^{2}(t,x)+\frac{1}{2b}|a-\sigma|^ {2}U^{2}(t,x)\right]dx+\int_{\Omega}\left[\frac{r}{4}R^{2}(t,x)+\frac{q^{2}}{r}U ^{2}(t,x)\right]dx \tag{4.5}\] \[= \,\frac{b}{2}\|W(t)\|^{2}+\frac{r}{4}\|R(t)\|^{2}+\left(\frac{1}{ 2b}|a-\sigma|^{2}+\frac{q^{2}}{r}\right)\|U(t)\|^{2},\quad t>0.\] For the last integral term in (4.4), by the Holder inequality, we get \[-k\int_{\Omega}Ru_{j}U\,dx\leq k\int_{\Omega}\left(\frac{r}{4k}R^{2}(t,x)+\frac{k}{r}u_{j}^{2}(t,x)U ^{2}(t,x)\right)dx\] \[\leq \,\frac{r}{4}\|R(t)\|^{2}+\frac{k^{2}}{r}\left[\int_{\Omega}u_{j }^{4}(t,x)\,dx\right]^{1/2}\left[\int_{\Omega}U^{4}(t,x)\,dx\right]^{1/2} \tag{4.6}\] \[= \,\frac{r}{4}\|R(t)\|^{2}+\frac{k^{2}}{r}\|u_{j}(t)\|_{L^{4}}^{2 }\|U(t)\|_{L^{4}}^{2},\quad t>0.\] Substitute the term estimates (4.5) and (4.6) into the differential inequality (4.4), we obtain \[\frac{1}{2}\frac{d}{dt}(\|U(t)\|^{2}+\|W(t)\|^{2}+\|R(t)\|^{2})+ \eta\|\nabla U(t)\|^{2}+\frac{b}{2}\|W(t)\|^{2}+\frac{r}{2}\|R(t)\|^{2} \tag{4.7}\] \[\leq \,\left(\beta+k+\frac{1}{2b}|a-\sigma|^{2}+\frac{q^{2}}{r}-mP \right)\|U(t)\|^{2}+\frac{k^{2}}{r}\|u_{j}(t)\|_{L^{4}}^{2}\|U(t)\|_{L^{4}}^{2 },\,\,\,t>0.\] Step 2. The key challenge here is to handle the last term on the right-hand side of the estimate inequality (4.7). We shall exploit the sharp technique of Gagliardo-Nirenberg interpolation inequalities [27, Theorem B.3]. In view of the Sobolev embedding \[H^{1}(\Omega)\subset L^{4}(\Omega)\subset L^{2}(\Omega),\] one has \[\|U(t)\|_{L^{4}}^{2}\leq C^{*}\|\nabla U(t)\|^{2\theta}\|U(t)\|^{2(1-\theta)} \tag{4.8}\] where the coefficient \(C^{*}(\Omega)>0\) only depends on the spatial domain \(\Omega\), and the interpolation index \(\theta=3/4\) is determined by \[-\frac{3}{4}=\theta\left(1-\frac{3}{2}\right)-\left(1-\theta\right)\frac{3}{2}\,.\] Hence (4.8) shows that \[\|U(t)\|_{L^{4}}^{2}\leq C^{*}\|\nabla U(t)\|^{3/2}\|U(t)\|^{1/2}. \tag{4.9}\] According to Theorem 3.3 and (3.15), \(\limsup_{t\to\infty}\sum_{i=1}^{m}\|u_{i}(t)\|_{L^{4}}^{4}<1+Q\), so that there exists a finite time \(T(g^{0})\geq 0\) such that for all \(1\leq i\leq m\), \[\|u_{i}(t)\|_{L^{4}}^{2}<(1+Q)^{1/2},\quad\text{for all}\;\;t>T(g^{0}).\] Therefore, for any given initial state \(g^{0}\in E\), by (4.9) and using Young's inequality (2.6), we can estimate \[\begin{split}&\frac{k^{2}}{r}\|u_{j}(t)\|_{L^{4}}^{2}\|U(t)\|_{L^{4 }}^{2}\leq\frac{k^{2}}{r}(1+Q)^{1/2}\,\|U(t)\|_{L^{4}}^{2}\\ \leq& C^{*}\|\nabla U(t)\|^{3/2}\left[\frac{k^{2}}{ r}(1+Q)^{1/2}\,\|U(t)\|^{1/2}\right]\\ \leq&\eta\|\nabla U(t)\|^{(3/2)\times(4/3)}+\frac{1} {\eta^{3}}\left[\frac{C^{*}k^{2}}{r}(1+Q)^{1/2}\,\|U(t)\|^{1/2}\right]^{4}\\ =&\eta\|\nabla U(t)\|^{2}+\frac{C^{*4}\,k^{8}(1+Q)^ {2}}{\eta^{3}\,r^{4}}\|U(t)\|^{2},\quad t>T(g^{0}).\end{split} \tag{4.10}\] Substitute (4.10) in (4.7). After cancellation of the gradient terms \(\eta\|\nabla U(t)\|^{2}\) on both sides of the inequality, it follows that for \(t>T(g^{0})\), \[\begin{split}&\frac{1}{2}\frac{d}{dt}(\|U(t)\|^{2}+\|W(t)\|^{2}+\|R(t)\|^{2})+ \frac{b}{2}\|W(t)\|^{2}+\frac{r}{2}\|R(t)\|^{2}\\ +&\left[mP-\left(\beta+k+\frac{1}{2b}|a-\sigma|^{2}+ \frac{q^{2}}{r}+\frac{C^{*4}\,k^{8}(1+Q)^{2}}{\eta^{3}\,r^{4}}\right)\right] \|U(t)\|^{2}\leq 0.\end{split} \tag{4.11}\] Therefore, the following Gronwall-type inequality holds: \[\begin{split}&\frac{d}{dt}(\|U(t)\|^{2}+\|W(t)\|^{2}+\|R(t)\|^{2})+ \alpha(P)(\|U(t)\|^{2}+\|W(t)\|^{2}+\|R(t)\|^{2})\\ \leq&\frac{d}{dt}(\|U(t)\|^{2}+\|W(t)\|^{2}+\|R(t)\|^ {2})+(b\|W(t)\|^{2}+r\|R(t)\|^{2})\\ +&\,2\left[mP-\left(\beta+k+\frac{1}{2b}|a-\sigma|^{2}+ \frac{q^{2}}{r}+\frac{C^{*4}\,k^{8}(1+Q)^{2}}{\eta^{3}\,r^{4}}\right)\right] \|U(t)\|^{2}\leq 0,\end{split} \tag{4.12}\] for \(t>T(g^{0})\), where the constant \[\alpha(P)=\min\left\{b,\,r,\,\left[2mP-2\left(\beta+k+\frac{1}{2b}|a-\sigma|^{ 2}+\frac{q^{2}}{r}+\frac{C^{*4}\,k^{8}(1+Q)^{2}}{\eta^{3}\,r^{4}}\right) \right]\right\}\] as shown in (4.3). Under the threshold condition (4.2) of this theorem, solving this linear Gronwall inequality (4.12) directly shows the exponential synchronization result: For any initial state \(g^{0}\in E\) and any two neurons \(\mathcal{N}_{i}\) and \(\mathcal{N}_{j}\) in the memristive FitzHugh-Nagumo neural network (1.1), their difference function \(g_{i}(t;g_{i}^{0})-g_{j}(t;g_{j}^{0})\) converges to zero in the state space \(E\) exponentially at a uniform rate \(\alpha(P)\) shown in (4.3). Namely, for any \(1\leq i<j\leq m\), \[\begin{split}\|g_{i}(t)-g_{j}(t)\|_{E}^{2}&=\|U_{ij} (t)\|^{2}+\|W_{ij}(t)\|^{2}+\|R_{ij}(t)\|^{2}\\ &\leq e^{-\alpha(P)\,t}\left\|g_{i}^{0}-g_{j}^{0}\right\|^{2} \to 0,\ \ \text{as}\,\ t\to\infty.\end{split} \tag{4.13}\] Hence it is proved that \[deg_{s}(\mathcal{NW})=\sum_{1\,\leq\,i\,<\,j\,\leq\,m}\left\{\sup_{g^{0}\,\in \,E}\,\left\{\limsup_{t\to\infty}\|g_{i}(t)-g_{j}(t)\|_{E}^{2}\right\}\right\} =0. \tag{4.14}\] Thus the exponential synchronization of the memristive and diffusive Hindmarsh-Rose neural network \(\mathcal{NW}\) in the space \(E\) is proved. ## 5. **Example and Numerical Simulation** In this section, we test some numerical experiments to verify and illustrate the obtained theoretical result on synchronization stated in Theorem 4.2. We numerically solve the memristive FitzHugh-Nagumo neural network \(\mathcal{NW}\) with the model (1.1)-(1.4) in a two-dimensional square domain. We use the finite difference method for the numerical scheme and programmed in Python. Choosing \(f(s)=s(s-1)(1-s)\), we consider the following selection of parameters: \[\begin{split}& m=4,\ \eta=10;\ \sigma=0.01;\ J=0.5;\ P=1.45;\\ & a=0.35;\ b=0.35;\ c=0.7;\ q=0.35;\ r=10.\end{split}\] Make the time-step to be \(0.00025\)s and spatial-step to be \(1\) on a \(32*32\) membrane. We compute the \(L^{2}\) norm of neuron potential \(u_{i}\), the recovering variable \(w_{i}\), the memductance \(\rho_{i}\), and also the vector solutions \(g_{i}\) from (4.13) in the energy space \(E\) as showing in Figure 1 to Figure 4. In Figure 1 to Figure 3, with a comparison between the beginning stages and results after \(10000\) iterations, one can observe the synchronization tendency of the three characterizing variables \((u_{i},w_{i},\rho_{i})\) among the neurons in the simulated mimristive neural network. From Figure 4, we observe that the differences among \(\|g_{i}\|\) tend to \(0\). We can get the the following constants that used in Theorem 4.2 based on our selection of parameters. \[\begin{split}&\lambda=0.25,\quad\phi(x)=4,\quad\beta=\frac{4}{3},\\ & C_{1}=437.5\quad C_{2}=876.4\quad\mu=0.175\quad K=41345645.6 \quad 1+Q=1220899.6\quad C^{*}=0.4\\ &\quad P=1.45>\Gamma=0.45,\quad\alpha=0.35.\end{split}\] Remark: The \(\lambda,\ \phi,\ \beta\) from (1.4) are not unique. The constant \(C^{*}\) from Gargliardo-Nirenberg inequality is chosen to be 0.4 based on [2]. Table 1 to Table 3 list the sampled values of the three components \(u_{i},w_{i},\) and \(\rho_{i}\) of the simulated solution \(g_{i}\) at one same point in the domain at \(t=0\) and at the 10000 time-step. It is seen that with a big difference on the initial values, after a certain time, the curves of \(u_{i}\), \(w_{i},\) and \(\rho_{i}\) tend to be close to each other between various neurons. The synchronization result rigorously proved in this work is illustrated by the example with sample selections of the system parameters and a randomized set of initial data. Our numerical simulation also exhibits that the neuron potentials \(u_{i}\) seem to be synchronized fastest within a limited time, while it takes much longer time to observe the synchronization on the other two variables \(w_{i}\) and \(\rho_{i}\). Figure 1. The \(L^{2}\) norm of the neurons \(u_{i}\) at the beginning (the upper figure) and after 10000 iterations (the lower figure) This observation actually enhances the conjecture that adding a nonlinear memristor coupling in the neuron potential equation would accelerate the synchronization for the main variable of neuron membrane potential. On the other hand, it also hints that the neuron potential equation is a nonlinear function of the neuron potential. Figure 3. The \(L^{2}\) norm of the neurons \(\rho_{i}\) at the beginning (the upper figure) and after 10000 iterations (the lower figure) Figure 2. The \(L^{2}\) norm of the neurons \(w_{i}\) at the beginning (the upper figure) and after 10000 iterations (the lower figure) that although the main result Theorem 4.2 confirmed the exponential synchronization has a uniform but may be small convergence rate, each of the three components may have a different synchronization rate, which turns out to be a new open and interesting problem for further research. \begin{table} \begin{tabular}{c|c|c} & Initial Value & At the 10000 time step \\ \hline \(w_{1}\) & 0.038162808368984426 & 1.4968727659565046 \\ \(w_{2}\) & 0.016109788021287225 & 1.4881936913572227 \\ \(w_{3}\) & 0.028702864538319866 & 1.4927071463421802 \\ \(w_{4}\) & 0.04497009552599465 & 1.4999646128986852 \\ \end{tabular} \end{table} Table 2. Comparision of the \(w_{i}\) at the point \(x=10,\ y=10\) Figure 4. The \(L^{2}\) norm of the neurons from the Energy space at the beginning (the upper figure) and after 10000 iterations (the lower figure) \begin{table} \begin{tabular}{c|c|c} & Initial Value & At the 10000 time step \\ \hline \(\rho_{1}\) & 0.02516293441173103 & 0.03032291951665976 \\ \(\rho_{2}\) & 0.040098450204586085 & 0.030324374854761176 \\ \(\rho_{3}\) & 0.015327673754565209 & 0.030322776082447638 \\ \(\rho_{4}\) & 0.03404629085391771 & 0.03032306624583209 \\ \end{tabular} \end{table} Table 3. Comparision of the \(\rho_{i}\) at the point \(x=10,\ y=10\) ## 6. **Conclusions** We summarize the new contribution of results in this paper. 1. We propose a new mathematical model in (1.1) of memristive neural networks in terms of the partly diffusive FitzHugh-Nagumo equations with a nonlinear memristor and linear synaptic coupling in the membrane potential equations. This model as a hybrid system of partial-ordinary differential equations features the full synaptic coupling among all the neurons. In comparison with the extensively studied ODE models, this model is more meaningful to capture the structure of biological neuron cells with long-branch axons in neurodynamics. 2. The nonlinear memristive coupling across the neurons membrane for this work is in the form of \(k\tanh(\rho_{i})u_{i}\), which appeared in quite a few researches as cited in the references. In this paper we proved the exponential synchronization of this model of memristive neural networks. There is another type of coupled memristors in the quadratic form \(k(c+\gamma\rho_{i}+\delta\rho_{i}^{2})u_{i}\), which have also been actively studied most with the ODE models of Hindmarsh-Rose equations on various topics of neuromorphic patterns and chaotic dynamics. But synchronization of the hybrid PDE neural network models such as the diffusive FitzHugh-Nagumo equations with quadratic memristors and linear membrane potential coupling seems still an open problem. 3. In this work we take the analytic approach of global dynamics for the weak solutions to pursue the synchronization investigation. Through the uniform _a priori_ estimates of grouped component solutions with adjustable scaling and maneuvering the integral inequalities, we are able to show the existence of absorbing set in the \(L^{2}\)-energy space of the solution semiflow and the existence of asymptotic ultimate bound in the higher-order integrable space of the key component solutions. This signifies our methodology from dissipative global dynamics to synchronization for such a complex neural network system. 4. The spirit of the entire mathematical proof is to tackle and control the nonlinear memductance-potential effect by the linear network coupling in different integrable spaces. Many steps of sharp analysis including the crucial Gagliardo-Nirenberg interpolation are carried out and cohesively managed. 5. The main result Theorem 4.2 of this paper provides a sufficient threshold condition for achieving the exponential synchronization of the memristive FitzHugh-Nagumo neural networks described by this hybrid system. Importantly this quantitative threshold condition (4.2)-(4.3) is simply on the linear coupling coefficient \(P\) and the exponentially decaying rate is explicitly expressed by the given biological and mathematical parameters. It is expected that modeling of biological and artificial neural networks by hybrid differential equations or other types of PDE in neuroscience and in deep learning field can be generalized with new features such as memristors and time delays. The mathematical approach presented in this work can be further explored and extended with applications in a broad scope. 6. Numerical simulation of our model is presented and aligned with the theoretical proof. All the important constants in the proof are calculated and the threshold of coupling strength P is estimated based on the theoretical result. Synchronization of our example can be seen from the \(L^{2}\) norm figures. Visualization of our model as well as other hybrid equation models of network systems and further investigation of time steps and computational estimate of suboptimal thresholds needed to achieve some required synchronization is another interesting research problem. **Acknowledgment** Jing Tian's work is supported in part by the AMS Simons Travel Grant and the Jess and Mildred Fisher Endowed Professor fund of Mathematics from the Fisher College of Science and Mathematics at Towson University.
2303.15479
Exploring the Performance of Pruning Methods in Neural Networks: An Empirical Study of the Lottery Ticket Hypothesis
In this paper, we explore the performance of different pruning methods in the context of the lottery ticket hypothesis. We compare the performance of L1 unstructured pruning, Fisher pruning, and random pruning on different network architectures and pruning scenarios. The experiments include an evaluation of one-shot and iterative pruning, an examination of weight movement in the network during pruning, a comparison of the pruning methods on networks of varying widths, and an analysis of the performance of the methods when the network becomes very sparse. Additionally, we propose and evaluate a new method for efficient computation of Fisher pruning, known as batched Fisher pruning.
Eirik Fladmark, Muhammad Hamza Sajjad, Laura Brinkholm Justesen
2023-03-26T21:46:34Z
http://arxiv.org/abs/2303.15479v1
Exploring the Performance of Pruning Methods in Neural Networks: An Empirical Study of the Lottery Ticket Hypothesis ###### Abstract In this paper, we explore the performance of different pruning methods in the context of the lottery ticket hypothesis. We compare the performance of L1 unstructured pruning, Fisher pruning, and random pruning on different network architectures and pruning scenarios. The experiments include an evaluation of one-shot and iterative pruning, an examination of weight movement in the network during pruning, a comparison of the pruning methods on networks of varying widths, and an analysis of the performance of the methods when the network becomes very sparse. Additionally, we propose and evaluate a new method for efficient computation of Fisher pruning, known as batched Fisher pruning. ## 1 Introduction ### Pruning For more than 30 years, pruning has been used to reduce the size of neural networks. For example, Optimal Brain Damage (OBD) is a pruning technique used by LeCun et al. [1] to prune unimportant weights from a neural network, which led to a significant improvement in speed and a small increase in accuracy. Furthermore, pruning can improve generalisation since smaller networks are less prone to over-fitting [2]. ### Pruning methods There exist many different pruning algorithms that can be applied to a neural network, such as penalty-based pruning [3], mutual information pruning [4], evolutionary pruning [5], sensitivity-based pruning [1], and magnitude-based pruning [6]. **Random pruning:** Random pruning is probably the simplest and most naive way to prune a network [7]. Here a certain percentage of the network weights are pruned at random. Thus, it does not attempt to determine whether some weights matter more than others. As a result, it usually leads to poor performance. **Magnitude-based pruning:** A relatively simple type of pruning algorithm is magnitude-based pruning, which is based on the assumption that small weights are irrelevant [6]. It therefore prunes small weights from the network. These algorithms are usually easy to compute and thus quite time-efficient [6]. However, while Sietsma & Dow [8] found that the removal of redundant weights led to improved performance, further pruning resulted in degraded performance on noisy data. Thus, some level of redundancy might be beneficial. **L1 pruning:** An example of magnitude-based pruning is L1 pruning where the weights with the smallest L1 norm are pruned (see Equation 1 taken from [9]). \[||\mathbf{x}||_{1}=\sum_{i=1}^{n}|x_{i}| \tag{1}\] **Other categorisations:** Furthermore, pruning algorithms can be classified according to two additional dimensions: structured-unstructured and global-local [10]. In structured pruning, individual parameters are pruned without considering their structure, whilst structured pruning involves the removal of whole structures of parameters (e.g., convolutional filters). In local pruning, pruning is performed per layer in the network, whilst global pruning is applied over all layers. In this paper, we only worked with global pruning methods. **Fisher pruning:** Theis et al. [11] introduced Fisher pruning and showed that it can be used to significantly reduce the computational complexity of state-of-the-art gaze models while maintaining similar performance. Fisher pruning is based on the concept of Fisher information, which is used to estimate the increase in loss when removing a specific weight from the network. This approximation is used to select weights for pruning where Fisher pruning removes the weights with the smallest expected increase in loss. Theis et al. [11] implemented pruning of individual weights as well as pruning of entire feature maps (especially suited for convolutional networks). In this study, we focus on the pruning of individual weights. In this case, the expected increase in loss when pruning the \(k\)th parameter can be calculated according to Equation 2 (equation taken from [11]): \[\Delta_{k}=\frac{1}{2N}\theta_{k}^{2}\sum_{n=1}^{N}g_{nk}^{2} \tag{2}\] where \(N\) is the number of data points used to estimate the Fisher information, \(\theta_{k}\) is the \(k\)th parameter, and \(g_{nk}\) is the gradient of the \(k\)th parameter with respect to the \(n\)th data point. ### Lottery Ticket Hypothesis **Definition:** The lottery ticket hypothesis was introduced by Frankle & Carbin [12] and states the following: _Given a dense neural network that has been trained from randomly initialised weights, there exists a sub-network, which (when trained in isolation) will achieve at least the same test accuracy as the original network when trained for at most the same number of iterations_. Such a trainable sub-network is referred to as a winning ticket. **Finding winning tickets:** Winning tickets can be found using standard pruning methods. Since pruning aims to remove unimportant weights, it is possible to apply pruning to the trained network to find suitable sub-networks. In this study, we consider two approaches to using pruning to find winning tickets: one-shot and iterative [12]. One-shot pruning is an approach where the network is trained before \(p\%\) of the weights in the network are pruned away. The weights are then reset to their initial state, and the network is trained until convergence again. However, iterative pruning trains a network, prunes \(p^{\frac{1}{n}}\%\) of the current weights, and resets the weights to their initial state. It then repeats this process until a total of \(p\%\) of the weights are pruned, at which point it trains the network till convergence one last time. It has been found that iterative pruning is better at finding winning tickets when networks become increasingly sparse [12]. However, this comes at a cost, as it is more computationally expensive than one-shot pruning. **Recent research:** Since the lottery ticket hypothesis was first introduced [12], a lot of research has been conducted in this field. Here we will summarise some relevant studies to show the range of research directions pursued. One area of interest is the timing of the pruning operation. Initially, Frankle et al. [12] focused on pruning after the network had been trained. In a later study [13], they compared the performance of winning tickets based on whether the pruning occurred at initialisation or early in training (between 0.1% and 7% through training). They noted that pruning at initialisation generally fails for deeper networks. However, when pruning is moved from initialisation to early in training, they were able to find small sub-networks that, after completing the rest of the training, matched the performance of the original network. Frankle et al. [14] further extended these findings by applying instability analysis to the lottery ticket hypothesis. They found that sub-networks identified through iterative magnitude pruning are only successful if they are stable to the noise in stochastic gradient descent. Another area of research is the resetting scheme used after pruning. In the original paper on the lottery ticket hypothesis [12], the weights of the winning ticket were reset to the original initialisations. However, Frankle et al. [15] subsequently introduced _late resetting_ where the weights are reset to the weights obtained after training for a few iterations. This allowed them to find successful winning tickets for a large state-of-the-art network (ResNet-50). Sub-networks identified by the lottery ticket hypothesis have also been found to facilitate transfer learning. Chen et al. [16] investigated the application of the lottery ticket hypothesis to supervised and self-supervised pre-trained models for computer vision tasks. Interestingly, it was found that the winning tickets identified for pre-trained networks also applied to downstream tasks. In fact, with 59.04% to 96.48% pruning, the sub-networks continued to perform well without any degradation on several downstream tasks (classification, detection, and segmentation). Finally, different approaches to retraining the pruned network have been explored. One such retraining technique is _fine-tuning_ where a small fixed learning rate is used used to train the unpruned weights from their final trained values [17]. Another retraining technique, proposed by Frankle et al. [14] is _weight rewinding_ where the unpruned weights are rewinded to an earlier point in training and then retrained from there with the original training schedule. Renda et al. [17] proposed a third retraining technique, _learning rate rewinding_, where the unpruned weights are trained from their final values with the learning rate schedule from weight rewinding. Renda et al. [17] found that weight rewinding and learning rate rewinding outperformed fine-tuning. Based on these results, they argued that the rewinding techniques could be used in a network-agnostic pruning algorithm that would be able to match more network-specific techniques. ### Project introduction This study is influenced by the work of Frankle & Carbin [12] and Theis et al. [11]. **Motivation:** There are several reasons for considering the lottery ticket hypothesis as an interesting field of research. It suggests that small neural networks (such as the winning tickets) are capable of learning as effectively as larger networks (i.e., obtain similar performance when trained for the same number of iterations) [15]. Given their small size, such networks can be trained much faster than their larger counterparts. Thus, insights from research on the lottery ticket hypothesis could potentially lead to more computationally efficient training procedures (e.g., by identifying suitable sub-networks early in training). Furthermore, research on the lottery ticket hypothesis can inspire the development of new and better initialisation schemes and architectures [12]. Lastly, smaller network sizes can improve the interpretability of machine learning models. Since the performance of the winning ticket is affected by the pruning method used, it is worthwhile to study the performance of different pruning methods. **Contributions:** * We reproduce selected experiments from [12]. * We implement iterative Fisher pruning for the identification of winning tickets and compare it to other pruning methods. * We perform further experimentation to investigate the performance of the different pruning methods under various conditions. * We introduce batched Fisher pruning, which extends the original Fisher pruning algorithm to work on batches, and investigate the effect of different batch sizes. ## 2 Implementation details For the experiments conducted in this report, we used the OpenLTH framework developed by Facebook Research [18]. This framework implements some of the latest research on the lottery ticket hypothesis (such as [12; 15; 14; 19; 20]) and was therefore an essential tool that allowed us to quickly start experimenting. Furthermore, it was simple to use, and it made it easy to implement new features as required for the different experiments. Lastly, the code and implementation details of our adaptation of Fisher pruning can be found here: [https://github.com/Fladmark/open_1th/blob/main/pruning/fisher_global.py](https://github.com/Fladmark/open_1th/blob/main/pruning/fisher_global.py). ## 3 Experiments ### One-shot pruning versus iterative pruning Our base implementation of the lottery ticket hypothesis is based on the iterative pruning paradigm, where the network is trained and pruned through several iterations until the desired reduction in network size has been achieved. An alternative to this approach is one-shot pruning where the network is trained once after which the network size is reduced in a single pruning step [12]. Both approaches have advantages and disadvantages. We expect iterative pruning to yield winning tickets with higher accuracy than one-shot pruning. However, the repeated training iterations make iterative pruning relatively expensive. On the other hand, since one-shot pruning only trains (and prunes) the network once, it is much cheaper to use. To test this, we compared iterative and one-shot pruning for L1 unstructured pruning and Fisher pruning. Figure 1 shows how the test accuracy changes with the percentage of weights pruned. Surprisingly, we observe that one-shot pruning and iterative pruning have very similar performances up to around 50% reduction. After this point, performance differences become noticeable with the iterative pruning methods resulting in slightly higher accuracies. The largest performance differences are seen when pruning exceeds 90%. Here we observe that the one-shot pruning methods exhibit steep drops in accuracy before the iterative methods. In general, at high levels of pruning, iterative pruning outperforms one-shot pruning in terms of accuracy. Furthermore, within each pruning paradigm, L1 unstructured pruning results in higher accuracy than Fisher pruning. However, for smaller reductions in network size, one-shot pruning results in accuracy performance similar to iterative pruning. Thus, Figure 1: Comparison of test accuracy for one-shot pruning and iterative pruning. The vertical lines mark the locations of the pruning iterations in iterative pruning. in cases where speed is essential and medium pruning is desired, one-shot pruning might be the best choice. ### Pruning and weight movement An interesting metric of comparison between different pruning methods is the movement in weight space. The goal of pruning is to remove "unnecessary" weights from the network and only retain the most relevant weights. During iterative pruning, weights are repeatedly trained and updated. They are therefore likely to move away from their initial value. In this experiment, we want to investigate whether the choice of pruning method affects the amount of movement in weight space. The weight movement is calculated according to Equations 3 and 4. \[weight_{abs\_diff\_i}=sum(abs(W_{0\_m}-W_{i\_m})) \tag{3}\] \[weight_{avg\_diff\_i}=\frac{weight_{abs\_diff\_i}}{N_{i}} \tag{4}\] where \(W_{0\_m}\) is the weight matrix of the initial unpruned network after training for \(m\) epochs, \(W_{i\_m}\) is the weight matrix of the network after \(i\) pruning iterations trained for \(m\) epochs, and \(N_{i}\) is the number of unpruned weights after \(i\) pruning iterations. \(abs()\) takes a matrix as input and returns a matrix where each element is the absolute value of the corresponding element in the input matrix. \(sum()\) takes a matrix as input and returns the sum of its elements. It should be noted that when we compute the subtraction in Equation 3, we only use the weights in \(W_{0\_m}\) that have not been pruned after \(i\) iterations. Figure 2 shows the average weight movement for the network at different percentages of pruning. We observe that as the percentage of pruned weights increases, the average weight movement increases as well. This could be because individual weights in a highly pruned network have to move more (on average) to get into a suitable configuration. In a larger network, this collective movement is spread over more weights, which might lead to smaller average weight movement (per weight). Furthermore, we note that random pruning results in higher weight movement than the other pruning methods. Since random pruning removes weights without reference to any measure of relevance, it might end up pruning important weights. When important weights are removed, the remaining weights will have to adapt to compensate for their loss. This can potentially explain the significantly higher weight movement for random pruning. In Figure 2, Fisher pruning and L1 unstructured pruning have very similar average weight differences. However, Fisher pruning has a slightly higher weight difference throughout. Fisher pruning removes Figure 2: Average weight movement for different pruning methods (_m_ = 10 epochs). weights based on the Fisher information. This calculation (see Equation 2) is based on gradients, which means that a parameter associated with smaller gradients has a higher chance of being pruned. We theorise that Fisher pruning is therefore likely to prune weights with smaller updates, which means that weights with (comparatively) larger updates are left unpruned. Hence, after pruning, the average weight difference would increase. Based on this, we expect Fisher pruning to have higher weight movement than L1 unstructured pruning, but less than random pruning. However, we did not expect Fisher pruning to be as close to L1 unstructured pruning as occurs in Figure 2. We expected to see a bigger weight difference for Fisher pruning--instead, it remains quite close to L1 unstructured pruning. This might suggest that pruning weights with a gradient-based measure does not significantly affect the amount to which the weights move during pruning. ### Varying network width It is hard to conclude which pruning method is better than others, especially when only considering networks of a fixed size. A pruning method that works well for medium-sized networks might be outperformed by another pruning method when applied to larger networks. It is therefore desirable to compare performance for a range of different network sizes. In this experiment, we compare Fisher pruning and L1 unstructured pruning on networks of varying widths. We start with a LeNet with 2 hidden layers of size 300 and 100 respectively. Three scaled-up versions of the network are then tested: (600, 200), (1200, 400), and (2400, 800) neurons per hidden layer. For each network, we iteratively prune 20% of the weights 10 times, which results in the network size being reduced by approximately 90%. The results are shown in Figure 3. Figure 3 illustrates the difficulty of identifying an overall best pruning method since neither pruning method dominates the other. It seems that Fisher pruning performs better on wider networks, whilst L1 unstructured pruning performs better on narrower networks. However, further experimentation would be needed to confirm this. Furthermore, as the size of the network increases, we observe that the accuracy of the winning ticket increases as well. One possible explanation is that as the network size increases, it becomes more likely that an appropriate sub-network (the winning ticket) is found by the pruning methods. However, since we prune a certain percentage of the weights in each case, the size of the winning ticket increases as the size of the initial network increases. This probably also contributes to the increase in accuracy. In the future, it would be interesting to extend this experiment by pruning to a fixed-sized winning ticket irrespective of the initial network size. Figure 3: Accuracy of different models (pruned and unpruned) for varying network widths. ### Over-pruning In the previous experiment, we explored how the size of the network influences the performance of different pruning methods. In this experiment, we want to investigate how the pruning methods perform when the network becomes very sparse (up to a 99.6% reduction in size). As previously, we compare Fisher pruning, L1 unstructured pruning, and random pruning. It is difficult to predict how Fisher pruning and L1 unstructured pruning will perform when pruning the network this severely. However, random pruning is expected to perform worse than both Fisher pruning and L1 unstructured pruning. Furthermore, we suspect that random pruning will result in a drop in accuracy due to the creation of a bottleneck in the network. Such a bottleneck can develop as the random nature of the pruning might result in most (or all) nodes in a layer being removed, which severely limits the information passed to the following layer in the network. Figure 4 compares the performance of Fisher pruning and L1 unstructured pruning. Figure 3(a) shows all 25 pruning iterations (indicated by the vertical lines in the plot), whilst Figure 3(b) only shows the first 18 pruning iterations. By excluding the last pruning iterations, we are better able to compare the performance as details are harder to make out in Figure 3(a) due to the final drop in accuracy affecting the scale of the \(y\)-axis. We observe that the performance of the two pruning methods is initially very similar--for the first 4 pruning iterations, their performance is nearly identical. After this point, some variation occurs, though the performance is still quite similar. This is especially apparent in Figure 3(a). However, L1 unstructured pruning results in a small peak in accuracy at around 92% pruning. Further experimentation would be needed to determine whether this is an anomaly or a feature of L1 unstructured pruning. Figures 4(a) and 4(b) are structured similarly to Figures 3(a) and 3(b), but include random pruning. At this scale, the small peak in L1 unstructured pruning becomes increasingly less noticeable. Additionally, Figure 4: Test accuracy of different pruning methods as the percentage of pruned weights is increased (20% pruning at each iteration). Figure 5: Test accuracy of different pruning methods as the percentage of pruned weights is increased (20% pruning at each iteration). our expectations for random pruning are confirmed as it generally performs worse than L1 unstructured pruning and Fisher pruning. After around 68% pruning, the accuracy starts to steadily decline (see Figure 4(b)). This could indicate the beginning of a bottleneck developing. However, after around 95% pruning, the accuracy drops dramatically--going all the way to 20%. Neither Fisher pruning nor L1 unstructured pruning exhibits a similarly steep drop in accuracy. We suspected that this was due to the aforementioned bottleneck. Since random pruning has no measure of importance for the different weights, it could end up removing nearly all weights from one layer, resulting in a bottleneck. On further inspection, our suspicion was confirmed. An output node in the unpruned network has 100 incoming connections. However, random pruning resulted in each of the output nodes having only 1 or 0 incoming connections. On the other hand, L1 unstructured pruning and Fisher pruning preserved between 21 and 39 incoming connections for the output nodes, allowing the network to make more accurate predictions. ### Batched Fisher pruning Equation 2 showed that \(\Delta_{k}\) contains a sum over the squared gradients of all the data points. This means that a backward pass is required for each data point to obtain the gradient for that data point. However, completing one backward pass per data point is very expensive compared to computing a single backward pass based on the combined loss of a batch of data points. Using batches is a standard procedure in machine learning where the batch size is an important (and sensitive) hyperparameter for model performance [21]. Furthermore, if we want to use the gradients that are automatically calculated during model training, then Equation 2 only works if the batch size is set to 1. For this reason, we decided to investigate the performance of Fisher pruning when using batches of data points. We hypothesised that batches could increase the performance of the pruning method. Furthermore, it would make it easier to incorporate Fisher pruning with the training of standard machine learning models where batches are commonly used. In this case, it would be possible to utilise the gradients calculated during training when computing the Fisher information. When using batches, Equation 2 can be rewritten as Equation 5. We will refer to this as "batched Fisher pruning". \[\Delta_{k}=\frac{1}{2B}\theta_{k}^{2}\sum_{b=1}^{B}g_{bk}^{2} \tag{5}\] where \(B\) is the number of batches and \(g_{bk}\) is the gradient of the \(k\)th parameter with respect to the \(b\)th batch. For this experiment, we start with a LeNet architecture with two hidden layers of 300 and 100 units respectively, which is trained on the MNIST data set. The models are pruned to approximately 10% of their original size using iterative Fisher pruning, and the best result from the final training (fine-tuning) of the winning ticket is kept. We repeat the experiment for three different random seeds. For each seed, three batch sizes are tested: 1, 100, and 10,000. It should be noted that the training procedure of the networks was kept constant throughout the experiment. The default training parameters were used with a batch size of 128. Thus, the Fisher information calculations were performed outside the training loop using a subset (10,000 samples) of the training samples. This allows us to isolate performance differences caused by batched Fisher pruning, rather than performance differences caused by variations in the internal training parameters (such as the training batch size). Figure 6 shows the performance of the different batch sizes, where a batch size of 1 is equivalent to the original Fisher pruning algorithm. We observe that increasing the batch size from 1 to 100 results in an increase in the accuracy of the pruned model. Furthermore, with a batch size of 100, we only sum 100 squared gradients instead of 10,000. Further increasing the batch size to 10,000 (i.e., taking the gradient of the loss of all the samples) also seems to increase the accuracy slightly when compared to the original Fisher pruning. However, the standard deviation is big in this case, which might be expected since the gradient is only calculated once. Since the LeNet architecture is quite simple, we decided to test how batched Fisher pruning performs on a more computationally expensive network. For this, we used the ResNet-20 architecture on the CIFAR-10 data set. The results (see Figure 7) further emphasised the benefit of using batched Fisher pruning. With a batch size of 1, Fisher pruning became unfeasible as it would take approximately a week to finish. This is due to the high cost of performing 10,000 backward passes with such a complex network. However, for the other two batch sizes (100 and 10,000), the training and pruning procedure finished in a couple of hours. In Figure 7, we observe that a higher test accuracy is achieved with a batch size of 100 compared to a batch size of 10,000. A similar trend was seen in Figure 6, however, the difference between the two models is even greater here (Figure 7). The main focus of this experiment was to investigate the potential benefit, in terms of improved test accuracy, when using batched Fisher pruning. However, batches can improve Fisher pruning in other ways as well. In particular, batched Fisher pruning can lead to a significant increase in speed as it requires fewer backward passes. In this study, we only had time to perform a limited number of tests. In the future, it would be interesting to expand this experiment to gain a better understanding of how batched Fisher pruning can improve performance. Figure 6: Test accuracy of pruned LeNet models (10% remaining) with different batch sizes for Fisher pruning. Figure 7: Test accuracy of pruned ResNet models (10% remaining) with different batch sizes for Fisher pruning. Conclusion In this study, we have explored different pruning techniques, with a focus on Fisher pruning and L1 unstructured pruning. Through our experimentation, we have found that one-shot pruning and iterative pruning have very similar performance up to around 50% reduction in network size, but at high levels of pruning, iterative pruning outperforms one-shot pruning in terms of accuracy. Additionally, we have found that the choice of pruning method affects the amount of weight movement, with L1 unstructured pruning resulting in slightly less weight movement than Fisher pruning. Furthermore, we have found that the performance of the pruning methods varies depending on the width of the network, with Fisher pruning seeming to perform better on wider networks, while L1 unstructured pruning performed better on narrower networks. However, further experimentation would be needed to confirm this. We also found that as the network becomes very sparse, the performance of Fisher pruning and L1 unstructured pruning diverges slightly. However, it would require further investigation to determine whether this is an anomaly or caused by characteristics of the pruning methods. On the other hand, random pruning exhibited a significant drop in accuracy when over-pruning, which is probably due to the creation of a bottleneck in the network. Finally, we have introduced the concept of batched Fisher pruning, which led to an improvement in both test accuracy and computational efficiency when compared to the traditional Fisher pruning method. ## 5 Future work Our investigation has highlighted several opportunities for future work. One avenue for further exploration is to conduct additional experimentation with varying network widths. This could involve both increasing the number of experiments and expanding the range of networks and data used. Additionally, we proposed pruning networks of different initial sizes down to a fixed-sized winning ticket (rather than a certain percentage). This would allow us to better investigate the effect of larger network sizes since the size of the winning ticket would no longer be proportional to the original network size. Another potential extension is to examine the impact of increased network depth on pruning performance. Furthermore, it would be beneficial to implement batched Fisher pruning with feature map Fisher information, which has been shown to be more appropriate for convolutional models (as suggested in [11]). It would also be interesting to investigate structured pruning, which removes entire neurons instead of single weights, as this constitutes a sort of middle ground between weight pruning and feature map pruning. This could potentially be combined with Fisher information. Lastly, it would be useful to explore the differences in performance between iterative pruning and continuous training methods.
2302.03132
Importance attribution in neural networks by means of persistence landscapes of time series
We propose and implement a method to analyze time series with a neural network using a matrix of area-normalized persistence landscapes obtained through topological data analysis. We include a gating layer in the network's architecture that is able to identify the most relevant landscape levels for the classification task, thus working as an importance attribution system. Next, we perform a matching between the selected landscape functions and the corresponding critical points of the original time series. From this matching we are able to reconstruct an approximate shape of the time series that gives insight into the classification decision. We test this technique with input data from a dataset of electrocardiographic signals.
Aina Ferrà, Carles Casacuberta, Oriol Pujol
2023-02-06T21:43:39Z
http://arxiv.org/abs/2302.03132v1
# Importance Attribution in Neural Networks by Means of Persistence Landscapes of Time Series ###### Abstract We propose and implement a method to analyze time series with a neural network using a matrix of area-normalized persistence landscapes obtained through topological data analysis. We include a gating layer in the network's architecture that is able to identify the most relevant landscape levels for the classification task, thus working as an importance attribution system. Next, we perform a matching between the selected landscape functions and the corresponding critical points of the original time series. From this matching we are able to reconstruct an approximate shape of the time series that gives insight into the classification decision. We test this technique with input data from a dataset of electrocardiographic signals. ## Introduction The use of methods from topological data analysis (TDA) to enhance the performance of neural networks is widespread. In some cases the purpose is to provide versatile vectorizations [4], or to achieve a higher prediction accuracy or classification accuracy [10], or to regularize learning algorithms by feeding topological information extracted from data [6, 7, 15]. Topology has also been used to reduce the size of datasets without much loss in training accuracy [17]. A survey of TDA methods for time-series analysis in deep learning using Betti numbers is offered in [22]. Tracking changes in the topology of a dataset as it passes through the layers of a well-trained neural network is the subject of [20], while the topology of neuron activations is analyzed in [16]. Assessment of the generalization gap by means of persistence descriptors without the need of a testing set is discussed in [1, 8]. The use of landscapes as persistence descriptors was initiated by Bubenik in [3]. Landscapes were used in connection with deep learning in [18] with the goal of improving learnability by adding information on topological features of input data into subsequent layers, but not for explainability purposes. Activation landscapes have also been used as topological summaries of neural network performance in [23], and for personalized arrhythmia classification [24]. In this article we use TDA towards interpretability of classification results in deep learning. More precisely, we use persistence landscapes to retrieve information about features from data on which a neural network focuses to perform a classification task. We preprocess data so that the network is fed with a sequence of landscape levels instead of the original signals. The hierarchical structure of persistence landscapes allows us to design a method for finding the most informative levels. For this, we introduce an additional layer to a chosen architecture, whose mission is to assign weights to persistence landscape levels of given signals from a dataset. Then we run again the network using only the landscape levels with the highest weights. The results show that the set of selected landscape levels (normally 2 to 4) yield similar classification accuracies as the collection of the first 10 levels. Selecting the most relevant landscape levels for a deep learning classification task opens the possibility of reconstructing partially the given data using only the chosen landscape functions. The resulting simplified version of the given data sheds light on which parts of data signals were most relevant for the network's classification task. This provides not only information about the learning process by the network but also about the most essential features carried by data. In the context of a heartbeat analysis (Section 3.2) we checked that our neural network obtains similar accuracies when fed with reconstructions of signals from selected landscape levels in comparison with those obtained with raw data. This enhances confidence in the classification results by providing evidence that the network is not focusing on artifactual details during the learning process. Our reconstruction method is described more precisely in a companion article [14], which addresses some mathematical questions related with the present paper and is related with the inverse problem in TDA, namely recovering certain types of data from persistence summaries [2, 13, 21]. As an outcome of our approach, we found that the number of landscape levels that are selected as being most relevant for a dataset is inversely associated with the accuracy of a neural network being trained with the given dataset (Fig. 6 below). Thus, datasets for which it is unclear which landscape levels should be marked as most important for a deep learning classifier tend to correspond with those with a lower classification performance. Basic facts about persistence landscapes are collected in Section 1, and our attribution algorithm for landscape levels is described in Section 2. In Subsection 3.1 we validate our technique with nine datasets from the UCR Time Series Classification Archive [9], and use it in Subsection 3.2 to test the accuracy of classification of electrocardiographic signals from the MIT-BIH Arrhythmia Database [19]. As discussed in Subsection 3.3, shifting signals may cause a loss of classification accuracy by a neural network, while persistence landscapes and results obtained from them remain invariant under horizontal shifts of the data. Hence there is an advantage in using landscapes for classification in cases where such shifts may be due to undesired effects. ## 1 Persistence landscapes for sublevel sets Time-series arrays can be viewed as one-dimensional continuous piecewise linear functions where persistent homology can be applied to study the evolution of sublevel sets. Thus we consider a sliding parameter \(t\) along the \(y\)-axis, and for each function \(f\) defined on an interval \([a,b]\) and each value of \(t\) we compute the number of connected components of the corresponding sublevel set \(L_{t}(f)\), which is defined as \[L_{t}(f)=\{x\in[a,b]\mid f(x)\leq t\}.\] This coincides with the number of connected components of the part of the graph of \(f\) which lies at or below height \(t\). The collection of all sublevel sets for a given function yields a persistence module whose value at \(t\) is the vector space \(H_{0}(L_{t}(f);\mathbb{R})\), where \(H_{0}\) denotes zero-dimensional homology and coefficients in the field \(\mathbb{R}\) of real numbers are used. For background about persistence modules and their associated barcodes and persistence diagrams, see [12]. A _barcode_ depicts the lifetime of each connected component of a sublevel set, from the height \(t=b\) (birth) where it appears until the height \(t=d\) (death) in which it merges with some other connected component. The corresponding _persistence diagram_ contains a point \((b,d)\) for each barcode line starting at \(b\) and ending at \(d\). The infinite ray depicting the essential homology class that survives to infinity is discarded for practical purposes. Barcodes or persistence diagrams are not optimal for their use in deep learning. Neural networks perform best with array-shaped data. In this article we use _landscapes_ as persistence summaries. Figure 1: From left to right, a piecewise linear function, its barcode of zero-dimensional homology of sublevel sets and the corresponding persistence diagram. Persistence landscapes were defined in [3] and, in the case of sublevel sets of signals, they express the evolution of connected components by means of a finite sequence of continuous piecewise linear functions with compact support. Computationally, each landscape function can be expressed as an array of discretized values, which makes it suitable to be introduced into a deep learning system. The sequence of landscape functions associated with a persistence diagram is defined as follows. For each point \((b,d)\) in the persistence diagram, one considers the corresponding _tent function_ \[\Lambda_{(b,d)}(t)=\max\{0,\min\{t-b,d-t\}\}.\] Next, a piecewise linear function \(\lambda_{k}\colon\mathbb{R}\to\mathbb{R}\) is defined for each \(k\geq 1\) as \[\lambda_{k}(t)=\operatorname{kmax}\{\Lambda_{(b,d)}(t)\},\] where \(\operatorname{kmax}\) returns the \(k\)-th largest value of a given set of real numbers whose elements are counted with multiplicities, or zero if there is no \(k\)-th largest value. Therefore, since the number of points in a persistence diagram is finite, \(\lambda_{k}=0\) for all sufficiently large values of \(k\). The first landscape levels \(\lambda_{1},\lambda_{2}\dots\) depict the most persistent topological features, while the last ones correspond to less persistent phenomena. ## 2 Attribution of importance The fact that persistence landscapes can be stratified into a hierarchical sequence of levels makes it possible to design a mechanism for importance attribution ranking landscape levels of a given sample of signals. In [14] a deterministic procedure is described to reconstruct signals from directional persistence landscapes in a number of chosen directions. It is also shown in [14] how to partially reconstruct the given signals using only a subset of selected landscape levels, which is the focus of interest in the present article. By combining this procedure with a machine learning assignment of a sequence of weights to landscapes, we achieve a substantial reduction of the number of critical points of the given data functions without losing much classification accuracy. To do this, we stack landscape functions from persistence of sublevel sets of the given signals in a matrix that will be fed into a neural network. Landscapes provide a convenient representation, since each landscape level corresponds to a different region of the oscillation of the input signal. Since our objective is to feed a deep learning model, we decided to normalize the area under each landscape function in order to force the network to focus on their morphology instead of their actual values. This process is illustrated in Fig. 3. Figure 3: Extracting information through persistence landscapes to feed a neural network. Figure 2: Sequence of nonzero levels \(\lambda_{k}\) of a persistence landscape (left). The existence of different levels of information naturally leads to the study of which levels are more important than others for the classification task. In order to implement this idea, we propose the use of a _gating layer_: we maintain the matrix shape throughout all the architecture and, before applying the fully connected layers, each landscape level \(\lambda_{k}\) is multiplied by a positive, less-than-one learnable weight \(w_{k}\). Thus we obtain a set of weights that indicate how influential is each landscape level for the classification task. Typically, a network should regard the first landscape levels as more important than the last ones, given that the first levels contain information about the most persistent topological features. By building a ranking of all the landscape levels, we are able to decide at which threshold of information the network stops learning. This is helpful in two main ways: first, we are able to reduce the information that we use to train our system by reducing the number of landscape functions that we pass to our network; and second, we can attribute importance to the parts of the original data that are producing the most relevant landscape levels. ## 3 Experimental setting and results In this section, we present the results of our experiments using a neural network with a fixed architecture and different input signals. Our main aims are to assess the changes in classification accuracy by using only a set of selected landscape levels in comparison with the full landscape and with the original data, while determining which are the most relevant landscape features in each database. Robustness of our method is estimated by applying it to nine databases of very different nature. **Data.** We applied our methodology to a collection of datasets taken from the UCR Time Series Classification Archive [9]. The criteria for choosing a dataset were the following: the dataset should have at most five different classes and the total number of samples divided by the number of classes should be greater than or equal to 500. These criteria were adopted in order to avoid dealing with data scarcity problems and difficulties caused by imbalanced classes or by an excessive number of classes. Table 1 contains a summary of the characteristics of each dataset. **Methodology.** In order to avoid discrepancies in the accuracy of the method due to the different ranges of values among datasets, input functions have been standardized to have values between 0 and 1. Moreover, when the topological preprocessing is applied, landscapes have been normalized so that the area under each landscape function is equal to 1. In doing so, we force the neural network to study the shape of the landscape, rather than only taking into account its actual values. The main objective of our study is to compare the ability of landscape levels to capture information against a baseline of the raw data with the only preprocessing of standardization. Furthermore, to assess that the selected landscape levels are sufficient to classify, the results of feeding a neural network with the full landscape and the results of using only the selected levels are compared. \begin{table} \begin{tabular}{l|r r r r} **Dataset** & **Samples** & **Length** & **Classes** & **Imbalanced** \\ \hline **ECG5000** & 5000 & 140 & 5 & Yes \\ **FreezerRegularTrain** & 3000 & 301 & 2 & No \\ **HandOutlines** & 1370 & 2709 & 2 & Yes \\ **ItalyPowerDemand** & 1096 & 24 & 2 & No \\ **MoteStrain** & 1272 & 84 & 2 & No \\ **PhalangesOutlinesCorrect** & 2658 & 80 & 2 & Yes \\ **StarLightCurves** & 9236 & 1024 & 3 & Yes \\ **Wafer** & 7164 & 152 & 2 & Yes \\ **Yoga** & 3300 & 426 & 2 & Yes \\ \hline \end{tabular} \end{table} Table 1: A summary of the characteristics of each dataset. For each dataset we indicate the total number of samples, the length of each sample, the number of classes and whether the dataset is imbalanced or not. The architecture of the neural network is as follows: three convolutional layers combined with row-preserving max pooling layers followed by two dense layers (Fig. 4). Our gating layer is used for selection and attribution purposes and it is only present when landscape levels are used as input. In such case, the gating layer is placed between the last max pooling layer and the first dense layer. The experiments are conducted using a 5-fold cross-validation. Training sets amount to 80% of each dataset. The neural network is trained during 240 epochs, with a starting learning rate of 0.01 that is divided by 5 every 100 epochs. This architecture has been chosen to be rather generic, without attempting to achieve the highest possible accuracy, neither with the original data nor by means of landscapes. Our purpose was to assess the validity our method while avoiding possible particularities due to a tailored choice of an optimal architecture. As for performance metrics, only accuracy is taken into account in this article. ### Validation of the method #### 3.1.1 Performance results We carried out the same experiment for 9 different datasets from [9] to verify the stability of the results (Table 2). For each dataset, we ran a neural network (Fig. 4) with three different inputs: the original data, a sequence of persistence landscape levels, and a selected subset of levels. Since the length of the full sequence of nonzero landscape levels is variable, we chose the first 10 levels \(\lambda_{1},\dots,\lambda_{10}\) since in most cases the 10th level was already zero, and fixing a larger number of landscape levels caused memory difficulties during the training process without a significant increase in accuracy. Subsequently, the selection of a smaller number of principal landscape levels was made by choosing the highest weights provided by the gating layer. The number of selected levels ranged from 2 to 5 depending on the dataset (Fig. 5). Further details about the selection of an appropriate subset of landscape levels are given in SS 3.1.2. Table 2 shows the average accuracy and standard deviation of each experiment using 5-fold cross-validation. The table contains average accuracy results using raw data, unnormalized landscapes, normalized landscapes, and a selected subset of normalized landscape levels. The results show that landscapes achieve sufficiently high classification accuracies, especially when they are normalized (third and fourth columns). In that respect, landscape accuracies are statistically comparable up to one standard deviation to using raw data in four out of the nine datasets. In Table 2, the results obtained by TDA-based strategies that are statistically comparable among them --including the method that achieved maximum accuracy-- are highlighted in bold font. Unnormalized landscapes consistently miss relevant information in most cases, and this is translated into a significant reduction in accuracy. It is also remarkable that the selected landscape levels achieve similar performances as whole (normalized) landscapes. This reinforces the hypothesis that most of the information contained in data is captured by a small subset of landscape levels. In the PhalangesOC dataset, normalized landscapes perform even better than the original data. As pointed out in the Discussion, this could be due to the inherent elastic deformation invariance provided by the landscape representation. Figure 4: Architecture of the neural network designed for this study. The gating layer is placed immediately before the first dense layer (pink) when landscapes are used as input. #### 3.1.2 Ranking of landscape levels The keystone of our process is to be able to identify which landscape levels carry the highest amount of information for classification outcomes. The gating layer multiplies each landscape level \(\lambda_{k}\) (with \(k=1,\ldots,10\)) by a learnable weight \(w_{k}\) with \(0\leq w_{k}\leq 1\). After the full training process of the neural network, the resulting weights are used to attribute importance to each landscape level. To ensure significance, we performed the experiment five times and recorded the mean weight value and standard deviation for each landscape level, as seen in Fig. 5. Although there is no obvious numerical method to determine the number of landscape levels that should be considered important in view of their weights, we used the following criterion. If \(w_{k}<\frac{1}{2}w_{k-1}\) for some \(k\), we call \(k\) a _significant drop_. If \(k\) is the largest significant drop with \(w_{k-1}>0.1\), then we select \(\lambda_{1},\ldots,\lambda_{k-1}\) as most important landscape levels. If there is no significant drop with \(w_{k-1}>0.1\), then we pick the smallest \(k\) such that \(w_{1}+\cdots+w_{k-1}>w_{k}+\cdots+w_{10}\) and also select \(\lambda_{1},\ldots,\lambda_{k-1}\). With very few exceptions, the network regards the first landscape levels as more important. These contain information of the most persistent topological features of each signal (connected components of sublevel sets). The first 10 levels were used in all the experiments. In some cases --namely, (d) and (f) in Fig. 5-- landscape levels \(\lambda_{k}\) with \(k>6\) were zero for all samples in the dataset. In these cases, the gating layer assigned small but not necessarily zero weights to the null levels. It is remarkable that the terminal landscape level (i.e., the 10th in our study) tends to be consistently more relevant than the immediately precedent ones, except in those cases where it is zero for the whole dataset. This suggests that the terminal landscape level may convey discriminant information, deserving further study. Fig. 5 shows that for certain datasets all weights are below 0.4, specifically (c) and (f), and marginally also (i). Looking at Table 2, we find that these datasets are precisely the ones that yield accuracies below 90% on test sets after the neural network had been trained with the original data. The datasets where the original data achieved a higher classification accuracy coincide with those with a smallest number of important landscape levels. Indeed, Fig. 6 shows an inverse relationship between accuracies and the number of selected landscape levels. As examples of unfavorable cases, we now discuss results obtained with the datasets FordA and TwoPatterns from [9]. These datasets share a common property, namely they consist of wave-like signals with a varying wavelength and the key information to classify them is the \(x\)-coordinate where the changes in the waves are happening. In one of them (FordA), the original data are difficult to \begin{table} \begin{tabular}{l|c|c c c c} **Dataset** & **Raw data** & **Unnormalized** & **Normalized** & **Selected** & No. \\ \hline **ECG5000** & \(94.72\pm 0.7\) & \(\mathbf{92.96\pm 0.5}\) & \(\mathbf{93.12\pm 0.4}\) & \(\mathbf{92.88\pm 0.3}\) & 3 \\ **FreezerRT** & \(99.53\pm 0.4\) & \(63.70\pm 4.2\) & \(\mathbf{88.97\pm 0.3}\) & \(\mathbf{88.70\pm 1.6}\) & 2 \\ **HandOutlines** & \(89.20\pm 1.7\) & \(75.77\pm 4.6\) & \(\mathbf{85.26\pm 2.0}\) & \(81.90\pm 2.0\) & 5 \\ **ItalyPowerD** & \(97.73\pm 1.1\) & \(87.18\pm 3.4\) & \(\mathbf{89.45\pm 1.7}\) & \(\mathbf{90.36\pm 1.3}\) & 2 \\ **MoteStrain** & \(90.98\pm 1.1\) & \(71.84\pm 1.8\) & \(\mathbf{77.33\pm 2.8}\) & \(\mathbf{76.31\pm 1.7}\) & 3 \\ **PhalangesOC** & \(64.02\pm 2.1\) & \(63.95\pm 4.2\) & \(\mathbf{68.95\pm 0.9}\) & \(\mathbf{69.21\pm 0.8}\) & 4 \\ **StarlightCurves** & \(95.70\pm 0.4\) & \(89.82\pm 2.3\) & \(\mathbf{94.92\pm 0.1}\) & \(\mathbf{95.22\pm 0.5}\) & 3 \\ **Wafer** & \(99.65\pm 0.2\) & \(90.86\pm 0.8\) & \(\mathbf{98.63\pm 0.3}\) & \(\mathbf{98.79\pm 0.4}\) & 3 \\ **Yoga** & \(82.48\pm 1.6\) & \(64.21\pm 4.1\) & \(75.36\pm 1.1\) & \(\mathbf{78.33\pm 1.0}\) & 4 \\ \hline \end{tabular} \end{table} Table 2: Average accuracies (given as percentages) and standard deviations on test sets from five runs of a neural network (Fig. 4) for nine signal datasets. Accuracies obtained from original data (first column) are compared with those obtained from the first 10 landscape levels without area normalization (second column) and with area normalization (third column), and from the most informative landscape levels (fourth colum). The last column indicates how many landscape levels were selected in each case. Statistically comparable accuracies among TDA-based strategies appear in boldface. classify, while in the other one (TwoPatterns) the original data are easily classifiable. In both cases, replacing the data by persistence landscapes erases the relevant information for a neural network classifier --since landscapes are invariant under wavelength changes if amplitude is preserved-- and thus we obtain low accuracy and considerable overfitting if landscapes are used instead of raw data. In Fig. 7 we see that, for the FordA datasets (where the neural network has trouble classifying even with the original data) the weights of persistence landscape levels are all similar and with a low relevance. In contrast, in the TwoPatterns case we see a clear ranking of the first landscape levels. Hence, landscape selection yields meaningful information about the dataset even in disadvantageous situations, since there is a consistent inverse relationship between the ability of the neural network to correctly classify the original data and the number of important landscape levels found through our method. In conclusion, Fig. 6 and Fig. 7 provide evidence that the outcome of landscape level selection can be related to how well a neural network can perform. Figure 5: Average weights and standard deviations of the first ten landscape levels for nine datasets after five runs of a neural network (Fig. 4) equipped with a gating layer. ### A use case: Results of a heartbeat analysis As an application case, we used our algorithm for a classification of electrocardiogram signals (ECG) from the MIT-BIH Arrhythmia Database [19] for evaluation of arrhythmia detectors. The dataset can be retrieved from [11] and it includes 48 half-hour excerpts of 24-hour ECG recordings obtained from 47 subjects (25 men aged 32 to 89 years and 22 women aged 23 to 89 years) studied between 1975 and 1979. Our data sample includes 87,554 heartbeats of five classes: one corresponding to normal beats (82.77%); three classes corresponding to different arrhythmia types, namely supraventricular premature beats (2.54%), premature ventricular contraction (6.61%), and fusion of ventricular and normal beats (0.73%); and one class for unidentifiable heartbeats (7.35%). Table 3 shows average accuracy after a 5-fold cross-validation. The classification accuracy of our neural network (Fig. 4) fed with the original unprocessed signal (98.41%) is compared with the accuracy of the same architecture using a 10-level landscape (94.55%) and using only the three most important landscape levels (94.00%). Landscapes were area-normalized since Table 2 evidenced an advantage of normalized landscapes versus unnormalized ones. The choice of three levels was based on weights assigned by the network, as shown in Fig. 8, where \(k=4\) is the largest significant drop. Figure 6: Inverse relationship between the accuracy of our neural network (red) trained with the original raw data and the number of landscape levels (blue) that were selected as important. Datasets in the horizontal axis are ordered by increasing accuracy. Figure 7: Average weights and standard deviations of the first ten landscape levels for two datasets after five runs of a neural network (Fig. 4) equipped with a gating layer. Next we used the partial reconstruction technique described in detail in [14, Section 3] in four examples, corresponding to the classes of (a) normal heartbeats, (b) supraventricular premature beats, (c) premature ventricular contraction, and (d) fusion of ventricular and normal beats. Three landscape levels were used for approximation in each case. The outcome is shown in Fig. 10. Each landscape function \(\lambda_{k}\) was paired with a list of \(y\)-values of critical points of the given signal \(f\) as specified in [14, Proposition 3.1]. Hence we obtained a list of \(y\)-values of critical points of \(f\) associated with the subset of selected landscape levels. The values in this list were compared with the list of all critical points of \(f\) in order to obtain the matching \(x\)-values, and a new graph was drawn by joining the resulting critical points of \(f\) in the order of their \(x\)-coordinates, as in Fig. 9. The procedure is detailed below in Algorithms 1, 2 and 3. The resulting simplified graphs (Fig. 10) mark the points of interest, according to the neural network used in our experiment, for the classification of ECG samples. Thus they encode the most relevant information on which the network focused for its task. \begin{table} \begin{tabular}{l c c c c} & **Raw data** & **10 levels** & **3 levels** & **Reconstructed** \\ \hline **Accuracy** & \(98.41\pm 0.09\) & \(94.55\pm 0.16\) & \(94.00\pm 0.13\) & \(97.04\pm 0.14\) \\ \hline \end{tabular} \end{table} Table 3: Accuracy of classification (given in percentages) of our neural network (Fig. 4) fed with unprocessed data versus processed data with ten landscape levels and processed data using the most significant three landscape levels, as well as data approximately reconstructed by means of three landscape levels. Figure 8: Average weights and standard deviations of the first ten landscape levels for a sample of the MIT-BIH Arrhythmia Database after five runs of a neural network (Fig. 4). Figure 9: An ECG signal function (left) and its approximate reconstruction from a set of selected landscape levels (right). We subsequently introduced the simplified reconstructions of the wave functions (Fig. 9) into the network in order to check if the data features distilled by our reconstruction method were sufficient for the network's classifications task. The results can be seen in Table 3 and indicate that the simplified signals gave rise to similar accuracies (97.04%) as the original data (98.41%). ### Invariance under translations Persistence summaries are not altered by horizontal shifts of signals and hence the accuracy of a classification task based on landscapes is invariant under such shifts. However, shifts may cause a loss of classification accuracy by a neural network fed with the original data. To demonstrate this effect, we used the same ECG dataset from SS 3.2, yet we modified each heartbeat by adding a number of zeros randomly split between the beginning and the end of the beat signal. Thus, while in the original dataset each heartbeat was represented by a vector of length 187, in our experiment we introduced zeros so that the length was increased to 374. \begin{table} \begin{tabular}{l c c} & **Raw data** & **Double length** \\ \hline **Accuracy** & \(98.41\pm 0.09\) & \(96.77\pm 0.10\) \\ \hline \end{tabular} \end{table} Table 4: Accuracies (given in percentages) of our neural network fed with unmodified data versus modified data by inserting zero segments at the beginning and end of each signal so as to duplicate the length of the signals (second column). Figure 10: Partial reconstruction of ECG graphs using the three most important landscape levels for each of four types of heartbeats. Classification of the shifted ECG graphs by means of the same neural network as in SS 3.2 with five repetitions resulted in lower accuracy (Table 4) than with the original data. However, shifts do not alter the evolution of connected components of sublevel sets of the graphs and therefore the landscapes associated with the shifted graphs are the same as those of the original data. This illustrates that the use of persistence descriptors can be advantageous in practical cases where translations of data signals are unsubstantial in nature and nevertheless can be misinterpreted by a neural network. ## 4 Discussion This article highlights an instance of the usefulness of topological data analysis in machine learning, specifically in the field of interpretability of outcomes of neural networks. Our procedure enabled us to distill partial information from the given data sufficiently relevant for classification purposes without a significant loss of accuracy. We used landscapes as descriptors of persistence of sublevel sets of signals, since landscapes come with a hierarchy of levels that enables us to rank the importance of each level by means of weights assigned by a gating layer in a neural network. We confirmed that using the whole persistence landscape is not necessary for an accurate classification of signals: once we have identified the subset of landscape levels that is most important for the network, running the experiment with only this subset of levels yields a statistically comparable accuracy (Table 2). A novelty of this study is normalization of landscape functions so that the area below the graph is constantly equal to one. This was conceived as an attempt to feed the neural network with _shapes_ rather than _magnitudes_. As Table 2 shows, the accuracies obtained with normalized landscapes were higher than those obtained prior to normalization. Furthermore, the standard deviation of accuracy is lower after normalization in most cases, suggesting that normalization enhances stability. In addition, our method allows us to partially reconstruct the given signals using the set of selected landscape levels, thus depicting which features of the data are most relevant for classification by means of the chosen architecture. Persistence descriptors are not injective in general and cannot be used to recover the data except in some cases where a collection of directional persistence diagrams are considered [2, 5, 14, 21]. However, our problem at hand is different: we need not fully reconstruct a function with the only knowledge of its persistence diagram, but rather attribute the persistence descriptors to the original information. Hence, our reconstruction task consists of matching points in the persistence landscape with corresponding parts of the given signals. Indeed, \(y\)-values of critical points of signals are determined by points in persistence diagrams as in [14, Section 1]. Since we are discretizing the given signals, difficulties regarding numerical precision may arise. When we are searching for peaks in landscape functions, the corresponding \(y\)-values of critical points in signals can be computed up to the chosen precision. When comparing those \(y\)-values with the original functions, we cannot expect a zero difference, since we are dealing with approximations. Instead, we have to take values that are below a certain threshold. In order to avoid picking \(x\)-values that do not correspond to the correct critical points, each time we had a candidate \(x\)-value we checked in the original function that it came indeed from a minimum or a maximum. A feature of our method is that persistence diagrams of sublevel sets of signals do not capture information about the distribution of data along the \(x\)-axis, but only along the \(y\)-axis. As a consequence, persistence summaries such as landscapes are invariant with respect to translations or scale changes on the \(x\)-axis, or, more generally, with respect to horizontal elastic deformations. This can be a disadvantage for the use of persistent homology in cases when, for example, the wavelength of periodic or almost periodic functions is crucial for classification purposes, as illustrated by the datasets FordA and TwoPatterns in Subsection 3.1.2. However, it can be an advantage if expansion or contraction along the \(x\)-axis produces undesired effects, as in the case of bradycardia and tachycardia in [10] or in the experiment made in Subsection 3.3. Hence, the use of persistence summaries can serve to remove spuriousness due to shifts on the \(x\)-coordinate without a physical significance; e.g., when time series are segmented into shorter signals or when random horizontal segments occur within signals. Regardless of the effect on performance metrics of using persistence descriptors instead of raw data, by using landscapes we gain insight about key patterns used to classify the given data, which makes the process more trustworthy. Thus, our method not only provides information about the focus of the network's learning process but it also serves to explore and better understand the dataset.
2307.03920
Training Physics-Informed Neural Networks via Multi-Task Optimization for Traffic Density Prediction
Physics-informed neural networks (PINNs) are a newly emerging research frontier in machine learning, which incorporate certain physical laws that govern a given data set, e.g., those described by partial differential equations (PDEs), into the training of the neural network (NN) based on such a data set. In PINNs, the NN acts as the solution approximator for the PDE while the PDE acts as the prior knowledge to guide the NN training, leading to the desired generalization performance of the NN when facing the limited availability of training data. However, training PINNs is a non-trivial task largely due to the complexity of the loss composed of both NN and physical law parts. In this work, we propose a new PINN training framework based on the multi-task optimization (MTO) paradigm. Under this framework, multiple auxiliary tasks are created and solved together with the given (main) task, where the useful knowledge from solving one task is transferred in an adaptive mode to assist in solving some other tasks, aiming to uplift the performance of solving the main task. We implement the proposed framework and apply it to train the PINN for addressing the traffic density prediction problem. Experimental results demonstrate that our proposed training framework leads to significant performance improvement in comparison to the traditional way of training the PINN.
Bo Wang, A. K. Qin, Sajjad Shafiei, Hussein Dia, Adriana-Simona Mihaita, Hanna Grzybowska
2023-07-08T07:11:52Z
http://arxiv.org/abs/2307.03920v1
Training Physics-Informed Neural Networks via Multi-Task Optimization for Traffic Density Prediction ###### Abstract Physics-informed neural networks (PINNs) are a newly emerging research frontier in machine learning, which incorporate certain physical laws that govern a given data set, e.g., those described by partial differential equations (PDEs), into the training of the neural network (NN) based on such a data set. In PINNs, the NN acts as the solution approximator for the PDE while the PDE acts as the prior knowledge to guide the NN training, leading to the desired generalization performance of the NN when facing the limited availability of training data. However, training PINNs is a non-trivial task largely due to the complexity of the loss composed of both NN and physical law parts. In this work, we propose a new PINN training framework based on the multi-task optimization (MTO) paradigm. Under this framework, multiple auxiliary tasks are created and solved together with the given (main) task, where the useful knowledge from solving one task is transferred in an adaptive mode to assist in solving some other tasks, aiming to uplift the performance of solving the main task. We implement the proposed framework and apply it to train the PINN for addressing the traffic density prediction problem. Experimental results demonstrate that our proposed training framework leads to significant performance improvement in comparison to the traditional way of training the PINN. Multi-task optimization, MTO, Physics-informed neural network, PINN, Knowledge transfer ## I Introduction The physical laws that govern the dynamics of a system can often be described as partial differential equations (PDEs). The solution to such PDEs allows the estimate of the system state over time in the future. However, it is often challenging to solve PDEs due to lack of analytical solutions. Compared to traditional numerical solvers, PINNs [1] provide a new and more efficient way of solving the PDE by approximating the solution to the PDE via the neural network (NN) model while incorporating certain PDE-related regularization terms as the prior knowledge into the NN training. In this way, the training of the NN can be guided by the physical laws which govern the generation of the training data to avoid the need of a large amount of training data by the NN to achieve the desired generalization performance [2]. In recent years, PINNs have been successfully applied in a variety of scientific and engineering scenarios, such as fluid dynamics [3][4] and material engineering [5][6], which show superiority over traditional PDE solvers. However, it is a more challenging task for training PINNs than training traditional NNs. Specifically, the loss function in the PINN is composed of two parts, i.e., the NN loss (related to NN training errors) and the PDE loss (related to PDE residuals), which may result in inconsistent gradient directions for reducing each part in different training stages. Because of the inherent magnitude difference of these two parts and the variability of the training data (for the NN loss) and the sampling data (for the PDE loss) in terms of both quantity and quality, decreasing one part during training is likely to lead to increase of another part. It makes traditional gradient descent-based training techniques very difficult (highly time-consuming) to converge. Training NNs, particularly deep NNs (DNNs) [7], is by no means trivial, which has attracted considerable research efforts from the past till now. Among existing works, those based on transfer learning have demonstrated excellence. Some of such approaches [8][9] make use of the knowledge in certain forms acquired from pre-trained models to assist in a given training task. Others [10] create multiple auxiliary training tasks which are somewhat relevant to a given training task, and solve them together with the given (main) task while enabling knowledge transfer across different task-solving processes such that the given task can be better solved. In the light of the latter kind of approaches, we propose a novel MTO-based PINN training framework, where auxiliary PINN training tasks are created and solved together with the main training task while enabling cross-task knowledge transfer to improve on the performance of solving the main task. In our proposed MTO-based PINN training framework, the auxiliary PINN training tasks can be designed from the aspects of using different training data and solving different tasks related to the main task, among others. The PINN models utilized in multiple different tasks share the same architecture except for the front (input) and/or end (output) layers, which can accommodate the data and/or tasks of different properties. Multiple PINNs are individually trained at the same time for solving their own tasks during which network parameters from the other PINNs can be used to help train any specific PINN via a linear combination with learnable coefficients if a certain knowledge transfer criterion is met. We implement the proposed training framework and apply it to train the PINN model for traffic density prediction which is a promising application of PINNs, where auxiliary tasks are designed by considering both different training data and other different but relevant traffic state estimation (prediction) tasks. Experimental results show that our method can consistently improve over the traditional way of training the PINN across various kinds of auxiliary tasks. ## II Background ### _PINNs in Traffic State Estimation_ Traffic state estimation has gained much research attention in the field of transport engineering because it directly impacts many downstream applications, e.g., traffic control, incident management, and vehicle navigation. In recent years, traffic state estimation based on PINNs have been studied [11][12]. Most of such works utilize macroscopic traffic flow models to depict the physical laws in the PINN, which analyze the traffic in an aggregative manner without considering individual vehicles. The macroscopic models are based on the kinematic wave theory and typically treat a traffic flow as a fluid stream [13][14]. They can capture forward and backward shockwaves that occur when the traffic state varies through a section of the road. Several traffic flow models, such as Lighthill-Whitham-Richards (LWR) [13][14] and Aw-Rascle-Zhang (ARZ) [15], have been adopted to define the PDE component in the PINN. As for the NN component in the PINN, most of the existing works on PINN-based traffic state estimation employ a similar NN architecture as that employed in [2], i.e., one input layer, several hidden layers, and one output layer, where the "Tanh" activation function is usually utilized in the hidden layers. Compared to the NN model, the PINN model can significantly improve traffic prediction performance in the face of a limited number of training data [11][12]. ### _MTO-based NN Training_ MTO [16][17] is a newly emerging research frontier in the field of optimization. It allows multiple relevant optimization tasks to be solved simultaneously and the knowledge acquired from solving one task is reused to help solve some other tasks via knowledge transfer so that the performance of solving each individual task gets improved. In recent years, many new MTO techniques [18][19][20] have been proposed and successfully applied in various fields [21]. One of the promising MTO application scenarios is to train NNs. It is well-known that training an NN corresponds to solve a complex non-convex optimization problem, prone to getting stuck into inferior local optima. To address this issue, the MTO-based NN training first creates multiple auxiliary training tasks relevant to the main training task. Then, both the main and auxiliary tasks are solved at the same time while allowing the knowledge obtained from one task-solving process, often in the form of promising network parameters, to assist in some other task-solving processes via knowledge transfer and reuse. As a result, the main training task can be better solved because the knowledge from relevant auxiliary tasks can help the main training task to jump out of its own inferior local optima. There exist different ways of creating auxiliary training tasks and the knowledge can be transferred and reused in different manners [10][22][23]. ## III The Proposed Method The MTO-based training paradigm for DNNs [10][22] has shown performance superiority over the traditional methods of training DNNs, where multiple auxiliary training tasks related to the given (main) training task are created and then solved together with the main task so that the useful knowledge from any individual task-solving process, e.g., network parameters, can be transferred and used to help solve some other training tasks, aiming to improve the performance of solving the main task. We extend this idea for training PINNs and choose traffic state prediction as the application scenario, where different traffic state variables that are somewhat related and multiple traffic data sets in different spatial and time zones are utilized for designing auxiliary tasks, relevant but different from the main task, to enable MTO-based training. In what follows, we will first introduce PINN's formulation in traffic state prediction and then elaborate the MTO-based PINN training framework. ### _Traffic PINNs_ Suppose the task is to estimate traffic state \(u\) (e.g., traffic flow \(q\), density \(k\), and speed \(v\).) over time \(t\) within a time span of \(T\) (seconds) in the future along a road segment of length \(D\) (meters). The PINN model, as illustrated in Fig. 1 will take as inputs time \(t\) and distance \(d\) (with respect to the road origin) and output \(\hat{u}\). Different from the traditional NN, PINN's loss function \(Loss\) has two parts, i.e., \(Loss_{NN}\) and \(Loss_{PDE}\). \(Loss_{NN}\) is typically formulated as the mean squared error (MSE) between NN's output \(\hat{u}\) and the corresponding ground truth \(u\) as follows: \[Loss_{MSE}=\frac{1}{n_{u}}\sum_{i=1}^{n_{u}}|\hat{u}(d_{i}^{u},t_{i}^{u})-u_{i} ^{u}|^{2} \tag{1}\] where \(M_{u}=\{d_{i}^{u},t_{i}^{u},u_{i}^{u}|i=1,...n_{u}\}\) represents a training set with \(n_{u}\) available training samples. The definition of \(Loss_{PDE}\) depends on the adopted PDE that governs traffic dynamics. Suppose the residual function of the PDE is denoted as \(f(d,t,u)\). \(Loss_{PDE}\) is formulated as: \[Loss_{PDE}=\frac{1}{n_{f}}\sum_{i=1}^{n_{f}}|f\left(d_{i}^{f},t_{i}^{f},\hat{u }_{i}^{f}\right)|^{2} \tag{2}\] where \(M_{f}=\{d_{i}^{f},t_{i}^{f},\hat{u}_{i}^{f}|i=1,...n_{f}\}\) is a set of \(n_{f}\) randomly sampled \(d\) and \(t\) from \([0,D]\) and \([0,T]\), respectively and the corresponding NN's outputs when they are fed into the NN as inputs. Fig. 1: A simple illustration of the PINN model. Following previous studies [13][14][24], we will employ Greenshields's LWR traffic flow model which can provide a macroscopic way for describing the evolution of traffic density \(k\) on a road network. It is based on an assumption that traffic density is a continuous function with respect to space and time, where traffic flow \(q\) is defined as the product of traffic density \(k\) and local traffic speed \(v\)[13][14]. Th model is underpinned by the following PDE: \[\frac{\partial q}{\partial d}+\frac{\partial k}{\partial t}=0 \tag{3}\] \[q=k\times v \tag{4}\] \[v=v_{f}\left(1-\frac{k}{k_{j}}\right) \tag{5}\] where \(v_{f}\) and \(k_{j}\) represent the free flow speed and the jammed density, respectively. From this PDE, we define the residual function with respect to density \(k\) or speed \(v\) as follows: \[f(d,t,k)=v_{f}\frac{\partial k}{\partial d}-2\frac{v_{f}}{k_{j}}\frac{\partial k }{\partial d}k+\frac{\partial k}{\partial t} \tag{6}\] \[f(d,t,v)=\frac{\partial v}{\partial d}k_{j}-2\frac{k_{j}}{v_{f}}\frac{\partial v }{\partial d}v-\frac{k_{j}}{v_{f}}\frac{\partial v}{\partial t} \tag{7}\] Depending on the considered prediction task (density or speed), one of the above will be used as \(Loss_{PDE}\) in the PINN. Therefore, the overall loss of the PINN is defined as: \[Loss=Loss_{NN}+Loss_{PDE} \tag{8}\] By combining the PDE-based traffic flow model and the data-driven NN model, the PINN model may rely on merely a limited amount of training data to obtain accurate prediction of traffic states. It aligns well with real-world scenarios where traffic sensors are often sparsely deployed. ### _MTO-based PINN Training_ Our proposed MTO-based PINN training framework starts with the design of auxiliary training tasks relevant to the main training task. In this work, the main task is defined as training a PINN for traffic density prediction based on a training set with known traffic density. Considering that traffic density and speed are inherently related, auxiliary tasks can be designed as training a PINN with the exact same architecture for traffic density prediction based on a different training set with known traffic density, training a PINN with the nearly same architecture (except for the output layer) for traffic speed prediction based on the same training set with known traffic speed, and training a PINN with the nearly same architecture (except for the output layer) for traffic speed prediction based on a different training set with known traffic speed, among others. The main and auxiliary training tasks will be individually solved at the same time. In the process of solving any task, when a certain knowledge transfer criterion is met, an MTO module will be triggered for incorporating the knowledge (in the form of network parameters) acquired from the other tasks. The training process for any task will be terminated when the pre-defined maximum number of training epochs is reached. In this work, we adopt an adaptive MTO triggering strategy. Specifically, if the best training loss value obtained so far cannot be improved by a decent amount (e.g., a pre-defined percentage of the best loss value obtained so far) over a period of S consecutive training epochs, so-called MTO triggering window size, the MTO module will be triggered. Suppose the MTO module is triggered for Task \(k\) (\(k\in\{1,...,N_{task}\}\)) at epoch \(i\). The current network parameters from Task \(k\) will be linearly combined with those from the other \(N_{task}-1\) tasks in a layer-wise manner to generate the new network parameters for Task \(k\). The combination coefficients \(\mathbf{\alpha^{k}}=\{a_{ij}^{k}|i=1,...,N_{task,j}=1,...,N_{layer}-1,a_{ij}^{k}\in R\}\) will be learned via solving Task \(k\) with respect to \(\mathbf{\alpha^{k}}\) while the original network parameters from all tasks are kept frozen. As such, the knowledge from the other tasks can be adaptively transferred into Task \(k\). Notably, the last (output) layer of the NN is not involved in the knowledge transfer process because the parameters in that layer are very task-specific and thus less suitable for cross-task knowledge transfer. After \(\mathbf{\alpha^{k}}\) is learned for a pre-specified number of training epochs, the new network parameters created upon it will be compared with the original Fig. 2: The basic working principle of the proposed MTO-based training framework. (pre-MTO) network parameters in terms of the corresponding training loss values. The network parameters with the smaller loss value will enter epoch \(i\)+1, and meanwhile the period of S consecutive training epochs will be re-counted from scratch. In this work, we choose to employ only one auxiliary task for simplicity. Fig. 2 illustrates the basic working principle of the proposed framework with \(N_{task}\)=2 as well as the involved MTO module. ## IV Experiments ### _Data Description_ We employ the US Highway 101 data set from the Next Generation Simulation (NGSIM) program for our study. The area of study for data collection spans around 640 meters and comprises five main lanes. The data set contains traffic data captured during a 45-min period in the morning peak, where the raw data have been aggregated every five seconds. We utilize the traffic density, speed, and flow information in the study area and exclude the initial and final road sections from our analysis due to incomplete data. Fig. 3 illustrates the distribution of normalized traffic density (via the min and max density values in the entire study area) with respect to distance \(d\) (from the road origin) and time \(t\) (in the 45-min period) for the area in the US 101 data set which is considered in this work. It illustrates multiple shockwaves, indicating the traffic congestion propagation on the freeway. We assume that in practice traffic data are only available in a few locations on the road due to the sparsely deployed traffic sensors. To evaluate the utility of the PINN in this scenario, we create two training sets from the whole data set. Data set A comprises the data from sensors located at \(d\) = 4, 8, 12, 16, 20, and 24 meters, respectively at time stamps in [0, 5, 10,..., 2695], and data set B contains the data from sensors located at \(d\) = 8, 92, 128, 292, and 408 meters, respectively at time stamps in [0, 5, 10,..., 2695]. In contrast, data set B covers a wider study area than A. In the two training sets, both distance and time are employed as the inputs, and either traffic density or speed can be adopted as the output. The test set for measuring the prediction performance of the PINN contains the data from sensors located at \(d\) \(\in\) [4, 8, 12,..., 408], respectively at time stamps in [0, 5, 10,..., 2695]. ### _Task Design_ The **main task** in this work is defined as training a PINN for making traffic density prediction based on a training set with known traffic density, i.e., Density (A) or Density (B). The **auxiliary tasks** in this work are designed to be one of the following three training tasks: * training a PINN with the same architecture as that used in the main task for traffic density prediction but based on a different training set (from the main task) with known traffic density, i.e., Density (B) or Density (A). * training a PINN with the nearly same architecture (except for the output layer) as that used in the main task for traffic speed prediction and based on the same training set (as the main task) with known traffic speed, i.e., Speed (A) or Speed (B), and * training a PINN with the nearly same architecture (except for the output layer) as that used in the main task for traffic speed prediction but based on a different training set (from the main task) with known traffic speed, i.e., Speed (B) or Speed (A). ### _Experimental Settings_ The NN component of all the PINN models used in our experiments adopts the same architecture as that employed in [11][12], i.e., a fully connected feedforward NN with one input, eight hidden, and one output layers. For training, we set batch size as 1024, and employ the Lamb optimizer [25] for training both network parameters and layer-wise weights (in the MTO module). The maximum number of training epochs for training the PINN is set to 4,000 and the MTO-triggering window size \(S\) is set to 50 with the improvement percentage set to 0.01 (of the best training loss obtained so far). Also, the Fig. 3: The spatiotemporal distribution of normalized traffic density for the area in the US 101 data set which is considered in this work. maximum number of training epochs for learning layer-wise weights in MTO is set to 200. Each method in comparison is executed for 10 independent runs. For performance evaluation, we employ the training loss of the PINN model to evaluate the training performance, and the mean absolute percentage error (MAPE) on the test set to measure PINN's generalization performance. We perform the statistical t-test at the significance level of 0.05 to compare the 10-run results of any two methods under consideration. ### _Overall Comparision_ We compare the proposed PINN training method with the traditional PINN training method for learning the same PINN model (for traffic density prediction) by using training sets A and B, respectively. Therefore, the main task is either Density (A) or Density (B). The auxiliary task adopted in the proposed training method is Density (B), Speed (A) or Speed (B) with respect to main task Density (A), and Density (A), Speed (A) or Speed (B) with respect to main task Density (B). Further, we perform a comparison with the NN-only counterpart of the PINN model to reveal the utility of the PINN. The experimental results are reported in Table I. It can be observed that the proposed MTO-based PINN training method consistently outperforms the traditional PINN training method in terms of both the loss on the training set and the MAPE on the test set for all three auxiliary tasks on both training sets A and B. Among three adopted auxiliary tasks, the speed task on a different training set outperforms the other two in terms of the eventually obtained training loss on both training sets. In addition, although the NN model can be trained to achieve the much better training loss, the corresponding MAPE on the test set is worse, implying overfitting and thus poor generalization. ### _Ablation Study_ MTO Triggering Strategy In this work, we adopt an adaptive strategy for triggering the MTO module, where the MTO is triggered whenever the best training loss value obtained so far cannot be improved by 1% over \(S\) consecutive epochs. To validate its effectiveness, we compare it with a fixed triggering strategy which regularly triggers the MTO module every 50 training epochs. Table II reports the comparison results of these two strategies in terms of their eventually obtained training loss values with respect to three different auxiliary tasks and two different training sets. We perform the statistical t-test at the significance level of 0.05 to compare these two strategies and highlight in bold the best one (with the minimum mean loss value over 10 runs) and also another if it is statistically similar to the best. It can be observed that the adaptive strategy consistently performs best across all the comparison scenarios. It is noteworthy that the adaptive strategy typically triggers the MTO module less often than the fixed strategy when using the same MTO triggering window size. For example, when the triggering window size is set to 50 and the total number of training epochs is set to 4,000, as employed in this work, the MTO triggering times for adaptive and fixed strategies are 60 and 80, respectively. It implies that the adaptive strategy may potentially reduce the computational cost by reducing MTO execution times. Fig. 4 illustrates the convergence curves of the training loss with respect to the proposed training methods equipped with the adaptive and fixed MTO triggering strategies and the traditional training method without MTO, respectively. It can be observed that regularly triggering the MTO module may result in the worse performance than the traditional training method. By using the adaptive strategy, MTO is not triggered in the beginning stage of training, but gradually and adaptively triggered to make performance improvement once the training process is stuck, as evidenced by the distribution of triggering points displayed in Fig. 4. Layer-wise Weight Initialization in the MTO Module In the MTO module, layer-wise weights \(\boldsymbol{\alpha^{k}}\), \(k=1\),..., \(N_{task}\) are learned based on the training data to enable cross-task knowledge transfer. To investigate the sensitivity of the weight learning to initialization, typically suffered by the NN training, we evaluate several different initial layer-wise weight settings. Suppose \(\boldsymbol{\alpha^{1}}\) and \(\boldsymbol{\alpha^{2}}\) are the main and auxiliary tasks under consideration. Table III shows the comparison results among five initial weight settings, where the four pairs of numbers refer to the same initial weight value for all the layers in the corresponding task, e.g., (1.0, 0.0) denotes the initial weight value of 1.0 for all layers in the main task and 0.0 for all layers in the auxiliary task; Xavier [7] refers to the uniformly random initialization. It can be observed that initialization sensitivity is not severe, though among the five compared settings, the best performer is (1.0, 0.0). In fact, this setting inherently allows for the fine-tuning of network parameters for the main task by making use of the network parameters from auxiliary tasks, and thus avoid the dramatic parameter update which may lead to performance degradation. Fig. 4: Training loss convergence curves for the proposed training method with the adaptive or fixed MTO triggering strategy and the traditional training method, where the main and auxiliary tasks are Density (B) and Speed (A), respectively. Training epochs at which MTO is triggered when using the adaptive strategy are denoted by yellow dots. ### _Parameter Sensitivity Analysis_ As discussed previously, the adaptive MTO triggering strategy plays an essential role in the proposed PINN training framework, where the MTO triggering window size \(S\) is a key parameter involved. In this section, we conduct a parameter sensitivity analysis on \(S\) with respect to the performance of the proposed training method. Specifically, we evaluate the total number of times that the MTO module gets triggered during the entire training period and the eventually obtained training loss values over 10 runs as the MTO triggering window size varies from 10 to 120 at the step size of 10 for the proposed method equipped with each of the three different auxiliary tasks on training set A. The results are illustrated in Fig. 5, which indicate that when the window size increases, the total number of MTO triggering times decreases and the training performance (in terms of the loss) fluctuates and accordingly the best window sizes, based on the training performance, for different auxiliary tasks are not same. In this work, we choose to use the window size of 50 in all experiments considering the overall performance across different auxiliary tasks. ## V Conclusions and Future Work We proposed a novel PINN training framework based on MTO. In this framework, one or more auxiliary training tasks are created and solved together with the main training task so that solving auxiliary tasks may help better solve the main task via knowledge transfer, where an MTO module is designed to enable knowledge transfer. We applied the proposed method to train the PINN for traffic density prediction, where different auxiliary tasks were designed and evaluated. Compared to the traditional PINN training method, our proposed MTO-based method demonstrated the performance advantages in terms of both training and testing. Our future work includes evaluation of the proposed method by using more than one auxiliary tasks and extending its application to the other traffic problems and non-traffic scenarios. We will also study how to better balance the two loss parts in an adaptive manner based on the strategies proposed in our previous works [26][27] to facilitate training.
2303.00706
Predicting the wall-shear stress and wall pressure through convolutional neural networks
The objective of this study is to assess the capability of convolution-based neural networks to predict wall quantities in a turbulent open channel flow. The first tests are performed by training a fully-convolutional network (FCN) to predict the 2D velocity-fluctuation fields at the inner-scaled wall-normal location $y^{+}_{\rm target}$, using the sampled velocity fluctuations in wall-parallel planes located farther from the wall, at $y^{+}_{\rm input}$. The predictions from the FCN are compared against the predictions from a proposed R-Net architecture. Since the R-Net model is found to perform better than the FCN model, the former architecture is optimized to predict the 2D streamwise and spanwise wall-shear-stress components and the wall pressure from the sampled velocity-fluctuation fields farther from the wall. The dataset is obtained from DNS of open channel flow at $Re_{\tau} = 180$ and $550$. The turbulent velocity-fluctuation fields are sampled at various inner-scaled wall-normal locations, along with the wall-shear stress and the wall pressure. At $Re_{\tau}=550$, both FCN and R-Net can take advantage of the self-similarity in the logarithmic region of the flow and predict the velocity-fluctuation fields at $y^{+} = 50$ using the velocity-fluctuation fields at $y^{+} = 100$ as input with about 10% error in prediction of streamwise-fluctuations intensity. Further, the R-Net is also able to predict the wall-shear-stress and wall-pressure fields using the velocity-fluctuation fields at $y^+ = 50$ with around 10% error in the intensity of the corresponding fluctuations at both $Re_{\tau} = 180$ and $550$. These results are an encouraging starting point to develop neural-network-based approaches for modelling turbulence near the wall in large-eddy simulations.
Arivazhagan G. Balasubramanian, Luca Guastoni, Philipp Schlatter, Hossein Azizpour, Ricardo Vinuesa
2023-03-01T18:03:42Z
http://arxiv.org/abs/2303.00706v1
# Predicting the wall-shear stress and wall pressure through convolutional neural networks ###### Abstract The objective of this study is to assess the capability of convolution-based neural networks to predict the wall quantities in a turbulent open channel flow, starting from measurements within the flow. Gradually approaching the wall, the first tests are performed by training a fully-convolutional network (FCN) to predict the two-dimensional velocity-fluctuation fields at the inner-scaled wall-normal location \(y^{+}_{\rm target}\), using the sampled velocity fluctuations in wall-parallel planes located farther from the wall, at \(y^{+}_{\rm input}\). The predictions from the FCN are compared against the predictions from a proposed R-Net architecture as a part of the network investigation study. Since the R-Net model is found to perform better than the FCN model, the former architecture is optimized to predict the two-dimensional streamwise and spanwise wall-shear-stress components and the wall pressure from the sampled velocity-fluctuation fields farther from the wall. The data for training and testing is obtained from direct numerical simulation (DNS) of open channel flow at friction Reynolds numbers \(Re_{\tau}=180\) and \(550\). The turbulent velocity-fluctuation fields are sampled at various inner-scaled wall-normal locations, _i.e._\(y^{+}=\{15,30,50,100,150\}\), along with the wall-shear stress and the wall pressure. At \(Re_{\tau}=550\), both FCN and R-Net can take advan tage of the self-similarity in the logarithmic region of the flow and predict the velocity-fluctuation fields at \(y^{+}=50\) using the velocity-fluctuation fields at \(y^{+}=100\) as input with about 10% error in prediction of streamwise-fluctuations intensity. Further, the network model trained in this work is also able to predict the wall-shear-stress and wall-pressure fields using the velocity-fluctuation fields at \(y^{+}=50\) with around 10% error in the intensity of the corresponding fluctuations at both \(Re_{\tau}=180\) and 550. These results are an encouraging starting point to develop neural-network-based approaches for modelling turbulence near the wall in numerical simulations, especially large-eddy simulations (LESs). keywords: Turbulent channel flow, Wall-shear stress, Deep learning, Fully Convolutional Network, Self-similarity + Footnote †: journal: Journal of Computational Physics ## 1 Introduction The direct numerical simulation (DNS) of turbulent flows is computationally challenging owing to the cost arising from the resolution requirements to simulate all the length and time scales of fluid motion. Turbulent flows in various engineering applications and practical flows of interest are characterized by a very high Reynolds number and it becomes computationally unfeasible to simulate the wide range of scales associated with these flows. For this reason, simpler canonical flow cases like the channel flows (Hoyas et al., 2022) and turbulent boundary layers (Sillero et al., 2014; Pozuelo et al., 2022) are widely studied using DNSs at relatively low Reynolds number to understand the physics of flow and thereby to model them. At higher Reynolds numbers, several investigations have been performed using high-resolution large-eddy simulations (Schlatter et al., 2010; Bobke et al., 2017; Li et al., 2021). Apart from canonical flows, LES has also been widely employed for different practical flows of interest like urban flows (Atzori et al., 2022) and the flow around an airfoil (Vinuesa et al., 2018; Tamaki and Kawai, 2022). Large eddy simulations address the issue of computational cost by filtering out the smallest turbulent scales and modelling the eddies that are smaller than the filter size. However, it should be noted that despite modelling the effects of the smallest scales, LESs can become computationally expensive at high Reynolds number and especially in wall-bounded flows. This is due to the resolution requirements for resolving the dynamically important flow structures in the viscous and the logarithmic layers, which scale as \(\mathcal{O}(Re_{\tau}^{2})\)(Larsson et al., 2016), where the friction Reynolds number \(Re_{\tau}\) is defined in terms of reference length \(h\) and friction velocity \(u_{\tau}=\sqrt{\tau_{w}/\rho}\) where \(\tau_{w}\) is the wall-shear stress and \(\rho\) is the fluid density. In wall-bounded turbulent flows, the size of the scales that characterize the near-wall region is very small. Hence, a wall-resolved LES can have a significant cost with increasing Reynolds number (Choi and Moin, 2012) and approaches to that of direct numerical simulations which prevents its use in high Reynolds number wall-bounded flows that occur in engineering applications (Park and Moin, 2014).. This problem is addressed by introducing wall models, which allow a manageable resolution while taking into account the characteristic of the flow related to wall presence. Several methods have been proposed to model the near-wall region and simulate complex flows at higher Reynolds numbers. Such methods mainly focused on wall-stress-modelling in addition to the hybrid LES/Reynolds-averaged Navier Stokes (RANS) approach. These wall models aim to reproduce the most important features of the inner-layer dynamics like (_e.g._ streaks and streamwise vortices), without integrating the Navier-Stokes equations in that flow region. Conventionally, the wall models were either based on physics or mathematical arguments (Larsson et al., 2016). Focusing our attention towards wall-shear stress modelling, the algebraic equilibrium wall model is the most commonly used method to specify wall-shear stress owing to its simplicity, which enforces the law of the wall both locally and instantaneously (Schumann, 1975) based on the idea that turbulence close to the wall reaches a state of equilibrium where the production and dissipation are balanced. However, the equilibrium assumption may not hold for flows with adverse pressure gradients or for cases with strong non-equilibrium effects. In particular, the integral wall model aims to address the non-equilirbium effects by solving a vertically integrated momentum equation which adds to the equilibrium logarithmic velocity profile (Yang et al., 2015). Other studies like Wang and Moin (2002) and Kawai and Larsson (2012) have also explored the non-equilibrium wall models which involve solving RANS equations. On the other hand, zonal model solves the thin-boundary-layer equation on a set of refined mesh near the wall (Park and Moin, 2014; Larsson et al., 2016). The wall-shear stress fluctuations modelling (Inoue et al., 2012) and dynamic slip wall models (Bose and Moin, 2014; Bae et al., 2018) are few other approaches to obtain the required wall-shear stress. A classification of wall models with the corresponding assumptions and error sources is presented in Piomelli and Balaras (2002). A recent review of wall models can be found in Larsson et al. (2016) and Bose and Park (2018). One alternative approach was proposed by Mizuno and Jimenez (2013): by taking advantage of the self-similarity hypothesis, according to which the eddy sizes scale linearly in the logarithmic region at high Reynolds number, an _off-wall_ boundary condition was defined. This approach moves the boundary of the computational domain away from the wall, removing the need to simulate the small scales associated with it. In their work, the velocity field at the off-wall boundary location is substituted by a re-scaled and a shifted copy of an interior reference plane farther from the wall. This allows the logarithmic region to be simulated without considering the near-wall dynamics. In this work, we investigate the possibility to train a neural-network model that predicts the flow close to the wall based on information farther from the wall, with the future possibility to apply it as an off-wall boundary condition. Recently, machine-learning-based approaches have been increasingly used in the study of turbulent flows for a variety of tasks related to flow prediction (Duraisamy et al., 2019; Brunton et al., 2020; Guastoni et al., 2021, 2022), prediction of temporal dynamics (Srinivasan et al., 2019; Eivazi et al., 2021; Borrelli et al., 2022), extraction of flow patterns (Jimenez, 2018; Eivazi et al., 2022; Martinez-Sanchez et al., 2023), generation of inflow conditions (Fukami et al., 2019; Yousif et al., 2023) or flow control (Rabault et al., 2019; Vinuesa et al., 2022; Guastoni et al., 2023) to name a few. In addition, neural network models have started offering new interesting opportunities to formulate efficient data-driven wall models, as highlighted in Vinuesa and Brunton (2022). Yang et al. (2019) utilized physics informed neural network (PINN) to propose a wall model, where the knowledge of mean flow scaling was incorporated in the feed-forward neural network to predict the LES-grid filtered wall-shear stress from the velocity at a distance from the wall. Their predictive model was shown to capture the law of the wall at different Reynolds number which was not present in the training dataset. Zhou et al. (2021) trained a feed-forward neural network to predict the wall-shear stress as a function of velocity and pressure gradients at a off-wall location in a periodic hill flow. Although the _a priori_ tests showed good results, _a posteriori_ tests did not provide accurate results. Whereas towards defining an off-wall boundary condition, the works like Moriya et al. (2021) and Bae and Koumoutsakos (2022) have exhibited promising potential of deep-learning and reinforcement learning based approaches in predicting the flow close to the wall. A survey of machine-learning-based wall models for large-eddy simulations can be found in Vadrot et al. (2022). The advantage of such machine-learning-based models is that once the model is trained, the evaluation of the neural network is computationally cheap and they can provide a valid alternative to the models that are currently employed within numerical simulations. In the present work, we first employ a fully convolutional network to predict the near-wall velocity-fluctuation fields using the velocity-fluctuation fields farther from the wall, corresponding to \(Re_{\tau}=180\). In addition, we explore the capability of a fully-convolutional network with residual skip-connections (denoted as R-Net) in predicting the near-wall velocity fluctuation fields. Then, the described network models (FCN and R-Net) are used to predict the velocity-fluctuation fields closer to the wall that is present in the self-similar region at \(Re_{\tau}=550\). A brief comparison of the results obtained from FCN and R-Net is performed, in order to provide an insight to designing an efficient network model in predicting wall quantities. Finally, the R-Net architecture model is used to predict the wall-shear stress and wall pressure using the velocity-fluctuation fields away from the wall. The manuscript is structured as follows. An overview of the methodology employed in this study is provided in SS2: the architecture of the neural-network models are introduced in SS2.1 and the dataset utilized to train the network models is described in SS2.2. The metrics used to compare the performance of the different networks are reported in SS2.3. The results are discussed in SS3, with SS3.1-SS3.4 containing the results corresponding to inner predictions, predictions in the self-similar region, network comparison and wall predictions, respectively. Finally, the conclusions are provided in SS4. ## 2 Methodology Taking inspiration from the data-driven approach proposed by Guastoni et al. (2021) for _non-intrusive_ sensing, where the turbulent velocity field at a given wall-normal distance is predicted by using quantities measured at the wall as inputs, we aim to explore the capability of convolutional networks to solve the opposite problem, where the inputs are located at a certain wall-normal distance with the objective to predict the wall-shear quantities and wall-pressure. We denote the prediction of wall quantities using the fields farther from the wall as _wall predictions_. As a primary step towards understanding the capability of convolutional networks in predicting the wall quantities, first we consider a simpler problem which is to predict the velocity fluctuation fields closer to the wall at \(y^{+}_{\rm target}\) using the velocity-fluctuation fields farther from the wall at \(y^{+}_{\rm input}\) as inputs. Note that '\(+\)' denotes inner scaling, _i.e._ scaling with the friction velocity \(u_{\tau}\) and the fluid kinematic viscosity \(\nu\). Such predictions where \(y^{+}_{\rm train}>y^{+}_{\rm target}\) are designated as _inner predictions_ whereas, the cases in which \(y^{+}_{\rm train}<y^{+}_{\rm target}\) are denoted as _outer predictions_. We test the performance of the networks for inner predictions by analyzing the mean-squared error in the instantaneous predictions and in the turbulent statistics as a function of the distance between the input and target velocity plane, \(\Delta y^{+}\left(||y^{+}_{\rm input}-y^{+}_{\rm target}||\right)\). This parametric study is performed at a lower \(Re_{\tau}\) of 180, however a selected case is considered at a higher Reynolds number, where self-similarity can be exploited by the prediction model. The assumption of self-similarity in a channel of height \(2h\) for the two wall-normal planes at \(y/h=0.2\) and \(y/h=0.1\) (where the length scales are proportional to \(y\)) at friction Reynolds number \(Re_{\tau}\approx 1000\) was the starting point to design an off-wall boundary condition in the model by Mizuno and Jimenez (2013). In the present work, we perform predictions in the self-similar region at a comparatively lower Reynolds number of \(Re_{\tau}=550\), with the wall-normal planes corresponding to \(y/h=0.2\) and \(y/h=0.1\) in scaled outer units. Such wall-normal planes correspond to \(y^{+}=100\) and \(y^{+}=50\), in inner-scaling respectively. The predictions from fully-convolutional networks (FCNs) are compared with the ones from R-Net architecture models. The R-Net architecture is then trained to predict the wall-shear and wall pressure quantities using the velocity fluctuation fields as inputs at different wall-normal distances. The prediction of wall quantities using R-Net are summarized for the two-different Reynolds number considered in this study. ### Network architecture A FCN similar to the one proposed by Guastoni et al. (2022) is used in this study which adopts convolution operations in each layer (LeCun et al., 1998) as given by: \[F_{i,j}=\sum_{m}\sum_{n}I_{i-m,j-n}K_{m,n}\,, \tag{1}\] where \(\mathbf{I}\in\mathbb{R}^{d_{1}\times d_{2}}\) is the input, \(\mathbf{K}\in\mathbb{R}^{k_{1}\times k_{2}}\) is the kernel (or filter) containing the parameters to be learned and \(\mathbf{F}\) is the resulting feature map. The convolutional kernels are defined by their width and height and in this study, kernels of the size \(3\times 3\) is used. A convolutional layer is defined by the number of kernels and the size of the kernel, which contain the learnable parameters. The transformed output is called _feature map_. Multiple feature maps are usually stacked and followed by an element-wise activation function to make each layer a non-linear transformation. The non-linearity in the activation of layers is introduced by the rectified linear unit (ReLU) activation function. The output of the activation function is fed into another convolutional layer, which allows the next layer to combine the features individually identified in each map. This enables the prediction of larger and more complex features for progressively deeper networks. Batch normalization (Ioffe and Szegedy, 2015) is performed after each convolutional layer (except for the last one). Since the ReLU activation function filters out the negative values, a modified ReLU function is used just before the output layer with a threshold of \(-1\) (for prediction of velocity fluctuations) or \(-25\) (for prediction of fluctuation wall quantities). The schematic of a fully convolutional network used in this study is shown in figure 1. The FCN employed in this study has 31 hidden layers with a total of 2,902,791 trainable parameters. A fully-convolutional network with skip-connections (He et al., 2016) between hidden layers \(i\) and \(N-i-1\) (where \(N\) indicates the total number of hidden layers in the network) is also investigated in this study and is denoted as R-Net. Note that the skip-connections resemble that of the ones employed in a typical U-Net architecture (Ronneberger et al., 2015). R-Net is an intermediary step between FCN and U-Net which does not employ up-sampling as present in a U-Net. The proposed R-Net architecture is shown in figure 1. The feature maps in the upstream part of the network are of different size compared to the ones in the downstream part of the network. Hence while performing skip connections, the feature maps from the upstream part of the network is cropped to the desired shape and concatenated to the feature maps in the downstream part of the network. The R-Net architecture consists of a total of 31 hidden layers with 2,568,681 trainable parameters. ### Dataset The convolutional networks are trained to predict two-dimensional velocity-fluctuation fields at the given wall-normal location \(y^{+}_{\text{target}}\), using velocity-fluctuation fields farther from the wall, at \(y^{+}_{\text{input}}\), as inputs (where \(y^{+}_{\text{input}}>y^{+}_{\text{target}}\)). The velocity-fluctuations fields are sampled from a direct numerical Figure 1: Schematic representation of the (top) FCN architecture and (bottom) R-Net architecture. The number of kernels applied to each of the layers is indicated in the figure. Here, the inputs correspond to the velocity-fluctuation fields at \(y^{+}=50\) and the outputs in FCN are the velocity-fluctuation fields at \(y^{+}=15\). In R-Net, it corresponds to the wall-shear stress components and the wall pressure. The skip-connections from the upstream part of the R-Net architecture to the downstream part of the network are indicated in red. simulation of an open channel flow, at friction Reynolds numbers \(Re_{\tau}=180\) and \(Re_{\tau}=550\), performed with the pseudo-spectral solver SIMSON (Chevalier et al., 2007). The reference length \(h\) for this flow case is the open-channel height and the sampled wall-parallel fields have size \(L_{x}\times L_{z}=4\pi h\times 2\pi h\). Periodic boundary conditions are imposed in the wall-parallel directions. The turbulent flow fields are sampled at wall-normal locations, \(y^{+}=15,30,50,100\) and \(150\). The resolution of the sampled fields is \((N_{x},N_{z})=(192,192)\) for \(Re_{\tau}=180\) and \((512,512)\) for \(Re_{\tau}=550\). Further details on the generation of dataset are available in Guastoni et al. (2021). The velocity fields are stored with a constant sampling period of \(\Delta t_{s}^{+}=5.08\) for \(Re_{\tau}=180\) and at \(\Delta t_{s}^{+}=1.49\) for \(Re_{\tau}=550\). The networks are trained using 50,400 instantaneous fields for \(Re_{\tau}=180\) and with 19,920 fields for \(Re_{\tau}=550\), split into training and validation sets, with a ratio of 4 to 1. The input velocity fluctuation fields to the network are padded in the wall-parallel directions using a periodic padding operation, to enforce periodicity in the obtained predictions. In the padding operation, a total of 64 points (32 points on either side) are added along the boundary of the fields. Thereby the size of the input fields is \(\approx 77\%\) larger than that of the outputs for the fields at \(Re_{\tau}=180\) whereas, it is \(\approx 26\%\) for the fields at \(Re_{\tau}=550\). Since the receptive field of the networks considered here is \(63\times 63\), the size of the outputs from the network is slightly larger than the sampled DNS flow fields and hence a cropping operation is performed to obtain the fields matching the size of the DNS fields. The input fluctuation fields to the network are scaled such that they have a similar magnitude as given by: \[\hat{u}=u\,,\;\;\hat{v}=v\frac{u_{\rm RMS}}{v_{\rm RMS}}\,,\;\;\hat{w}=w\frac {u_{\rm RMS}}{w_{\rm RMS}}\,, \tag{2}\] where RMS refers to root-mean-squared quantities. The same scaling is used when the network outputs are velocity fields at a different wall-normal location. For the prediction of fluctuations of the wall quantities, the outputs are normalized by the respective RMS quantities as defined by: \[\frac{\overline{\partial u}}{\partial y}=\frac{\partial u/\partial y}{\partial u /\partial y_{\rm RMS}}\,,\;\;\frac{\overline{\partial w}}{\partial y}=\frac {\partial w/\partial y}{\partial w/\partial y_{\rm RMS}}\,,\;\;\overline{p}= \frac{p}{p_{\rm RMS}}\,. \tag{3}\] In the remainder of the paper \(\overline{\cdot}\) is dropped for clarity when referring to normalized quantities. ### Network performance measures The mean-squared error (MSE) between the instantaneous DNS fields (\(u_{\text{DNS}}\)) and the predictions (\(u_{\text{FCN}}\) denotes prediction from FCN; \(u_{\text{RN}}\) indicates prediction from R-Net) is used as the loss function for training the networks introduced in this study. It can be written as: \[\begin{split}\mathcal{L}(u_{\text{FCN}};u_{\text{DNS}})& =\frac{1}{N_{x}N_{z}}\sum_{i=1}^{N_{x}}\sum_{j=1}^{N_{z}}\left|u_{ \text{FCN}}(i,j)-u_{\text{DNS}}(i,j)\right|^{2},\\ \mathcal{L}(u_{\text{RN}};u_{\text{DNS}})&=\frac{1 }{N_{x}N_{z}}\sum_{i=1}^{N_{x}}\sum_{j=1}^{N_{z}}\left|u_{\text{RN}}(i,j)-u_{ \text{DNS}}(i,j)\right|^{2}.\end{split} \tag{4}\] The performance of the network is evaluated based on the quality of the instantaneous predictions in the test dataset, whose samples are obtained from simulations initialized with different random seeds, in order to ensure that the training and test datasets do not exhibit unwanted correlations. A total of 8,880 samples and 3,320 samples are used to obtain the converged statistics for \(Re_{\tau}=180\) and \(Re_{\tau}=550\), respectively. The sampling period for the test dataset is slightly different from the one used in the training dataset. We consider \(\Delta t_{s}^{+}=1.69\) for \(Re_{\tau}=180\) and \(\Delta t_{s}^{+}=1.49\) for \(Re_{\tau}=550\). It should be noted that the quality of instantaneous predictions improves when the network is trained with less-correlated samples (_i.e. higher \(\Delta t_{s}^{+}\)_), provided that the network has sufficient capacity (Guastoni et al., 2021). The predictions are also evaluated from the statistical point of view, namely considering the error in RMS quantities of velocity fluctuations: \[\begin{split} E_{\text{RMS;FCN}}(u)&=\frac{\left|u _{\text{RMS,FCN}}-u_{\text{RMS,DNS}}\right|}{u_{\text{RMS,DNS}}}\,,\\ E_{\text{RMS;RN}}(u)&=\frac{\left|u_{\text{RMS, RN}}-u_{\text{RMS,DNS}}\right|}{u_{\text{RMS,DNS}}}\,,\end{split} \tag{5}\] and the instantaneous correlation coefficient between the predicted and the DNS fields: \[\begin{split} R_{\text{FCN;DNS}}(u)&=\frac{\left\langle u _{\text{FCN}}u_{\text{DNS}}\right\rangle_{x,z,t}}{u_{\text{RMS,FCN}}u_{\text{ RMS,DNS}}}\,,\\ R_{\text{RN;DNS}}(u)&=\frac{\left\langle u_{\text{ RN}}u_{\text{DNS}}\right\rangle_{x,z,t}}{u_{\text{RMS,RN}}u_{\text{RMS, DNS}}}\,,\end{split} \tag{6}\] with \(\langle\cdot\rangle\) corresponding to the average in space or time, depending on the subscript. Note that the argument \(u\) in equations (5) and (6) refers to the corresponding measures for streamwise velocity component. For wall predictions as discussed in SS3.4, the argument is either \(u_{y}\) or \(w_{y}\) or \(p\), which correspond to streamwise wall-shear stress, spanwise wall-shear stress and wall pressure, respectively. The sub-script 'pred' is also used in the text to indicate the predicted quantity from the network. Finally, a comparison of the pre-multiplied two-dimensional power-spectral density is performed to verify the distribution of energy in different length scales. The two-dimensional (2D) pre-multiplied power-spectral density (PSD) \(k_{z}k_{x}\phi_{ij}\left(\lambda_{x}^{+},\lambda_{z}^{+}\right)\) is obtained in the streamwise and spanwise directions for the target DNS fields in the test dataset and is compared against the spectra obtained with the corresponding predictions from the network. Note that here \(k_{x}\), \(k_{z}\) denote wavenumbers in the streamwise and spanwise directions, with the corresponding wavelengths in inner-scaled units denoted as \(\lambda_{x}^{+}\), \(\lambda_{z}^{+}\). \(\phi_{ij}\) is the power-spectral density defined for the particular quantity \(ij\). ## 3 Results ### Inner predictions In order to understand how the MSE is affected by the separation distance, a total of 10 predictions are performed with the velocity fields obtained at various wall-normal locations from the DNS simulation and we refer to them as _inner_ predictions, with different separation distances defined as: \(\Delta y^{+}=y_{\text{input}}^{+}-y_{\text{target}}^{+}\). The input velocity-fluctuation field closest to the wall is located at \(y^{+}=30\) and the corresponding target field at \(y^{+}=15\). The training of the FCN and R-Net used for inner predictions consisted of 50 epochs, where an epoch identifies a complete pass through the data in the training dataset. The mean-squared error in the instantaneous predictions, the relative percentage error in the prediction of root-mean-squared (RMS) fluctuations and the correlation coefficient between the predicted fields from FCN and the DNS fields are shown in figure 2, for the streamwise component of velocity fluctuations. The MSE grows almost linearly with respect to \(\Delta y^{+}\). However, from a qualitative analysis of the predictions, the performance is significantly degraded for \(\Delta y^{+}>80\). This is perhaps more evident when the statistical error is considered. For larger separation distances, the error in predicting the streamwise fluctuation intensity is above 30% and we also observe a difference in the slope of the curves as the separation distance increases for \(\Delta y^{+}>80\). The correlation coefficient between the predicted and the DNS fields shows a trend similar to that of the MSE. For smaller separation distances, the correlation coefficient is high and close to 1, then it rapidly decreases with \(\Delta y^{+}\). From figure 2 we can conclude that a correlation coefficient \(R_{\rm FCN;DNS}(u)\approx 0.8\) is the minimum requirement to have convincing predictions. Out of the three velocity components predicted by the FCN network, the streamwise result is used as a reference because it is the most energetic one, influencing most of the overall network performance. The other two velocity components predicted along with the streamwise one are typically of the similar magnitude or slightly worse in terms of both statistical error and correlation coefficient. When the input and the target fields are separated by a large wall-normal distance (\(\Delta y^{+}>80\)), it can be difficult for the networks to learn the relation between input and output. One possible explanation for this is the poor correlation between the input and the target fields for larger separation distances. For smaller \(\Delta y^{+}\), there is a significant correlation between the flow features while for larger \(\Delta y^{+}\) the correlation drops drastically and the quality of predictions is reduced. The study by Sasaki et al. (2019) showed the lack of coherence (analogous to correlation and defined in frequency domain) in the short wavelengths (_i.e._ in the small scales) between the input and target velocity fields for large \(\Delta y^{+}\). These observations indicate that, for larger \(\Delta y^{+}\), it would be harder to predict the fields using FCN. Additionally, the higher errors in the prediction of the target fields with larger separation distances can be attributed to the limitation of the convolutional operation when it is used to predict the smaller scales in the target plane (which is closer to the wall). This is because the convolutional operation acts as a filter on the input data. Hence, it becomes difficult for the network to predict the high-frequency content in the output. If we consider the results at a given separation distance, the MSE in the streamwise component of velocity fluctuation increases as the predicted velocity field is closer to the wall. This is because the velocity-fluctuation fields closer to the wall are characterized by smaller scales and it is harder to predict them from the input velocity fields that may not clearly exhibit such behaviour. Additional complexity arises due to the reduced variability of features in the receptive field (the region of input field from which a single point in the target is obtained) of the input velocity planes, compared to the target velocity planes closer to the wall. We verified this hypothesis by Figure 2: Variation of (top-left) mean-squared error normalized with the square of the RMS, (top-right) relative error in prediction of RMS fluctuation, (bottom) correlation coefficient between the predicted and DNS fields for streamwise velocity component with respect to separation distance for inner predictions. inverting the input and target velocity fields (so that \(y^{+}_{\rm input}<y^{+}_{\rm target}\)) and training the network models to predict the flow farther away from the wall, using near-wall velocity fields as inputs. These predictions are named _outer_ predictions and they are similar to the ones performed by Guastoni et al. (2022) except that the inputs are velocity-fluctuation fields at a given wall-normal distance, instead of the wall-shear stresses and the wall pressure. The inner predictions are more complicated because the smaller scales have to be inferred from the larger ones. Indeed, the network models provide a lower MSE in outer predictions compared to inner predictions due to the wide range of small scales in the input velocity fields closer to the wall. The results obtained for outer predictions are provided in A. ### Prediction in the self-similar region From the previous results, we find that it is challenging for the networks to find a non-linear transfer function between the input and output fields with larger \(\Delta y^{+}\). At higher Reynolds number, despite the larger range of scales in the flow field, this task becomes simpler because it is possible to exploit the linear dependence of eddy size with respect to the distance from the wall within the logarithmic layer. To this end, we consider the predictions at \(y^{+}=50\) (\(y/h=0.1\)) using the velocity-fluctuation fields at \(y^{+}=100\) (\(y/h=0.2\)) for \(Re_{\tau}=550\). These wall-normal locations are similar to the boundary and the reference planes considered by Mizuno and Jimenez (2013) for the studied \(Re_{\tau}\). It should be noted that the linear dependence was originally hypothesized at an asymptotic limit, at very high Reynolds number but, it was also used for finite Reynolds numbers. In figure 3 we show a qualitative comparison of the streamwise, wall-normal and spanwise velocity fluctuations predicted by the FCN and R-Net, compared with the reference DNS data. The quality of prediction is quantitatively assessed using the performance metrics introduced in SS2.3 and they are summarized in the tables 1, 2 for the FCN and R-Net predictions at \(y^{+}=50\). Since the training procedure is stochastic, the reported errors in the predictions are averaged over 3 different models obtained with different initializations of the learnable parameters of the network. \begin{table} \begin{tabular}{c c c c} & & \(i\) & \\ \cline{2-4} Parameters & \(u\) & \(v\) & \(w\) \\ \hline \(\mathcal{L}(i_{\text{FCN}};i_{\text{DNS}})/i_{\text{RMS}}^{2}\) & 0.241 \(\pm\) 0.004 & 0.425 \(\pm\) 0.009 & 0.324 \(\pm\) 0.007 \\ \(E_{\text{RMS;FCN}}(i)\) [\%] & 12.15 \(\pm\) 1.33 & 22.1 \(\pm\) 3.46 & 16.91 \(\pm\) 2.19 \\ \(R_{\text{FCN;DNS}}\) & 0.871 \(\pm\) 0.003 & 0.759 \(\pm\) 0.006 & 0.821 \(\pm\) 0.004 \\ \end{tabular} \end{table} Table 1: Model-averaged errors in the FCN predictions of velocity fluctuation fields at \(y^{+}=50\) from \(y^{+}=100\) corresponding to \(Re_{\tau}=550\) \begin{table} \begin{tabular}{c c c c} & & \(i\) & \\ \cline{2-4} Parameters & \(u\) & \(v\) & \(w\) \\ \hline \(\mathcal{L}(i_{\text{FN}};i_{\text{DNS}})/i_{\text{RMS}}^{2}\) & 0.239 \(\pm\) 0.003 & 0.425 \(\pm\) 0.004 & 0.322 \(\pm\) 0.003 \\ \(E_{\text{RMS;RN}}(i)\) [\%] & 10.81 \(\pm\) 1.14 & 18.4 \(\pm\) 1.22 & 14.58 \(\pm\) 2.44 \\ \(R_{\text{RN;DNS}}\) & 0.873 \(\pm\) 0.002 & 0.763 \(\pm\) 0.002 & 0.824 \(\pm\) 0.002 \\ \end{tabular} \end{table} Table 2: Model-averaged errors in the R-Net predictions of velocity fluctuation fields at \(y^{+}=50\) from \(y^{+}=100\) corresponding to \(Re_{\tau}=550\) At \(y^{+}=50\), the relative error in the RMS streamwise velocity fluctuations from the FCN and R-Net is around 10%, which is similar to that observed in the low \(Re_{\tau}\) case. Also, the correlation between the predicted and the DNS velocity-fluctuation field in the streamwise direction is more than 85% as can also be observed in tables 1 and 2. Note that the convolutional networks are not explicitly optimized to reproduce the statistical behaviour of the flow, so the results in this metric depend entirely on the capability of the neural network to predict the instantaneous velocity-fluctuation fields. fluctuation fields are well represented in the predictions from FCN and R-Net. The predictions in the smaller scales are also in good agreement with the DNS reference. On the other hand, this is not true for the predictions of the wall-normal and the spanwise velocity-fluctuation fields, which appear smoother than their DNS counterpart, as if a low-pass filter was used. This qualitative analysis is confirmed by the pre-multiplied two-dimensional power-spectral density of the streamwise, wall-normal and spanwise fluctuations shown in figure 4. From the spectra, it is possible to observe how the energy content of the velocity fields is more accurately reproduced in the streamwise direction, although all three velocity-component predictions lack energy at the shortest wavelengths. This result highlights that the self-similarity can be implicitly utilized by the FCN in predicting the velocity-fluctuation fields in the overlap region at higher \(Re_{\tau}\). These preliminary results indicate the advantage of incorporating the physical knowledge available for wall-bounded flows during the development of prospective data-driven wall models for LES. Figure 4: Pre-multiplied two-dimensional power-spectral densities for \(Re_{\tau}=550\) at \(y^{+}=50\). The contour levels contain 10%, 50% and 90% of the maximum DNS power-spectral density. Shaded contours refer to DNS data and the dashed contour lines correspond to FCN and R-Net predictions. ### Comparison of network performances A brief comparison of the network performance between the FCN and the proposed R-Net architecture is performed, with a motivation towards identifying the capability of the network architectures in predicting the flow quantities closer to the wall and thereby enabling the choice of employing an efficient neural network in predicting wall quantities. Overall, from the results discussed in SS3.1-3.2, it is observed that both the network architectures are able to predict the velocity fluctuation fields closer to the wall with similar order of accuracy. However, from figure 2, it is observed that for larger separation distances between the inputs and outputs, R-Net architecture tends to provide better quality of predictions in comparison to the results obtained from FCN. Whereas for smaller separation distances, the performance is very similar and in some cases slightly better when compared with the performance of FCN. Further, the R-Net architecture is well-suited to capture the overall turbulent kinetic energy in the predictions as close as possible to the DNS when compared against the results from FCN. This is also observed from the comparison of the pre-multiplied power sepctral density plots obtained for predicting the velocity fluctuation fields at \(y^{+}=30\) from the velocity fluctuation fields at \(y^{+}=150\) for \(Re_{\tau}=180\) as shown in figure 5. Although neither of the two architectures is able to capture the small scales in the velocity-fluctuation fields closer to the wall, the spectra of the predicted fluctuation fields from R-Net exhibits better agreement with that obtained from DNS. This indicates that the R-Net architecture is able to take advantage of the skip-connections in steering the network towards identifying the most energetic scales in the outputs. Further, the possible similarity in the large scales between the input and output fields are better exploited by the skip-connections in R-Net in comparison to the FCN architecture and hence, the R-Net architecture is able to predict well the most energetic scales in all components of the predictions. In addition, it should also be noted that the size of the proposed R-Net architecture is about 11% smaller than that of the FCN, which also highlights that the R-Net is able to reuse the features learnt in the upstream part of the network towards identifying the outputs with similar or better accuracy in comparison to FCN. Further, from tables 1 and 2, a similar magnitude of accuracy is obtained in predicting the fields in the self-similar region. Possibly, for larger separation distances we might also observe better predictions in R-Net relative to FCN for the fields corresponding to \(Re_{\tau}=550\), which was not verified in this study. Figure 5: Pre-multiplied two-dimensional power-spectral densities for \(Re_{\tau}=180\) at \(y^{+}=30\). The contour levels contain 10%, 50% and 90% of the maximum DNS power-spectral density. Shaded contours refer to DNS data and the dashed contour lines correspond to FCN and R-Net predictions. ### Prediction of wall quantities The proposed R-Net architecture is employed to predict the wall quantities such as streamwise wall-shear stress, spanwise wall-shear stress and wall pressure using the velocity-fluctuation fields at a certain \(y^{+}\) plane as inputs. A sample qualitative prediction of the wall quantities corresponding to \(Re_{\tau}=180\), obtained using velocity-fluctuation fields at \(y^{+}=30\) as inputs is shown in figure 6. Further, the network performance measures as introduced in SS2.3 is reported in table 3 for the different wall predictions conducted at \(Re_{\tau}=180\). The R-Net architecture is able to predict the wall-shear and wall pressure using the velocity fluctuation fields at \(y^{+}=50\) with less than about 10% error in the prediction of corresponding RMS quantities. Further, as the inner-scaled separation distance becomes larger than 80, (_i.e._ in this case predicting the wall quantities using the fields at \(y^{+}=100\),) we find the quality of predictions to drastically diminish. On the other hand, if the input fields are close to the wall (_i.e._\(y^{+}\leq 30\),) the prediction of wall quantities is in good agreement with the DNS fields and the error in the corresponding RMS quantities is less than about 2% in almost all the components. A comparison of the premultiplied two-dimensional power spectral density between the DNS fields and the predictions is provided in figure 7. From the figure, it is observed that as the position of the input fields moves away from the wall, the network model lacks the capability to predict the small scale structures in the wall fields, which is closely related to the reasons outlined in SS3.1. Similarly, for the wall predictions at \(Re_{\tau}=550\), the error metrics are provided in table 4. A sample qualitative prediction of the wall quantities corresponding to \(Re_{\tau}=550\), obtained using velocity-fluctuation fields at \(y^{+}=50\) is also provided in figure 6. Finally, a comparison of the premultiplied two-dimensional power spectral density between the DNS fields and the predictions for \(Re_{\tau}=550\) is provided in figure 9. The observations made for the wall predictions at \(Re_{\tau}=180\) is readily applicable to the predictions at \(Re_{\tau}=550\). Further, the magnitude of error is not drastically different from that observed at \(Re_{\tau}=180\), although the errors at \(Re_{\tau}=550\) are higher due to the wider range of scales contained in the fields to be predicted. From the results discussed above, we observe the prediction quality to drastically improve as the input fields are closer to the wall. Hence for predicting the wall quantities at \(Re_{\tau}=550\) from the input fields at \(y^{+}=100\), it is intuitive to take advantage of the self-similarity and implement a convolutional network to predict the fields at \(y^{+}=50\) and thereby to utilize a R-Net architecture to finally obtain the wall quantities. This approach utilizes the velocity fluctuations at \(y^{+}=50\) as auxillary quantities in the prediction of wall-shear and wall-pressure. However, such an approach also yielded results which were similar to the ones observed in table 4. \begin{table} \begin{tabular}{c|c c c c} & & & \(i\) & \\ \cline{3-5} \(y^{+}_{\rm inputs}\) & Parameters & \(u_{y}\) & \(w_{y}\) & \(p\) \\ \hline & \({\cal L}(i_{\rm RN};i_{\rm DNS})/i_{\rm RMS}^{2}\) & 0.012 \(\pm\) 0.002 & 0.022 \(\pm\) 0.006 & 0.099 \(\pm\) 0.008 \\ 15 & \(E_{\rm RMS;RN}(i)\,[\%]\) & 1.60 \(\pm\) 1.09 & 2.97 \(\pm\) 0.95 & 2.09 \(\pm\) 0.86 \\ & \(R_{\rm RN;DNS}\) & 0.994 \(\pm\) 0.001 & 0.993 \(\pm\) 0.001 & 0.949 \(\pm\) 0.004 \\ \hline & \({\cal L}(i_{\rm RN};i_{\rm DNS})/i_{\rm RMS}^{2}\) & 0.056 \(\pm\) 0.001 & 0.070 \(\pm\) 0.003 & 0.107 \(\pm\) 0.006 \\ 30 & \(E_{\rm RMS;RN}(i)\,[\%]\) & 2.62 \(\pm\) 1.28 & 2.34 \(\pm\) 0.92 & 3.07 \(\pm\) 2.21 \\ & \(R_{\rm RN;DNS}\) & 0.971 \(\pm\) 0.001 & 0.965 \(\pm\) 0.001 & 0.945 \(\pm\) 0.003 \\ \hline & \({\cal L}(i_{\rm RN};i_{\rm DNS})/i_{\rm RMS}^{2}\) & 0.244 \(\pm\) 0.013 & 0.349 \(\pm\) 0.009 & 0.272 \(\pm\) 0.010 \\ 50 & \(E_{\rm RMS;RN}(i)\,[\%]\) & 10.31 \(\pm\) 3.10 & 14.73 \(\pm\) 3.30 & 13.07 \(\pm\) 3.06 \\ & \(R_{\rm RN;DNS}\) & 0.848 \(\pm\) 0.004 & 0.815 \(\pm\) 0.004 & 0.853 \(\pm\) 0.006 \\ \hline & \({\cal L}(i_{\rm RN};i_{\rm DNS})/i_{\rm RMS}^{2}\) & 0.674 \(\pm\) 0.003 & 0.709 \(\pm\) 0.002 & 0.620 \(\pm\) 0.006 \\ 100 & \(E_{\rm RMS;RN}(i)\,[\%]\) & 33.31 \(\pm\) 0.84 & 43.77 \(\pm\) 0.86 & 39.26 \(\pm\) 2.48 \\ & \(R_{\rm RN;DNS}\) & 0.574 \(\pm\) 0.002 & 0.538 \(\pm\) 0.001 & 0.616 \(\pm\) 0.006 \\ \end{tabular} \end{table} Table 3: Model-averaged errors in the R-Net predictions of wall-quantities corresponding to \(Re_{\tau}=180\) Figure 6: (Top row) DNS velocity fluctuations at \(y^{+}=30\), (middle row) wall-quantities and (bottom row) corresponding R-Net predictions of the (left column) streamwise, (middle column) spanwise wall-shear and (right column) wall pressure for \(Re_{\tau}=180\). The fields are scaled with respect to the corresponding RMS values. Figure 7: Pre-multiplied two-dimensional power-spectral densities for the wall quantities at \(Re_{\tau}=180\). The contour levels contain 10%, 50% and 90% of the maximum DNS power-spectral density. Shaded contours refer to DNS data and the dashed contour lines correspond to R-Net predictions with inputs at different wall-normal locations differentiated by the color of contour lines. \begin{table} \begin{tabular}{c|c c c c} \multicolumn{4}{c}{} \\ \cline{3-5} \multicolumn{1}{c}{\(y_{\text{inputs}}^{+}\)} & Parameters & \multicolumn{1}{c}{\(u_{y}\)} & \multicolumn{1}{c}{\(w_{y}\)} & \multicolumn{1}{c}{\(p\)} \\ \hline \multirow{3}{*}{15} & \(\mathcal{L}(i_{\text{RN}};i_{\text{DNS}})/i_{\text{RMS}}^{2}\) & 0.013 \(\pm\) 0.0003 & 0.016 \(\pm\) 0.0013 & 0.137 \(\pm\) 0.013 \\ & \(E_{\text{RMS};\text{RN}}(i)\) [\%] & 0.89 \(\pm\) 0.68 & 1.51 \(\pm\) 1.12 & 3.07 \(\pm\) 1.97 \\ & \(R_{\text{RN};\text{DNS}}\) & 0.993 \(\pm\) 0.0002 & 0.992 \(\pm\) 0.0003 & 0.922 \(\pm\) 0.0068 \\ \hline \multirow{3}{*}{30} & \(\mathcal{L}(i_{\text{RN}};i_{\text{DNS}})/i_{\text{RMS}}^{2}\) & 0.074 \(\pm\) 0.0001 & 0.088 \(\pm\) 0.0032 & 0.133 \(\pm\) 0.0002 \\ & \(E_{\text{RMS};\text{RN}}(i)\) [\%] & 3.90 \(\pm\) 0.44 & 2.91 \(\pm\) 2.24 & 2.92 \(\pm\) 2.23 \\ & \(R_{\text{RN};\text{DNS}}\) & 0.962 \(\pm\) 0.0001 & 0.956 \(\pm\) 0.0002 & 0.931 \(\pm\) 0.0008 \\ \hline \multirow{3}{*}{50} & \(\mathcal{L}(i_{\text{RN}};i_{\text{DNS}})/i_{\text{RMS}}^{2}\) & 0.257 \(\pm\) 0.0031 & 0.316 \(\pm\) 0.0045 & 0.228 \(\pm\) 0.0042 \\ & \(E_{\text{RMS};\text{RN}}(i)\) [\%] & 10.35 \(\pm\) 1.53 & 13.07 \(\pm\) 1.62 & 8.68 \(\pm\) 0.24 \\ & \(R_{\text{RN};\text{DNS}}\) & 0.865 \(\pm\) 0.0020 & 0.827 \(\pm\) 0.0032 & 0.879 \(\pm\) 0.0023 \\ \hline \multirow{3}{*}{100} & \(\mathcal{L}(i_{\text{RN}};i_{\text{DNS}})/i_{\text{RMS}}^{2}\) & 0.837 \(\pm\) 0.0035 & 0.906 \(\pm\) 0.0202 & 0.736 \(\pm\) 0.0893 \\ & \(E_{\text{RMS};\text{RN}}(i)\) [\%] & 43.86 \(\pm\) 3.17 & 58.08 \(\pm\) 4.77 & 25.07 \(\pm\) 9.53 \\ \end{tabular} \end{table} Table 4: Model-averaged errors in the R-Net predictions of wall-quantities corresponding to \(Re_{\tau}=550\) Figure 8: (Top row) DNS velocity fluctuations at \(y^{+}=50\), (middle row) wall-quantities and (bottom row) corresponding R-Net predictions of the (left column) streamwise, (middle column) spanwise wall-shear and (right column) wall pressure for \(Re_{\tau}=550\). The fields are scaled with respect to the corresponding RMS values. ter ## 4 Conclusions In this work, the possibility of predicting the velocity-fluctuation fields closer to the wall using the fluctuation fields farther from it by means of an FCN and R-Net is assessed. Several predictions were performed to understand the implementation and the quality of predictions at lower \(Re_{\tau}\). The variation of the MSE with respect to the separation distance between the input and the target fluctuation fields exhibits a non-linear behaviour and it also varies with respect to the \(y^{+}\) location of the predicted fluctuation field. The results also indicate the capability of the FCN to predict the non-linear transfer function between the velocity-fluctuation fields that are separated by short distances. Additionally, a higher \(Re_{\tau}\) of 550 was also considered for testing the capability of the network to predict fields closer to the wall characterized by wider range of scales. At high Reynolds number, the self-similarity hypothesis Figure 9: Pre-multiplied two-dimensional power-spectral densities for the wall quantities at \(Re_{\tau}=550\). The contour levels contain 10%, 50% and 90% of the maximum DNS power-spectral density. Shaded contours refer to DNS data and the dashed contour lines correspond to R-Net predictions with inputs at different wall-normal locations differentiated by the color of contour lines. in the logarithmic layer can be exploited by the convolutional networks. The R-Net architecture is used to predict the velocity-fluctuation fields at \(y^{+}=50\) using the fluctuation fields at \(y^{+}=100\) corresponding to \(Re_{\tau}=550\) and it provides better instantaneous predictions than the lower-Reynolds case of \(Re_{\tau}=180\) due to the corresponding velocity-fluctuation fields at \(y/h\approx 0.27\) and \(0.55\), which are not in self-similar region. The fluctuation intensities are also reasonably well-predicted for \(Re_{\tau}=550\), with an error in the streamwise RMS-fluctuation is around \(10\%\) compared to the DNS statistics. Furthermore, the spectral analysis of the predictions shows that the energy content at the length-scales that are present in the input flow field are well-predicted. Note, however, that the energy in the smaller scales is difficult to reproduce since the input fields do not provide information about them. The present results highlight that the self-similarity in the overlap region of the flow can be effectively utilized by the network models to predict the velocity-fluctuation fields at higher \(Re_{\tau}\). Note that such similarity is not explicitly enforced in the neural-network architecture, but this physical property can be exploited by the network to obtain better predictions. Further, the study is extended to predict the wall-shear stress components and wall pressure using the velocity-fluctuation fields at a certain wall-normal distance close to the wall. The proposed R-Net architecture is able to predict the wall quantities with less than \(15\%\) error in the corresponding fluctuation intensity at both \(Re_{\tau}=180\) and \(550\), when the input velocity fluctuation fields at \(y^{+}=50\) are used. The closer to the wall the input fields are, the higher is the prediction accuracy. These results are an encouraging starting point to utilize such neural-network models in the development of data-driven wall models for LES. In the direction of improving accuracy of predictions obtained from network models, the use of U-Net architecture to reconstruct the small features in the wall is a viable option and will be considered in the scope of future work. Note however that this is just a proof of concept regarding the predictive capabilities of these models, and being able to implement such strategies in _a-posteriori_ tests would require combining these methods with a LES solver. ## 5 Acknowledgments The authors acknowledge the funding provided by the Swedish e-Science Research Centre (SeRC), ERC grant no. "2021-CoG-101043998, DEEPCON TROL" to RV and the Knut and Alice Wallenberg (KAW) Foundation. The authors thank Dr. Alejandro Guemes, Prof. Andrea Ianiro and Prof. Stefano Discetti for their valuable insights and discussions on this research project. The analysis was performed on resources provided by the Swedish National Infrastructure for Computing (SNIC) at PDC. Views and opinions expressed are however those of the author(s) only and do not necessarily reflect those of the European Union or the European Research Council. Neither the European Union nor the granting authority can be held responsible for them. ## Appendix A Outer predictions In contrast to the inner predictions discussed in SS3.1, outer predictions refer to the prediction of velocity fluctuation fields farther from the wall using the fields closer to the wall as inputs. A total of 10 predictions are performed with the velocity fields obtained at various wall-normal locations from the DNS simulation at \(Re_{\tau}=180\). Here, the separation distances are defined as: \(\Delta y^{+}=y^{+}_{\rm target}-y^{+}_{\rm input}\). The input velocity-fluctuation field closest to the wall is located at \(y^{+}=15\) and the corresponding target field is at \(y^{+}=30\). The results obtained for outer predictions are plotted in figure 10. In comparison to the results obtained for inner predictions as plotted in figure 2, the outer predictions are observed to be much better and exhibits a different slope for the variation of error in prediction of streamwise fluctuation intensity with respect to separation distance. Further, a saturation of MSE for higher separation distances is clearly observed for inner predictions whereas such saturation was not conceived in the present study for outer predictions. If a particular separation distance is considered, the target fields closer to the wall are more accurately predicted in the case of outer predictions, a result opposite to what is observed for the inner predictions.
2302.07426
Computational Complexity of Learning Neural Networks: Smoothness and Degeneracy
Understanding when neural networks can be learned efficiently is a fundamental question in learning theory. Existing hardness results suggest that assumptions on both the input distribution and the network's weights are necessary for obtaining efficient algorithms. Moreover, it was previously shown that depth-$2$ networks can be efficiently learned under the assumptions that the input distribution is Gaussian, and the weight matrix is non-degenerate. In this work, we study whether such assumptions may suffice for learning deeper networks and prove negative results. We show that learning depth-$3$ ReLU networks under the Gaussian input distribution is hard even in the smoothed-analysis framework, where a random noise is added to the network's parameters. It implies that learning depth-$3$ ReLU networks under the Gaussian distribution is hard even if the weight matrices are non-degenerate. Moreover, we consider depth-$2$ networks, and show hardness of learning in the smoothed-analysis framework, where both the network parameters and the input distribution are smoothed. Our hardness results are under a well-studied assumption on the existence of local pseudorandom generators.
Amit Daniely, Nathan Srebro, Gal Vardi
2023-02-15T02:00:26Z
http://arxiv.org/abs/2302.07426v2
# Efficiently Learning Neural Networks: ###### Abstract Understanding when neural networks can be learned efficiently is a fundamental question in learning theory. Existing hardness results suggest that assumptions on both the input distribution and the network's weights are necessary for obtaining efficient algorithms. Moreover, it was previously shown that depth-\(2\) networks can be efficiently learned under the assumptions that the input distribution is Gaussian, and the weight matrix is non-degenerate. In this work, we study whether such assumptions may suffice for learning deeper networks and prove negative results. We show that learning depth-\(3\) ReLU networks under the Gaussian input distribution is hard even in the smoothed-analysis framework, where a random noise is added to the network's parameters. It implies that learning depth-\(3\) ReLU networks under the Gaussian distribution is hard even if the weight matrices are non-degenerate. Moreover, we consider depth-\(2\) networks, and show hardness of learning in the smoothed-analysis framework, where both the network parameters and the input distribution are smoothed. Our hardness results are under a well-studied assumption on the existence of local pseudorandom generators. Collaboration on the Theoretical Foundations of Deep Learning (deepfoundations.ai) ## 1 Introduction The computational complexity of learning neural networks has been extensively studied in recent years, and there has been much effort in obtaining both upper bounds and hardness results. Nevertheless, it is still unclear when neural networks can be learned in polynomial time, namely, under what assumptions provably efficient algorithms exist. Existing results imply hardness already for learning depth-\(2\) ReLU networks in the standard PAC learning framework (e.g., Klivans and Sherstov (2006); Daniely and Shalev-Shwartz (2016)). Thus, without any assumptions on the input distribution or the network's weights, efficient learning algorithms might not be achievable. Even when assuming that the input distribution is Gaussian, strong hardness results were obtained for depth-\(3\) ReLU networks (Daniely and Vardi, 2021; Chen et al., 2022), suggesting that assumptions merely on the input distribution might not suffice. Also, a hardness result by Daniely and Vardi (2020) shows that strong assumptions merely on the network's weights (without restricting the input distribution) might not suffice even for efficiently learning depth-\(2\) networks. The aforementioned hardness results hold already for _improper learning_, namely, where the learning algorithm is allowed to return a hypothesis that does not belong to the considered hypothesis class. Thus, a combination of assumptions on the input distribution and the network's weights seems to be necessary for obtaining efficient algorithms. Several polynomial-time algorithms for learning depth-\(2\) neural networks have been obtained, under assumptions on the input distribution and the network's weights (Awasthi et al., 2021; Janzamin et al., 2015; Zhong et al., 2017; Ge et al., 2017; Bakshi et al., 2019; Ge et al., 2018). In these works, it is assumed that the weight matrices are non-degenerate. That is, they either assume that the condition number of the weight matrix is bounded, or some similar non-degeneracy assumption. Specifically, Awasthi et al. (2021) gave an efficient algorithm for learning depth-\(2\) (one-hidden-layer) ReLU networks, that may include bias terms in the hidden neurons, under the assumption that the input distribution is Gaussian, and the weight matrix is non-degenerate. The non-degeneracy assumption holds w.h.p. if we add a small random noise to any weight matrix, and hence their result implies efficient learning of depth-\(2\) ReLU networks under the Gaussian distribution in the _smoothed-analysis_ framework. The positive results on depth-\(2\) networks suggest the following question: _Is there an efficient algorithm for learning ReLU networks of depth larger than \(2\) under the Gaussian distribution, where the weight matrices are non-degenerate, or in the smoothed-analysis framework where the network's parameters are smoothed?_ In this work, we give a negative answer to this question, already for depth-\(3\) networks1. We show that learning depth-\(3\) ReLU networks under the Gaussian distribution is hard even in the smoothed-analysis framework, where a random noise is added to the network's parameters. As a corollary, we show that learning depth-\(3\) ReLU networks under the Gaussian distribution is hard even if the weight matrices are non-degenerate. Our hardness results are under a well-studied cryptographic assumption on the existence of _local pseudorandom generators (PRG)_ with polynomial stretch. Footnote 1: We note that in our results the neural networks have the ReLU activation also in the output neuron. Motivated by the existing positive results on smoothed-analysis in depth-\(2\) networks, we also study whether learning depth-\(2\) networks with smoothed parameters can be done under weak assumptions on the input distribution. Specifically, we consider the following question: _Is there an efficient algorithm for learning depth-\(2\) ReLU networks in the smoothed-analysis framework, where both the network's parameters and the input distribution are smoothed?_ We give a negative answer to this question, by showing hardness of learning depth-\(2\) ReLU networks where a random noise is added to the network's parameters, and the input distribution on \(\mathbb{R}^{d}\) is obtained by smoothing an i.i.d. Bernoulli distribution on \(\{0,1\}^{d}\). This hardness result is also under the assumption on the existence of local PRGs. Related work Hardness of learning neural networks.Hardness of improperly learning depth-\(2\) neural networks follows from hardness of improperly learning DNFs or intersections of halfspaces, since these classes can be expressed by depth-\(2\) networks. Klivans and Sherstov (2006) showed, assuming the hardness of the shortest vector problem, that learning intersections of halfspaces is hard. Hardness of learning DNF formulas is implied by Applebaum et al. (2010) under a combination of two assumptions: the first is related to the planted dense subgraph problem in hypergraphs, and the second is related to local PRGs. Daniely and Shalev-Shwartz (2016) showed hardness of learning DNFs under a common assumption, namely, that refuting a random \(K\)-SAT formula is hard. All of the above results are distribution-free, namely, they do not imply hardness of learning neural networks under some specific distribution. Applebaum and Raykov (2016) showed, under an assumption on a specific candidate for Goldreich's PRG (i.e., based on a predicate called \(\mathrm{XOR}\text{-}\mathrm{MAJ}\)), that learning depth-\(3\) Boolean circuits under the uniform distribution on the hypercube is hard. Daniely and Vardi (2021) proved distribution-specific hardness of learning Boolean circuits of depth-\(2\) (namely, DNFs) and depth-\(3\), under the assumpion on the existence of local PRGs that we also use in this work. For DNF formulas, they showed hardness of learning under a distribution where each component is drawn i.i.d. from a Bernoulli distribution (which is not uniform). For depth-\(3\) Boolean circuits, they showed hardness of learning under the uniform distribution on the hypercube. Since the Boolean circuits can be expressed by ReLU networks of the same depth, these results readily translate to distribution-specific hardness of learning neural networks. Chen et al. (2022) showed hardness of learning depth-\(2\) neural networks under the uniform distribution on the hypercube, based on an assumption on the hardness of the _Learning with Rounding (LWR)_ problem. Note that the input distributions in the above results are supported on the hypercube, and they do not immediately imply hardness of learning neural networks under continuous distributions. When considering the computational complexity of learning neural networks, perhaps the most natural choice of an input distribution is the standard Gaussian distribution. Daniely and Vardi (2021) established hardness of learning depth-\(3\) networks under this distribution, based on the assumpion on the existence of local PRGs. Chen et al. (2022) also showed hardness of learning depth-\(3\) networks under the Gaussian distribution, but their result holds already for networks that do not have an activation function in the output neuron, and it is based on the LWR assumption. They also showed hardness of learning constant depth ReLU networks from label queries (i.e., where the learner has the ability to query the value of the target network at any desired input) under the Gaussian distribution, based either on the decisional Diffie-Hellman or the Learning with Errors assumptions. The above results suggest that assumptions on the input distribution might not suffice for achieving an efficient algorithm for learning depth-\(3\) neural networks. A natural question is whether assumptions on the network weights may suffice. Daniely and Vardi (2020) showed (under the assumption that refuting a random \(K\)-SAT formula is hard) that distribution-free learning of depth-\(2\) neural networks is hard already if the weights are drawn from some "natural" distribution or satisfy some "natural" properties. Thus, if we do not impose any assumptions on the input distribution, then even very strong assumptions on the network's weights do not suffice for efficient learning. Several works in recent years have shown hardness of distribution-specific learning shallow neural networks using gradient-methods or statistical query (SQ) algorithms (Shamir, 2018; Song et al., 2017; Vempala and Wilmes, 2019; Goel et al., 2020; Diakonikolas et al., 2020; Chen et al., 2022). Specifically, Goel et al. (2020) and Diakonikolas et al. (2020) gave superpolynomial _correlational SQ_ (CSQ) lower bounds for learning depth-\(2\) networks under the Gaussian distribution. Since there is separation between CSQ and SQ, these results do not imply hardness of general SQ learning. Chen et al. (2022) showed general SQ lower bounds for depth-\(3\) networks under the Gaussian distribution. It is worth noting that while the SQ framework captures some variants of the gradient-descent algorithm, it does not capture, for example, stochastic gradient-descent (SGD), which examines training points individually (see a discussion in Goel et al. (2020)). We emphasize that none of the above distribution-specific hardness results for neural networks (either for improper learning or SQ learning) holds in the smoothed analysis framework or for non-degenerate weights. While hardness of proper learning is implied by hardness of improper learning, there are also works that show hardness of properly learning depth-\(2\) networks under more standard assumptions (cf. Goel et al. (2020)). Finally, distribution-specific hardness of learning a single ReLU neuron in the agnostic setting was shown in Goel et al. (2019, 2020b); Diakonikolas et al. (2020a). Learning neural networks in polynomial time.Awasthi et al. (2021) gave a polynomial-time algorithm for learning depth-\(2\) (one-hidden-layer) ReLU networks, under the assumption that the input distribution is Gaussian, and the weight matrix of the target network is non-degenerate. Their algorithm is based on tensor decomposition, and it can handle bias terms in the hidden layer. Their result also implies that depth-\(2\) ReLU networks with Gaussian inputs can be learned efficiently under the smoothed-analysis framework. Our work implies that such a result might not be possible in depth-\(3\) networks (with activation in the output neuron). Prior to Awasthi et al. (2021), several works gave polynomial time algorithms for learning depth-\(2\) neural networks where the input distribution is Gaussian and the weight matrix is non-degenerate (Janzamin et al., 2015; Zhong et al., 2017; Ge et al., 2017, 2018; Bakshi et al., 2019), but these works either do not handle the presence of bias terms or do not handle the ReLU activation. Some of the aforementioned works consider networks with multiple outputs, and allow certain non-Gaussian input distributions. Provable guarantees for learning neural networks in super-polynomial time were given in Diakonikolas et al. (2020b); Chen et al. (2022b); Diakonikolas and Kane (2020). Distribution-free learning of a single ReLU neuron (in the realizable setting) can be done in polynomial time (Kalai and Sastry, 2009; Kakade et al., 2011). ## 2 Preliminaries ### Notation We use bold-face letters to denote vectors, e.g., \(\mathbf{x}=(x_{1},\ldots,x_{d})\). For a vector \(\mathbf{x}\) and a sequence \(S=(i_{1},\ldots,i_{k})\) of \(k\) indices, we let \(\mathbf{x}_{S}=(x_{i_{1}},\ldots,x_{i_{k}})\), i.e., the restriction of \(\mathbf{x}\) to the indices \(S\). We denote by \(\mathbbm{1}[\cdot]\) the indicator function, for example \(\mathbbm{1}[t\geq 5]\) equals \(1\) if \(t\geq 5\) and \(0\) otherwise. For an integer \(d\geq 1\) we denote \([d]=\{1,\ldots,d\}\). We denote by \(\mathcal{N}(0,\sigma^{2})\) the normal distribution with mean \(0\) and variance \(\sigma^{2}\), and by \(\mathcal{N}(\mathbf{0},\Sigma)\) the multivariate normal distribution with mean \(\mathbf{0}\) and covariance matrix \(\Sigma\). The identity matrix of size \(d\) is denoted by \(I_{d}\). For \(\mathbf{x}\in\mathbb{R}^{d}\) we denote by \(\|\mathbf{x}\|\) the Euclidean norm. We use \(\mathrm{poly}(a_{1},\ldots,a_{n})\) to denote a polynomial in \(a_{1},\ldots,a_{n}\). ### Local pseudorandom generators An \((n,m,k)\)-hypergraph is a hypergraph over \(n\) vertices \([n]\) with \(m\) hyperedges \(S_{1},\ldots,S_{m}\), each of cardinality \(k\). Each hyperedge \(S=(i_{1},\ldots,i_{k})\) is ordered, and all the \(k\) members of a hyperedge are distinct. We let \(\mathcal{G}_{n,m,k}\) be the distribution over such hypergraphs in which a hypergraph is chosen by picking each hyperedge uniformly and independently at random among all the possible \(n\cdot(n-1)\cdot\ldots\cdot(n-k+1)\) ordered hyperedges. Let \(P:\{0,1\}^{k}\rightarrow\{0,1\}\) be a predicate, and let \(G\) be a \((n,m,k)\)-hypergraph. We call _Goldreich's pseudorandom generator (PRG)_(Goldreich, 2000) the function \(f_{P,G}:\{0,1\}^{n}\rightarrow\{0,1\}^{m}\) such that for \(\mathbf{x}\in\{0,1\}^{n}\), we have \(f_{P,G}(\mathbf{x})=(P(\mathbf{x}_{S_{1}}),\ldots,P(\mathbf{x}_{S_{m}}))\). The integer \(k\) is called the _locality_ of the PRG. If \(k\) is a constant then the PRG and the predicate \(P\) are called _local_. We say that the PRG has _polynomial stretch_ if \(m=n^{s}\) for some constant \(s>1\). We let \(\mathcal{F}_{P,n,m}\) denote the collection of functions \(f_{P,G}\) where \(G\) is an \((n,m,k)\)-hypergraph. We sample a function from \(\mathcal{F}_{P,n,m}\) by choosing a random hypergraph \(G\) from \(\mathcal{G}_{n,m,k}\). We denote by \(G\stackrel{{ R}}{{\leftarrow}}\mathcal{G}_{n,m,k}\) the operation of sampling a hypergraph \(G\) from \(\mathcal{G}_{n,m,k}\), and by \(\mathbf{x}\stackrel{{ R}}{{\leftarrow}}\{0,1\}^{n}\) the operation of sampling \(\mathbf{x}\) from the uniform distribution on \(\{0,1\}^{n}\). We say that \(\mathcal{F}_{P,n,m}\) is \(\varepsilon\)-pseudorandom generator (\(\varepsilon\)-PRG) if for every polynomial-time probabilistic algorithm \(\mathcal{A}\) the _distinguishing advantage_ \[\left|\Pr_{G\xleftarrow{R}\mathcal{G}_{n,m,k}\xleftarrow{R}\{0,1\}^{n}}[ \mathcal{A}(G,f_{P,G}(\mathbf{x}))=1]-\Pr_{G\xleftarrow{R}\mathcal{G}_{n,m,k} \mathbf{y}\xleftarrow{R}\{0,1\}^{m}}[\mathcal{A}(G,\mathbf{y})=1]\right|\] is at most \(\varepsilon\). Thus, the distinguisher \(\mathcal{A}\) is given a random hypergraph \(G\) and a string \(\mathbf{y}\in\{0,1\}^{m}\), and its goal is to distinguish between the case where \(\mathbf{y}\) is chosen at random, and the case where \(\mathbf{y}\) is a random image of \(f_{P,G}\). Our assumption is that local PRGs with polynomial stretch and constant distinguishing advantage exist: **Assumption 2.1**.: _For every constant \(s>1\), there exists a constant \(k\) and a predicate \(P:\{0,1\}^{k}\rightarrow\{0,1\}\), such that \(\mathcal{F}_{P,n,n^{s}}\) is \(\frac{1}{3}\)-PRG._ We remark that the same assumption was used by Daniely and Vardi (2021) to show hardness-of-learning results. Note that we assume constant distinguishing advantage. In the literature, a requirement of negligible distinguishing advantage2 is often considered (cf. Applebaum and Lovett (2016), Applebaum (2016), Couteau et al. (2018)). Thus, our requirement from the PRG is weaker. Footnote 2: More formally, that for \(1-o_{n}(1)\) fraction of the hypergraphs, the distinguisher has no more than negligible advantage. Local PRGs have been extensively studied in the last two decades. In particular, local PRGs with polynomial stretch have shown to have remarkable applications, such as secure-computation with constant computational overhead (Ishai et al., 2008, Applebaum et al., 2017), and general-purpose obfuscation based on constant degree multilinear maps (cf. Lin (2016), Lin and Vaikuntanathan (2016)). Significant evidence for Assumption 2.1 was shown in Applebaum (2013) and Applebaum and Lovett (2016). See Daniely and Vardi (2021) for further discussion on the assumption, and on prior works regarding the relation between Goldreich's PRG and hardness of learning. ### Neural networks We consider feedforward neural networks, computing functions from \(\mathbb{R}^{d}\) to \(\mathbb{R}\). The network is composed of layers of neurons, such that each neuron computes a function of the form \(\mathbf{x}\mapsto\sigma(\mathbf{w}^{\top}\mathbf{x}+b)\), where \(\mathbf{w}\) is a weight vector, \(b\) is a bias term and \(\sigma:\mathbb{R}\mapsto\mathbb{R}\) is a non-linear activation function. The _input to the neuron_ is defined as \(\mathbf{w}^{\top}\mathbf{x}+b\), i.e., the value before applying the activation function. In this work, we focus on the ReLU activation function, namely, \(\sigma(z)=[z]_{+}=\max\{0,z\}\). For a matrix \(W=(\mathbf{w}_{1},\ldots,\mathbf{w}_{m})\), we let \(\sigma(W^{\top}\mathbf{x}+\mathbf{b})\) be a shorthand for \(\big{(}\sigma(\mathbf{w}_{1}^{\top}\mathbf{x}+b_{1}),\ldots,\sigma(\mathbf{w} _{m}^{\top}\mathbf{x}+b_{m})\big{)}\), and define a layer of \(m\) neurons as \(\mathbf{x}\mapsto\sigma(W^{\top}\mathbf{x}+\mathbf{b})\). By denoting the output of the \(i\)-th layer as \(O_{i}\), we can define a network of arbitrary depth recursively by \(O_{i+1}=\sigma(W_{i+1}^{\top}O_{i}+\mathbf{b}_{i+1})\). The _weights vector_ of the \(j\)-th neuron in the \(i\)-th layer is the \(j\)-th column of \(W_{i}\), and its _outgoing-weights vector_ is the \(j\)-th row of \(W_{i+1}\). We define the _depth_ of the network as the number of layers. Unless stated otherwise, the output neuron also has a ReLU activation function. A neuron which is not an input or output neuron is called a _hidden neuron_. We sometimes consider neural networks with multiple outputs. The parameters of the neural network is the set of its weight matrices and bias vectors. We often view the parameters as a vector \(\boldsymbol{\theta}\in\mathbb{R}^{p}\) obtained by concatenating these matrices and vectors. For \(B\geq 0\), we say that the parameters are \(B\)-bounded if the absolute values of all weights and biases are at most \(B\). ### Learning neural networks and the smoothed-analysis framework We first define learning neural networks under the standard PAC framework: **Definition 2.1** (Distribution-specific PAC learning).: _Learning depth-\(k\) neural networks under an input distribution \(\mathcal{D}\) on \(\mathbb{R}^{d}\) is defined by the following framework:_ 1. _An adversary chooses a set of_ \(B\)_-bounded parameters_ \(\boldsymbol{\theta}\in\mathbb{R}^{p}\) _for a depth-_ \(k\) _neural network_ \(N_{\boldsymbol{\theta}}:\mathbb{R}^{d}\rightarrow\mathbb{R}\)_, as well as some_ \(\epsilon>0\)_._ 2. _Consider an examples oracle, such that each example_ \((\mathbf{x},y)\in\mathbb{R}^{d}\times\mathbb{R}\) _is drawn i.i.d. with_ \(\mathbf{x}\sim\mathcal{D}\) _and_ \(y=N_{\boldsymbol{\theta}}(\mathbf{x})\)_. Then, given access to the examples oracle, the goal of the learning algorithm_ \(\mathcal{L}\) _is to return with probability at least_ \(\frac{3}{4}\) _a hypothesis_ \(h:\mathbb{R}^{d}\rightarrow\mathbb{R}\) _such that_ \[\operatorname*{\mathbb{E}}_{\mathbf{x}\sim\mathcal{D}}\left[\left(h(\mathbf{x })-N_{\boldsymbol{\theta}}(\mathbf{x})\right)^{2}\right]\leq\epsilon\;.\] _We say that_ \(\mathcal{L}\) _is_ efficient _if it runs in time_ \(\operatorname{poly}(d,p,B,1/\epsilon)\)_._ We consider learning in the _smoothed-analysis_ framework (Spielman and Teng, 2004), which is a popular paradigm for analyzing non-worst-case computational complexity (Roughgarden, 2021). The smoothed-analysis framework has been successfully applied to many learning problems (e.g., Awasthi et al. (2021); Ge et al. (2018); Kalai et al. (2009); Bhaskara et al. (2014, 2019); Haghtalab et al. (2020); Ge et al. (2015); Kalai and Teng (2008); Brutzkus et al. (2020)). In the smoothed-analysis setting, the target network is not purely controlled by an adversary. Instead, the adversary can first generate an arbitrary network, and the parameters for this network (i.e., the weight matrices and bias terms) will be randomly perturbed to yield a perturbed network. The algorithm only needs to work with high probability on the perturbed network. This limits the power of the adversary and prevents it from creating highly degenerate cases. Formally, we consider the following framework (we note that a similar model was considered in Awasthi et al. (2021) and Ge et al. (2018)): **Definition 2.2** (Learning with smoothed parameters).: _Learning depth-\(k\) neural networks with smoothed parameters under an input distribution \(\mathcal{D}\) is defined as follows:_ 1. _An adversary chooses a set of_ \(B\)_-bounded parameters_ \(\boldsymbol{\theta}\in\mathbb{R}^{p}\) _for a depth-_ \(k\) _neural network_ \(N_{\boldsymbol{\theta}}:\mathbb{R}^{d}\rightarrow\mathbb{R}\)_, as well as some_ \(\tau,\epsilon>0\)_._ 2. _A perturbed set of parameters_ \(\hat{\boldsymbol{\theta}}\) _is obtained by a random perturbation to_ \(\boldsymbol{\theta}\)_, namely,_ \(\hat{\boldsymbol{\theta}}=\boldsymbol{\theta}+\boldsymbol{\xi}\) _for_ \(\boldsymbol{\xi}\sim\mathcal{N}(\mathbf{0},\tau^{2}I_{p})\)_._ 3. _Consider an examples oracle, such that each example_ \((\mathbf{x},y)\in\mathbb{R}^{d}\times\mathbb{R}\) _is drawn i.i.d. with_ \(\mathbf{x}\sim\mathcal{D}\) _and_ \(y=N_{\hat{\boldsymbol{\theta}}}(\mathbf{x})\)_. Then, given access to the examples oracle, the goal of the learning algorithm_ \(\mathcal{L}\) _is to return with probability at least_ \(\frac{3}{4}\) _(over the random perturbation_ \(\boldsymbol{\xi}\) _and the internal randomness of_ \(\mathcal{L}\)_) a hypothesis_ \(h:\mathbb{R}^{d}\rightarrow\mathbb{R}\) _such that_ \[\operatorname*{\mathbb{E}}_{\mathbf{x}\sim\mathcal{D}}\left[\left(h(\mathbf{x })-N_{\hat{\boldsymbol{\theta}}}(\mathbf{x})\right)^{2}\right]\leq\epsilon\;.\] _We say that_ \(\mathcal{L}\) _is_ efficient _if it runs in time_ \(\operatorname{poly}(d,p,B,1/\epsilon,1/\tau)\)_._ Finally, we also consider a setting where both the parameters and the input distribution are smoothed: **Definition 2.3** (Learning with smoothed parameters and inputs).: _Learning depth-\(k\) neural networks with smoothed parameters and inputs under an input distribution \(\mathcal{D}\) is defined as follows:_ 1. _An adversary chooses a set of_ \(B\)_-bounded parameters_ \(\boldsymbol{\theta}\in\mathbb{R}^{p}\) _for a depth-_\(k\) _neural network_ \(N_{\boldsymbol{\theta}}:\mathbb{R}^{d}\rightarrow\mathbb{R}\)_, as well as some_ \(\tau,\omega,\epsilon>0\)_._ 2. _A perturbed set of parameters_ \(\hat{\boldsymbol{\theta}}\) _is obtained by a random perturbation to_ \(\boldsymbol{\theta}\)_, namely,_ \(\hat{\boldsymbol{\theta}}=\boldsymbol{\theta}+\boldsymbol{\xi}\) _for_ \(\boldsymbol{\xi}\sim\mathcal{N}(\mathbf{0},\tau^{2}I_{p})\)_. Moreover, a smoothed input distribution_ \(\hat{\mathcal{D}}\) _is obtained from_ \(\mathcal{D}\)_, such that_ \(\hat{\mathbf{x}}\sim\hat{\mathcal{D}}\) _is chosen by drawing_ \(\mathbf{x}\sim\mathcal{D}\) _and adding a random perturbation from_ \(\mathcal{N}(\mathbf{0},\omega^{2}I_{d})\)_._ 3. _Consider an examples oracle, such that each example_ \((\mathbf{x},y)\in\mathbb{R}^{d}\times\mathbb{R}\) _is drawn i.i.d. with_ \(\mathbf{x}\sim\hat{\mathcal{D}}\) _and_ \(y=N_{\hat{\boldsymbol{\theta}}}(\mathbf{x})\)_. Then, given access to the examples oracle, the goal of the learning algorithm_ \(\mathcal{L}\) _is to return with probability at least_ \(\frac{3}{4}\) _(over the random perturbation_ \(\boldsymbol{\xi}\) _and the internal randomness of_ \(\mathcal{L}\)_) a hypothesis_ \(h:\mathbb{R}^{d}\rightarrow\mathbb{R}\) _such that_ \[\operatorname*{\mathbb{E}}_{\mathbf{x}\sim\hat{\mathcal{D}}}\left[\left(h( \mathbf{x})-N_{\hat{\boldsymbol{\theta}}}(\mathbf{x})\right)^{2}\right]\leq \epsilon\;.\] _We say that_ \(\mathcal{L}\) _is_ efficient _if it runs in time_ \(\operatorname{poly}(d,p,B,1/\epsilon,1/\tau,1/\omega)\)_._ We emphasize that all of the above definitions consider learning in the distribution-specific setting. Thus, the learning algorithm may depend on the specific input distribution \(\mathcal{D}\). ## 3 Results As we discussed in the introduction, there exist efficient algorithms for learning depth-\(2\) (one-hidden-layer) ReLU networks with smoothed parameters under the Gaussian distribution. We now show that such a result may not be achieved for depth-\(3\) networks: **Theorem 3.1**.: _Under Assumption 2.1, there is no efficient algorithm that learns depth-\(3\) neural networks with smoothed parameters (in the sense of Definition 2.2) under the standard Gaussian distribution._ We prove the theorem in Section 4. Next, we conclude that learning depth-\(3\) neural networks under the Gaussian distribution on \(\mathbb{R}^{d}\) is hard in the standard PAC framework even if all weight matrices are non-degenerate, namely, when the minimal singular values of the weight matrices are lower bounded by \(1/\operatorname{poly}(d)\). As we discussed in the introduction, in one-hidden-layer networks with similar assumptions there exist efficient learning algorithms. **Corollary 3.1**.: _Under Assumption 2.1, there is no efficient algorithm that learns depth-\(3\) neural networks (in the sense of Definition 2.1) under the standard Gaussian distribution on \(\mathbb{R}^{d}\), even if the smallest singular value of each weight matrix is at least \(1/\operatorname{poly}(d)\)._ The proof of the above corollary follows from Theorem 3.1, using the fact that by adding a small random perturbation to the weight matrices, we get w.h.p. non-degenerate matrices. Hence, an efficient algorithm that learns non-degenerate networks suffices for obtaining an efficient algorithm that learns under the smoothed analysis framework. See Appendix B for the formal proof. Theorem 3.1 gives a strong limitation on learning depth-\(3\) networks in the smoothed-analysis framework. Motivated by existing positive results on smoothed-analysis in depth-\(2\) networks, we now study whether learning depth-\(2\) networks with smoothed parameters can be done under weak assumptions on the input distribution. Specifically, we consider the case where both the parameters and the input distribution are smoothed. We show that efficiently learning depth-\(2\) networks may not be possible with smoothed parameters where the input distribution on \(\mathbb{R}^{d}\) is obtained by smoothing an i.i.d. Bernoulli distribution on \(\{0,1\}^{d}\). **Theorem 3.2**.: _Under Assumption 2.1, there is no efficient algorithm that learns depth-\(2\) neural networks with smoothed parameters and inputs (in the sense of Definition 2.3), under the distribution \(\mathcal{D}\) on \(\{0,1\}^{d}\) where each coordinate is drawn i.i.d. from a Bernoulli distribution which takes the value \(0\) with probability \(\frac{1}{\sqrt{d}}\)._ We prove the theorem in Appendix C. The proof follows from similar ideas to the proof of Theorem 3.1, which we discuss in the next section. ## 4 Proof of Theorem 3.1 The proof builds on a technique from Daniely and Vardi (2021). It follows by showing that an efficient algorithm for learning depth-\(3\) neural networks with smoothed parameters under the Gaussian distribution can be used for breaking a local PRG. Intuitively, the main challenge in our proof in comparison to Daniely and Vardi (2021) is that our reduction must handle the random noise which is added to the parameters. Specifically, Daniely and Vardi (2021) define a certain examples oracle, and show that the examples returned by the oracle are realizable by some neural network which depends on the unknown \(\mathbf{x}\in\{0,1\}^{n}\) used by the PRG. Since the network depends on this unknown \(\mathbf{x}\), some of the parameters of the network are unknown, and hence it is not trivial how to define an examples oracle which is realizable by a perturbed network. Moreover, we need to handle this random perturbation without increasing the network's depth. We now provide the formal proof. The proof relies on several lemmas which we prove in Appendix A. For a sufficiently large \(n\), let \(\mathcal{D}\) be the standard Gaussian distribution on \(\mathbb{R}^{n^{2}}\). Assume that there is a \(\operatorname{poly}(n)\)-time algorithm \(\mathcal{L}\) that learns depth-\(3\) neural networks with at most \(n^{2}\) hidden neurons and parameter magnitudes bounded by \(n^{3}\), with smoothed parameters, under the distribution \(\mathcal{D}\), with \(\epsilon=\frac{1}{n}\), and \(\tau=1/\operatorname{poly}(n)\) that we will specify later. Let \(m(n)\leq\operatorname{poly}(n)\) be the sample complexity of \(\mathcal{L}\), namely, \(\mathcal{L}\) uses a sample of size at most \(m(n)\) and returns with probability at least \(\frac{3}{4}\) a hypothesis \(h\) with \(\mathbb{E}_{\mathbf{z}\sim\mathcal{D}}\left[\left(h(\mathbf{z})-N_{\hat{ \boldsymbol{\theta}}}(\mathbf{z})\right)^{2}\right]\leq\epsilon=\frac{1}{n}\), where \(N_{\hat{\boldsymbol{\theta}}}\) is the perturbed network. Let \(s>1\) be a constant such that \(n^{s}\geq m(n)+n^{3}\) for every sufficiently large \(n\). By Assumption 2.1, there exists a constant \(k\) and a predicate \(P:\{0,1\}^{k}\rightarrow\{0,1\}\), such that \(\mathcal{F}_{P,n,n^{s}}\) is \(\frac{1}{3}\)-PRG. We will show an efficient algorithm \(\mathcal{A}\) with distinguishing advantage greater than \(\frac{1}{3}\) and thus reach a contradiction. Throughout this proof, we will use the following notations. For a hyperedge \(S=(i_{1},\ldots,i_{k})\) we denote by \(\mathbf{z}^{S}\in\{0,1\}^{kn}\) the following encoding of \(S\): the vector \(\mathbf{z}^{S}\) is a concatenation of \(k\) vectors in \(\{0,1\}^{n}\), such that the \(j\)-th vector has \(0\) in the \(i_{j}\)-th coordinate and \(1\) elsewhere. Thus, \(\mathbf{z}^{S}\) consists of \(k\) size-\(n\) slices, each encoding a member of \(S\). For \(\mathbf{z}\in\{0,1\}^{kn}\), \(i\in[k]\) and \(j\in[n]\), we denote \(z_{i,j}=z_{(i-1)n+j}\). That is, \(z_{i,j}\) is the \(j\)-th component in the \(i\)-th slice in \(\mathbf{z}\). For \(\mathbf{x}\in\{0,1\}^{n}\), let \(P_{\mathbf{x}}:\{0,1\}^{kn}\rightarrow\{0,1\}\) be such that for every hyperedge \(S\) we have \(P_{\mathbf{x}}(\mathbf{z}^{S})=P(\mathbf{x}_{S})\). Let \(c\) be such that \(\Pr_{t\sim\mathcal{N}(0,1)}[t\leq c]=\frac{1}{n}\). Let \(\mu\) be the density of \(\mathcal{N}(0,1)\), let \(\mu_{-}(t)=n\cdot\mathds{1}[t\leq c]\cdot\mu(t)\), and let \(\mu_{+}=\frac{n}{n-1}\cdot\mathds{1}[t\geq c]\cdot\mu(t)\). Note that \(\mu_{-},\mu_{+}\) are the densities of the restriction of \(\mu\) to the intervals \(t\leq c\) and \(t\geq c\) respectively. Let \(\Psi:\mathbb{R}^{kn}\rightarrow\{0,1\}^{kn}\) be a mapping such that for every \(\mathbf{z}^{\prime}\in\mathbb{R}^{kn}\) and \(i\in[kn]\) we have \(\Psi(\mathbf{z}^{\prime})_{i}=\mathds{1}[z^{\prime}_{i}\geq c]\). For \(\tilde{\mathbf{z}}\in\mathbb{R}^{n^{2}}\) we denote \(\tilde{\mathbf{z}}_{[kn]}=(\tilde{z}_{1},\ldots,\tilde{z}_{kn})\), namely, the first \(kn\) components of \(\tilde{\mathbf{z}}\) (assuming \(n^{2}\geq kn\)). ### Defining the target network for \(\mathcal{L}\) Since our goal is to use the algorithm \(\mathcal{L}\) for breaking PRGs, in this subsection we define a neural network \(\tilde{N}:\mathbb{R}^{n^{2}}\rightarrow\mathbb{R}\) that we will later use as a target network for \(\mathcal{L}\). The network \(\tilde{N}\) contains the subnetworks \(N_{1},N_{2},N_{3}\) which we define below. Let \(N_{1}\) be a depth-\(2\) neural network with input dimension \(kn\), at most \(n\log(n)\) hidden neurons, at most \(\log(n)\) output neurons (with activations in the output neurons), and parameter magnitudes bounded by \(n^{3}\) (all bounds are for a sufficiently large \(n\)), which satisfies the following. We denote the set of output neurons of \(N_{1}\) by \(\mathcal{E}_{1}\). Let \(\mathbf{z}^{\prime}\in\mathbb{R}^{kn}\) be an input to \(N_{1}\) such that \(\Psi(\mathbf{z}^{\prime})=\mathbf{z}^{S}\) for some hyperedge \(S\), and assume that for every \(i\in[kn]\) we have \(z^{\prime}_{i}\not\in\left(c,c+\frac{1}{n^{2}}\right)\). Fix some \(\mathbf{x}\in\{0,1\}^{n}\). Then, for \(S\) with \(P_{\mathbf{x}}(\mathbf{z}^{S})=0\) the inputs to all output neurons \(\mathcal{E}_{1}\) are at most \(-1\), and for \(S\) with \(P_{\mathbf{x}}(\mathbf{z}^{S})=1\) there exists a neuron in \(\mathcal{E}_{1}\) with input at least \(2\). Recall that our definition of a neuron's input includes the addition of the bias term. The construction of the network \(N_{1}\) is given in Lemma A.3. Intuitively, the network \(N_{1}\) consists of a layer that transforms w.h.p. the input \(\mathbf{z}^{\prime}\) to \(\Psi(\mathbf{z}^{\prime})=\mathbf{z}^{S}\), followed by a layer that satisfies the following: Building on a lemma from Daniely and Vardi (2021) which shows that \(P_{\mathbf{x}}(\mathbf{z}^{S})\) can be computed by a DNF formula, we define a layer where each output neuron corresponds to a term in the DNF formula, such that if the term evaluates to 0 then the input to the neuron is at most \(-1\), and otherwise it is at least \(2\). Note that the network \(N_{1}\) depends on \(\mathbf{x}\). However, only the second layer depends on \(\mathbf{x}\), and thus given an input we may compute the first layer even without knowing \(\mathbf{x}\). Let \(N_{1}^{\prime}:\mathbb{R}^{kn}\rightarrow\mathbb{R}\) be a depth-\(3\) neural network with no activation function in the output neuron, obtained from \(N_{1}\) by summing the outputs from all neurons \(\mathcal{E}_{1}\). Let \(N_{2}\) be a depth-\(2\) neural network with input dimension \(kn\), at most \(n\log(n)\) hidden neurons, at most \(2n\) output neurons, and parameter magnitudes bounded by \(n^{3}\) (for a sufficiently large \(n\)), which satisfies the following. We denote the set of output neurons of \(N_{2}\) by \(\mathcal{E}_{2}\). Let \(\mathbf{z}^{\prime}\in\mathbb{R}^{kn}\) be an input to \(N_{2}\) such that for every \(i\in[kn]\) we have \(z^{\prime}_{i}\not\in\left(c,c+\frac{1}{n^{2}}\right)\). If \(\Psi(\mathbf{z}^{\prime})\) is an encoding of a hyperedge then the inputs to all output neurons \(\mathcal{E}_{2}\) are at most \(-1\), and otherwise there exists a neuron in \(\mathcal{E}_{2}\) with input at least \(2\). The construction of the network \(N_{2}\) is given in Lemma A.5. Intuitively, each neuron in \(\mathcal{E}_{2}\) is responsible for checking whether \(\Psi(\mathbf{z}^{\prime})\) violates some requirement that must hold in an encoding of a hyperedge. Let \(N_{2}^{\prime}:\mathbb{R}^{kn}\rightarrow\mathbb{R}\) be a depth-\(3\) neural network with no activation function in the output neuron, obtained from \(N_{2}\) by summing the outputs from all neurons \(\mathcal{E}_{2}\). Let \(N_{3}\) be a depth-\(2\) neural network with input dimension \(kn\), at most \(n\log(n)\) hidden neurons, \(kn\leq n\log(n)\) output neurons, and parameter magnitudes bounded by \(n^{3}\) (for a sufficiently large \(n\)), which satisfies the following. We denote the set of output neurons of \(N_{3}\) by \(\mathcal{E}_{3}\). Let \(\mathbf{z}^{\prime}\in\mathbb{R}^{kn}\) be an input to \(N_{3}\). If there exists \(i\in[kn]\) such that \(z^{\prime}_{i}\in\left(c,c+\frac{1}{n^{2}}\right)\) then there exists a neuron in \(\mathcal{E}_{3}\) with input at least \(2\). Moreover, if for all \(i\in[kn]\) we have \(z^{\prime}_{i}\not\in\left(c-\frac{1}{n^{2}},c+\frac{2}{n^{2}}\right)\) then the inputs to all neurons in \(\mathcal{E}_{3}\) are at most \(-1\). The construction of the network \(N_{3}\) is straightforward and given in Lemma A.6. Let \(N_{3}^{\prime}:\mathbb{R}^{kn}\rightarrow\mathbb{R}\) be a depth-\(3\) neural network with no activation function in the output neuron, obtained from \(N_{3}\) by summing the outputs from all neurons \(\mathcal{E}_{3}\). Let \(N^{\prime}:\mathbb{R}^{kn}\rightarrow\mathbb{R}\) be a depth-\(3\) network obtained from \(N_{1}^{\prime},N_{2}^{\prime},N_{3}^{\prime}\) as follows. For \(\mathbf{z}^{\prime}\in\mathbb{R}^{kn}\) we have \(N^{\prime}(\mathbf{z}^{\prime})=\left[1-N_{1}^{\prime}(\mathbf{z}^{\prime})-N_{2 }^{\prime}(\mathbf{z}^{\prime})-N_{3}^{\prime}(\mathbf{z}^{\prime})\right]_{+}\). The network \(N^{\prime}\) has at most \(n^{2}\) neurons, and parameter magnitudes bounded by \(n^{3}\) (all bounds are for a sufficiently large \(n\)). Finally, let \(\tilde{N}:\mathbb{R}^{n^{2}}\rightarrow\mathbb{R}\) be a depth-\(3\) neural network such that \(\tilde{N}(\tilde{\mathbf{z}})=N^{\prime}\left(\tilde{\mathbf{z}}_{[kn]}\right)\). ### Defining the noise magnitude \(\tau\) and analyzing the perturbed network In order to use the algorithm \(\mathcal{L}\) w.r.t. some neural network with parameters \(\boldsymbol{\theta}\), we need to implement an examples oracle, such that the examples are labeled according to a neural network with parameters \(\mathbf{\theta}+\mathbf{\xi}\), where \(\mathbf{\xi}\) is a random perturbation. Specifically, we use \(\mathcal{L}\) with an examples oracle where the labels correspond to a network \(\tilde{N}:\mathbb{R}^{n^{2}}\rightarrow\mathbb{R}\), obtained from \(\tilde{N}\) (w.r.t. an appropriate \(\mathbf{x}\in\{0,1\}^{n}\) in the construction of \(N_{1}\)) by adding a small perturbation to the parameters. The perturbation is such that we add i.i.d. noise to each parameter in \(\tilde{N}\), where the noise is distributed according to \(\mathcal{N}(0,\tau^{2})\), and \(\tau=1/\operatorname{poly}(n)\) is small enough such that the following holds. Let \(f_{\mathbf{\theta}}:\mathbb{R}^{n^{2}}\rightarrow\mathbb{R}\) be any depth-\(3\) neural network parameterized by \(\mathbf{\theta}\in\mathbb{R}^{r}\) for some \(r>0\) with at most \(n^{2}\) neurons, and parameter magnitudes bounded by \(n^{3}\) (note that \(r\) is polynomial in \(n\)). Then with probability at least \(1-\frac{1}{n}\) over \(\mathbf{\xi}\sim\mathcal{N}(0,\tau^{2}I_{r})\), we have \(|\xi_{i}|\leq\frac{1}{10}\) for all \(i\in[r]\), and the network \(f_{\mathbf{\theta}+\mathbf{\xi}}\) is such that for every input \(\tilde{\mathbf{z}}\in\mathbb{R}^{n^{2}}\) with \(\|\tilde{\mathbf{z}}\|\leq 2n\) and every neuron we have: Let \(a,b\) be the inputs to the neuron in the computations \(f_{\mathbf{\theta}}(\tilde{\mathbf{z}})\) and \(f_{\mathbf{\theta}+\mathbf{\xi}}(\tilde{\mathbf{z}})\) (respectively), then \(|a-b|\leq\frac{1}{2}\). Thus, \(\tau\) is sufficiently small, such that w.h.p. adding i.i.d. noise \(\mathcal{N}(0,\tau^{2})\) to each parameter does not change the inputs to the neurons by more than \(\frac{1}{2}\). Note that such an inverse-polynomial \(\tau\) exists, since when the network size, parameter magnitudes, and input size are bounded by some \(\operatorname{poly}(n)\), then the input to each neuron in \(f_{\mathbf{\theta}}(\tilde{\mathbf{z}})\) is \(\operatorname{poly}(n)\)-Lipschitz as a function of \(\mathbf{\theta}\), and thus it suffices to choose \(\tau\) that implies with probability at least \(1-\frac{1}{n}\) that \(\|\mathbf{\xi}\|\leq\frac{1}{q(n)}\) for a sufficiently large polynomial \(q(n)\) (see Lemma A.7 for details). Let \(\tilde{\mathbf{\theta}}\in\mathbb{R}^{p}\) be the parameters of the network \(\tilde{N}\). Recall that the parameters vector \(\tilde{\mathbf{\theta}}\) is the concatenation of all weight matrices and bias terms. Let \(\hat{\mathbf{\theta}}\in\mathbb{R}^{p}\) be the parameters of \(\hat{N}\), namely, \(\hat{\mathbf{\theta}}=\tilde{\mathbf{\theta}}+\mathbf{\xi}\) where \(\mathbf{\xi}\sim\mathcal{N}(0,\tau^{2}I_{p})\). By our choice of \(\tau\) and the construction of the networks \(N_{1},N_{2},N_{3}\), with probability at least \(1-\frac{1}{n}\) over \(\mathbf{\xi}\), for every \(\tilde{\mathbf{z}}\) with \(\|\tilde{\mathbf{z}}\|\leq 2n\), the inputs to the neurons \(\mathcal{E}_{1},\mathcal{E}_{2},\mathcal{E}_{3}\) in the computation \(\hat{N}(\tilde{\mathbf{z}})\) satisfy the following properties, where we denote \(\mathbf{z}^{\prime}=\tilde{\mathbf{z}}_{[kn]}\): 1. If \(\Psi(\mathbf{z}^{\prime})=\mathbf{z}^{S}\) for some hyperedge \(S\), and for every \(i\in[kn]\) we have \(z^{\prime}_{i}\not\in\left(c,c+\frac{1}{n^{2}}\right)\), then the inputs to \(\mathcal{E}_{1}\) satisfy: * If \(P_{\mathbf{x}}(\mathbf{z}^{S})=0\) the inputs to all neurons in \(\mathcal{E}_{1}\) are at most \(-\frac{1}{2}\). * If \(P_{\mathbf{x}}(\mathbf{z}^{S})=1\) there exists a neuron in \(\mathcal{E}_{1}\) with input at least \(\frac{3}{2}\). 2. If for every \(i\in[kn]\) we have \(z^{\prime}_{i}\not\in\left(c,c+\frac{1}{n^{2}}\right)\), then the inputs to \(\mathcal{E}_{2}\) satisfy: * If \(\Psi(\mathbf{z}^{\prime})\) is an encoding of a hyperedge then the inputs to all neurons \(\mathcal{E}_{2}\) are at most \(-\frac{1}{2}\). * Otherwise, there exists a neuron in \(\mathcal{E}_{2}\) with input at least \(\frac{3}{2}\). 3. The inputs to \(\mathcal{E}_{3}\) satisfy: * If there exists \(i\in[kn]\) such that \(z^{\prime}_{i}\in\left(c,c+\frac{1}{n^{2}}\right)\) then there exists a neuron in \(\mathcal{E}_{3}\) with input at least \(\frac{3}{2}\). * If for all \(i\in[kn]\) we have \(z^{\prime}_{i}\not\in\left(c-\frac{1}{n^{2}},c+\frac{2}{n^{2}}\right)\) then the inputs to all neurons in \(\mathcal{E}_{3}\) are at most \(-\frac{1}{2}\). ### Stating the algorithm \(\mathcal{A}\) Given a sequence \((S_{1},y_{1}),\ldots,(S_{n^{s}},y_{n^{s}})\), where \(S_{1},\ldots,S_{n^{s}}\) are i.i.d. random hyperedges, the algorithm \(\mathcal{A}\) needs to distinguish whether \(\mathbf{y}=(y_{1},\ldots,y_{n^{s}})\) is random or that \(\mathbf{y}=(P(\mathbf{x}_{S_{1}}),\ldots,P(\mathbf{x}_{S_{n^{s}}}))=(P_{ \mathbf{x}}(\mathbf{z}^{S_{1}}),\ldots,P_{\mathbf{x}}(\mathbf{z}^{S_{n^{s}}}))\) for a random \(\mathbf{x}\in\{0,1\}^{n}\). Let \(\mathcal{S}=((\mathbf{z}^{S_{1}},y_{1}),\ldots,(\mathbf{z}^{S_{n^{s}}},y_{n^{s} }))\). We use the efficient algorithm \(\mathcal{L}\) in order to obtain distinguishing advantage greater than \(\frac{1}{3}\) as follows. Let \(\mathbf{\xi}\) be a random perturbation, and let \(\hat{N}\) be the perturbed network as defined above, w.r.t. the unknown \(\mathbf{x}\in\{0,1\}^{n}\). Note that given a perturbation \(\mathbf{\xi}\), only the weights in the second layer of the subnetwork \(N_{1}\) in \(\hat{N}\) are unknown, since all other parameters do not depend on \(\mathbf{x}\). The algorithm \(\mathcal{A}\) runs \(\mathcal{L}\) with the following examples oracle. In the \(i\)-th call, the oracle first draws \(\mathbf{z}\in\{0,1\}^{kn}\) such that each component is drawn i.i.d. from a Bernoulli distribution which takes the value \(0\) with probability \(\frac{1}{n}\). If \(\mathbf{z}\) is an encoding of a hyperedge then the oracle replaces \(\mathbf{z}\) with \(\mathbf{z}^{S_{i}}\). Then, the oracle chooses \(\mathbf{z}^{\prime}\in\mathbb{R}^{kn}\) such that for each component \(j\), if \(z_{j}\geq c\) then \(z^{\prime}_{j}\) is drawn from \(\mu_{+}\), and otherwise \(z^{\prime}_{j}\) is drawn from \(\mu_{-}\). Let \(\tilde{\mathbf{z}}\in\mathbb{R}^{n^{2}}\) be such that \(\tilde{\mathbf{z}}_{[kn]}=\mathbf{z}^{\prime}\), and the other \(n^{2}-kn\) components of \(\tilde{\mathbf{z}}\) are drawn i.i.d. from \(\mathcal{N}(0,1)\). Note that the vector \(\tilde{\mathbf{z}}\) has the distribution \(\mathcal{D}\), due to the definitions of the densities \(\mu_{+}\) and \(\mu_{-}\), and since replacing an encoding of a random hyperedge by an encoding of another random hyperedge does not change the distribution of \(\mathbf{z}\). Let \(\hat{b}\in\mathbb{R}\) be the bias term of the output neuron of \(\hat{N}\). The oracle returns \((\tilde{\mathbf{z}},\tilde{y})\), where the labels \(\tilde{y}\) are chosen as follows: * If \(\Psi(\mathbf{z}^{\prime})\) is not an encoding of a hyperedge, then \(\tilde{y}=0\). * If \(\Psi(\mathbf{z}^{\prime})\) is an encoding of a hyperedge: * If \(\mathbf{z}^{\prime}\) does not have components in the interval \((c-\frac{1}{n^{2}},c+\frac{2}{n^{2}})\), then if \(y_{i}=0\) we set \(\tilde{y}=\hat{b}\), and if \(y_{i}=1\) we set \(\tilde{y}=0\). * If \(\mathbf{z}^{\prime}\) has a component in the interval \((c,c+\frac{1}{n^{2}})\), then \(\tilde{y}=0\). * If \(\mathbf{z}^{\prime}\) does not have components in the interval \((c,c+\frac{1}{n^{2}})\), but has a component in the interval \((c-\frac{1}{n^{2}},c+\frac{2}{n^{2}})\), then the label \(\tilde{y}\) is determined as follows: * If \(y_{i}=1\) then \(\tilde{y}=0\). * If \(y_{i}=0\): Let \(\hat{N}_{3}\) be the network \(\hat{N}\) after omitting the neurons \(\mathcal{E}_{1},\mathcal{E}_{2}\) and their incoming and outgoing weights. Then, we set \(\tilde{y}=[\hat{b}-\hat{N}_{3}(\tilde{\mathbf{z}})]_{+}\). Note that since only the first layer of \(N_{1}\) depends on \(\mathbf{x}\), then we can compute \(\hat{N}_{3}(\tilde{\mathbf{z}})\) without knowing \(\mathbf{x}\). Let \(h\) be the hypothesis returned by \(\mathcal{L}\). Recall that \(\mathcal{L}\) uses at most \(m(n)\) examples, and hence \(\mathcal{S}\) contains at least \(n^{3}\) examples that \(\mathcal{L}\) cannot view. We denote the indices of these examples by \(I=\{m(n)+1,\ldots,m(n)+n^{3}\}\), and the examples by \(\mathcal{S}_{I}=\{(\mathbf{z}^{S_{i}},y_{i})\}_{i\in I}\). By \(n^{3}\) additional calls to the oracle, the algorithm \(\mathcal{A}\) obtains the examples \(\tilde{\mathcal{S}}_{I}=\{(\tilde{\mathbf{z}}_{i},\tilde{y}_{i})\}_{i\in I}\) that correspond to \(\mathcal{S}_{I}\). Let \(h^{\prime}\) be a hypothesis such that for all \(\tilde{\mathbf{z}}\in\mathbb{R}^{n^{2}}\) we have \(h^{\prime}(\tilde{\mathbf{z}})=\max\{0,\min\{\hat{b},h(\tilde{\mathbf{z}})\}\}\), thus, for \(\hat{b}\geq 0\) the hypothesis \(h^{\prime}\) is obtained from \(h\) by clipping the output to the interval \([0,\hat{b}]\). Let \(\ell_{I}(h^{\prime})=\frac{1}{|I|}\sum_{i\in I}(h^{\prime}(\tilde{\mathbf{z}}_ {i})-\tilde{y}_{i})^{2}\). Now, if \(\ell_{I}(h^{\prime})\leq\frac{2}{n}\), then \(\mathcal{A}\) returns \(1\), and otherwise it returns \(0\). We remark that the decision of our algorithm is based on \(h^{\prime}\) (rather than \(h\)) since we need the outputs to be bounded, in order to allow using Hoeffding's inequality in our analysis, which we discuss in the next subsection. ### Analyzing the algorithm \(\mathcal{A}\) Note that the algorithm \(\mathcal{A}\) runs in \(\mathrm{poly}(n)\) time. We now show that if \(\mathcal{S}\) is pseudorandom then \(\mathcal{A}\) returns \(1\) with probability greater than \(\frac{2}{3}\), and if \(\mathcal{S}\) is random then \(\mathcal{A}\) returns \(1\) with probability less than \(\frac{1}{3}\). We start with the case where \(\mathcal{S}\) is pseudorandom. In Lemma A.8, we prove that if \(\mathcal{S}\) is pseudorandom then w.h.p. (over \(\boldsymbol{\xi}\sim\mathcal{N}(\mathbf{0},\tau^{2}I_{p})\) and the i.i.d. inputs \(\tilde{\mathbf{z}}_{i}\sim\mathcal{D}\)) the examples \((\tilde{\mathbf{z}}_{1},\tilde{y}_{1}),\ldots,(\tilde{\mathbf{z}}_{m(n)+n^{3}},\tilde{y}_{m(n)+n^{3}})\) returned by the oracle are realized by \(\hat{N}\). Thus, \(\tilde{y}_{i}=\hat{N}(\tilde{\mathbf{z}}_{i})\) for all \(i\). As we show in the lemma, this claim follows by noting that the following hold w.h.p., where we denote \(\mathbf{z}^{\prime}_{i}=(\tilde{\mathbf{z}}_{i})_{[kn]}\): * If \(\Psi(\mathbf{z}^{\prime}_{i})\) is not an encoding of a hyperedge, then the oracle sets \(\tilde{y}_{i}=0\), and we have: If \(\mathbf{z}_{i}^{\prime}\) does not have components in \(\left(c,c+\frac{1}{n^{2}}\right)\), then there exists a neuron in \(\mathcal{E}_{2}\) with output at least \(\frac{3}{2}\) (by Property (P2)), which implies \(\hat{N}(\tilde{\mathbf{z}}_{i})=0\). * If \(\mathbf{z}^{\prime}\) has a component in \(\left(c,c+\frac{1}{n}\right)\), then there exists a neuron in \(\mathcal{E}_{3}\) with output at least \(\frac{3}{2}\) (by Property (P3)), which implies \(\hat{N}(\tilde{\mathbf{z}}_{i})=0\). * If \(\Psi(\mathbf{z}_{i}^{\prime})\) is an encoding of a hyperedge \(S\), then by the definition of the examples oracle we have \(S=S_{i}\). Hence: * If \(\mathbf{z}_{i}^{\prime}\) does not have components in \(\left(c-\frac{1}{n^{2}},c+\frac{2}{n^{2}}\right)\), then: * If \(y_{i}=0\) then the oracle sets \(\tilde{y}_{i}=\hat{b}\). Since \(\mathcal{S}\) is pseudorandom, we have \(P_{\mathbf{x}}(\mathbf{z}^{S})=P_{\mathbf{x}}(\mathbf{z}^{S_{i}})=y_{i}=0\). Hence, in the computation \(\hat{N}(\tilde{\mathbf{z}}_{i})\) the inputs to all neurons in \(\mathcal{E}_{1},\mathcal{E}_{2},\mathcal{E}_{3}\) are at most \(-\frac{1}{2}\) (by Properties (P1), (P2) and (P3)), and thus their outputs are \(0\). Therefore, \(\hat{N}(\tilde{\mathbf{z}}_{i})=\hat{b}\). * If \(y_{i}=1\) then the oracle sets \(\tilde{y}_{i}=0\). Since \(\mathcal{S}\) is pseudorandom, we have \(P_{\mathbf{x}}(\mathbf{z}^{S})=P_{\mathbf{x}}(\mathbf{z}^{S_{i}})=y_{i}=1\). Hence, in the computation \(\hat{N}(\tilde{\mathbf{z}}_{i})\) there exists a neuron in \(\mathcal{E}_{1}\) with output at least \(\frac{3}{2}\) (by Property (P1)), which implies \(\hat{N}(\tilde{\mathbf{z}}_{i})=0\). * If \(\mathbf{z}_{i}^{\prime}\) has a component in \(\left(c,c+\frac{1}{n^{2}}\right)\), then the oracle sets \(\tilde{y}_{i}=0\). Also, in the computation \(\hat{N}(\tilde{\mathbf{z}}_{i})\) there exists a neuron in \(\mathcal{E}_{3}\) with output at least \(\frac{3}{2}\) (by Property (P3)), which implies \(\hat{N}(\tilde{\mathbf{z}}_{i})=0\). * If \(\mathbf{z}_{i}^{\prime}\) does not have components in the interval \((c,c+\frac{1}{n^{2}})\), but has a component in the interval \((c-\frac{1}{n^{2}},c+\frac{2}{n^{2}})\), then: * If \(y_{i}=1\) the oracle sets \(\tilde{y}_{i}=0\). Since \(\mathcal{S}\) is pseudorandom, we have \(P_{\mathbf{x}}(\mathbf{z}^{S})=P_{\mathbf{x}}(\mathbf{z}^{S_{i}})=y_{i}=1\). Hence, in the computation \(\hat{N}(\tilde{\mathbf{z}}_{i})\) there exists a neuron in \(\mathcal{E}_{1}\) with output at least \(\frac{3}{2}\) (by Property (P1)), which implies \(\hat{N}(\tilde{\mathbf{z}}_{i})=0\). * If \(y_{i}=0\) the oracle sets \(\tilde{y}_{i}=[\hat{b}-\hat{N}_{3}(\tilde{\mathbf{z}}_{i})]_{+}\). Since \(\mathcal{S}\) is pseudorandom, we have \(P_{\mathbf{x}}(\mathbf{z}^{S})=P_{\mathbf{x}}(\mathbf{z}^{S_{i}})=y_{i}=0\). Therefore, in the computation \(\hat{N}(\tilde{\mathbf{z}}_{i})\) all neurons in \(\mathcal{E}_{1},\mathcal{E}_{2}\) have output \(0\) (by Properties (P1) and (P2)), and hence their contribution to the output of \(\hat{N}\) is \(0\). Thus, by the definition of \(\hat{N}_{3}\), we have \(\hat{N}(\tilde{\mathbf{z}}_{i})=[\hat{b}-\hat{N}_{3}(\tilde{\mathbf{z}}_{i})]_{+}\). Recall that the algorithm \(\mathcal{L}\) is such that with probability at least \(\frac{3}{4}\) (over \(\boldsymbol{\xi}\sim\mathcal{N}(\mathbf{0},\tau^{2}I_{p})\), the i.i.d. inputs \(\tilde{\mathbf{z}}_{i}\sim\mathcal{D}\), and its internal randomness), given a size-\(m(n)\) dataset labeled by \(\hat{N}\), it returns a hypothesis \(h\) such that \(\mathbb{E}_{\tilde{\mathbf{z}}\sim\mathcal{D}}\left[\left(h(\tilde{\mathbf{z}}) -\hat{N}(\tilde{\mathbf{z}})\right)^{2}\right]\leq\frac{1}{n}\). By the definition of \(h^{\prime}\) and the construction of \(\hat{N}\), if \(h\) has small error then \(h^{\prime}\) also has small error, namely, we have \(\mathbb{E}_{\tilde{\mathbf{z}}\sim\mathcal{D}}\left[(h^{\prime}(\tilde{ \mathbf{z}})-\hat{N}(\tilde{\mathbf{z}}))^{2}\right]\leq\frac{1}{n}\). In Lemma A.9 we use the above arguments and Hoeffding's inequality over \(\tilde{\mathcal{S}}_{I}\), and prove that with probability greater than \(\frac{2}{3}\) we have \(\ell_{I}(h^{\prime})\leq\frac{2}{n}\). Next, we consider the case where \(\mathcal{S}\) is random. Let \(\tilde{\mathcal{Z}}\subseteq\mathbb{R}^{n^{2}}\) be such that \(\tilde{\mathbf{z}}\in\tilde{\mathcal{Z}}\) iff \(\tilde{\mathbf{z}}_{[kn]}\) does not have components in the interval \((c-\frac{1}{n^{2}},c+\frac{2}{n^{2}})\), and \(\Psi(\tilde{\mathbf{z}}_{[kn]})=\mathbf{z}^{S}\) for a hyperedge \(S\). If \(\mathcal{S}\) is random, then by the definition of our examples oracle, for every \(i\in[m(n)+n^{3}]\) such that \(\tilde{\mathbf{z}}_{i}\in\tilde{\mathcal{Z}}\), we have \(\tilde{y}_{i}=\hat{b}\) with probability \(\frac{1}{2}\) and \(\tilde{y}_{i}=0\) otherwise. Also, by the definition of the oracle, \(\tilde{y}_{i}\) is independent of \(S_{i}\) and independent of the choice of the vector \(\tilde{\mathbf{z}}_{i}\) that corresponds to \(\mathbf{z}^{S_{i}}\). Hence, for such \(\tilde{\mathbf{z}}_{i}\in\tilde{\mathcal{Z}}\) with \(i\in I\), any hypothesis cannot predict the label \(\tilde{y}_{i}\), and the expected loss for the example is at least \(\left(\frac{\hat{b}}{2}\right)^{2}\). Moreover, in Lemma A.11 we show that \(\Pr\left[\tilde{\mathbf{z}}_{i}\in\tilde{\mathcal{Z}}\right]\geq\frac{1}{2\log(n)}\) for a sufficiently large \(n\). In Lemma A.12 we use these arguments to prove a lower bound on \(\mathbb{E}_{\mathcal{S}_{I}}\left[\ell_{I}(h^{\prime})\right]\), and by Hoeffding's inequality over \(\widehat{\mathcal{S}}_{I}\) we conclude that with probability greater than \(\frac{2}{3}\) we have \(\ell_{I}(h^{\prime})>\frac{2}{n}\). Overall, if \(\mathcal{S}\) is pseudorandom then with probability greater than \(\frac{2}{3}\) the algorithm \(\mathcal{A}\) returns \(1\), and if \(\mathcal{S}\) is random then with probability greater than \(\frac{2}{3}\) the algorithm \(\mathcal{A}\) returns \(0\). Thus, the distinguishing advantage is greater than \(\frac{1}{3}\). ## 5 Discussion Understanding the computational complexity of learning neural networks is a central question in learning theory. Our results imply that the assumptions which allow for efficient learning in one-hidden-layer networks might not suffice in deeper networks. Also, in depth-\(2\) networks we show that it is not sufficient to assume that both the parameters and the inputs are smoothed. We hope that our hardness results will help focus on assumptions that may allow for efficient learning. Below we discuss several intriguing open problems. First, we emphasize that our hardness results are for neural networks that include the ReLU activation also in the output neuron. In contrast, the positive results on learning depth-\(2\) networks that we discussed in the introduction do not include activation in the output neuron. Therefore, as far as we are aware, there is still a gap between the upper bounds and our hardness results: (1) Under the assumption that the input is Gaussian and the weights are non-degenerate, the cases of depth-\(2\) networks with activation in the output neuron and of depth-\(3\) networks without activation in the output are not settled; (2) In the setting where both the parameters and the input distribution are smoothed, the case of depth-\(2\) networks without activation in the output is not settled. Moreover, our hardness result for depth-\(3\) networks suggests that adding a small (yet polynomial) noise to the parameters is not sufficient to allow efficient learning under the Gaussian distribution. An intriguing direction is to explore the case where the noise is larger. Intuitively, the case of very large noise corresponds to learning a random network, where the weights are drawn i.i.d. from the Gaussian distribution. Hence, it would be interesting to understand whether there is an efficient algorithm for learning random ReLU networks under the Gaussian input distribution. Likewise, the effect of large noise may also be considered w.r.t. the inputs, namely, we may use large noise for obtaining smoothed input distributions. ### Acknowledgements This work was done as part of the NSF-Simons Sponsored Collaboration on the Theoretical Foundations of Deep Learning.
2306.11758
MRFI: An Open Source Multi-Resolution Fault Injection Framework for Neural Network Processing
To ensure resilient neural network processing on even unreliable hardware, comprehensive reliability analysis against various hardware faults is generally required before the deep neural network models are deployed, and efficient error injection tools are highly demanded. However, most existing fault injection tools remain rather limited to basic fault injection to neurons and fail to provide fine-grained vulnerability analysis capability. In addition, many of the fault injection tools still need to change the neural network models and make the fault injection closely coupled with normal neural network processing, which further complicates the use of the fault injection tools and slows down the fault simulation. In this work, we propose MRFI, a highly configurable multi-resolution fault injection tool for deep neural networks. It enables users to modify an independent fault configuration file rather than neural network models for the fault injection and vulnerability analysis. Particularly, it integrates extensive fault analysis functionalities from different perspectives and enables multi-resolution investigation of the vulnerability of neural networks. In addition, it does not modify the major neural network computing framework of PyTorch. Hence, it allows parallel processing on GPUs naturally and exhibits fast fault simulation according to our experiments.
Haitong Huang, Cheng Liu, Bo Liu, Xinghua Xue, Huawei Li, Xiaowei Li
2023-06-20T06:46:54Z
http://arxiv.org/abs/2306.11758v2
# MRFI: An Open Source Multi-Resolution Fault Injection Framework for Neural Network Processing ###### Abstract To ensure resilient neural network processing on even unreliable hardware, comprehensive reliability analysis against various hardware faults is generally required before the deep neural network models are deployed, and efficient error injection tools are highly demanded. However, most existing fault injection tools remain rather limited to basic fault injection to neurons and fail to provide fine-grained vulnerability analysis capability. In addition, many of the fault injection tools still need to change the neural network models and make the fault injection closely coupled with normal neural network processing, which further complicates the use of the fault injection tools and slows down the fault simulation. In this work, we propose MRFI, a highly configurable multi-resolution fault injection tool for deep neural networks. It enables users to modify an independent fault configuration file rather than neural network models for the fault injection and vulnerability analysis. Particularly, it integrates extensive fault analysis functionalities from different perspectives and enables multi-resolution investigation of the vulnerability of neural networks. In addition, it does not modify the major neural network computing framework of PyTorch. Hence, it allows parallel processing on GPUs naturally and exhibits fast fault simulation according to our experiments. ## I Introduction Deep neural network models are increasingly used in safety-critical applications like autonomous driving and avionics, but computational errors caused by imperfect hardware such as process variations, defects and impurities in materials, and noise can lead to unexpected inference and cause severe consequences in these safety-critical applications. To guarantee resilient deep learning, it is crucial to thoroughly evaluate the reliability of neural network models before their deployment. While it is prohibitively expensive to perform fault injection to realistic chips, simulation based error injection tools such as PyTorchFI [1], Ares [2], TensorFlow [3], TorchFI [4], and MindFI [5] have been extensively developed. These tools typically provide basic functionalities such as error injection and reliability analysis to general neural network processing and significantly alleviate the design efforts required for neural network reliability analysis in presence of various hardware errors. Nevertheless, it has become evident that existing fault injection tools are insufficient to address complex neural network reliability analysis for the following aspects. First, they generally utilize hardware fault models such as bit flip model to simulate the influence of hardware errors on neural network processing, but they do not model any specific hardware architectures and the correlation between the neuron-wise error injection and realistic hardware-based fault injection remains unclear. The accuracy of the fault simulation needs to be calibrated such that it can be utilized as a common metric to reliability study of neural network processing. Second, there is a lack of standard error injection metrics and neural network evaluation metrics that can be utilized to align the fault simulation results and distinct fault simulation results may be obtained from these different fault injection tools, which dramatically affects the reliability study of neural network processing. For instance, many prior fault injection tools fail to clarify the model quantization during reliability evaluation [6] and biased evaluation results are obtained because of the quantization setups. Third, many of the fault injection tools are closely coupled with the neural network frameworks such as PyTorch. The error model and error injection may vary with the different neural network layers [7], which also complicates the fault simulation. In addition, fine-grained selective fault-tolerant design [8] has also been explored and it poses great challenges to the fault simulation and evaluation of existing fault injection tools. These unique fault simulation and evaluation requirements further make the fault injection frameworks difficult to scale and port to GPUs or other parallel computing systems. To address the above problems, we present MRFI, a highly configurable open-sourced fault injection tool for reliability investigation and evaluation of neural network processing. On the one hand, it provides unified error models, neural network quantization setups, and error injection mechanisms to ensure consistent metrics of error injection and reliability evaluation. Moreover, it is compared to typical fault injection platforms with more detailed architectural details and calibrated for more fair comparison. On the other hand, it provides a multi-resolution vulnerability investigation of neural network processing from distinct angles and granularities, which can be utilized to guide selective fault-tolerant neural network design conveniently. In addition, MRFI utilizes a tree structure for flexible error injection configurations and reliability evaluation of different neural network modules without modifying the neural network processing engines, which will not affect the underlying parallel computing engines on GPUs and can achieve the state-of-the-art fault simulation. The contributions of this paper can be summarized as follows: * We present an open-sourced multi-resolution fault injection framework MRFI and have it calibrated with architecture-specific fault injection frameworks. * MRFI provides unified error injection and reliability evaluation with flexible simulation configurations. Particularly, it allows fine-grained vulnerability analysis from different angles and can be utilized for selective protection against various hardware errors. * MRFI is built on top of PyTorch and does not affect the computing engine of PyTorch. Hence, the fault injection and reliability evaluation can be scaled to parallel computing systems like GPUs conveniently and achieve competitive simulation speed. ## II Related Work Research on the reliability and fault tolerance of deep learning revolves around error simulation, fault evaluation, fault-tolerant model design, and fault-tolerant hardware design. Error simulation methods can be divided into hardware-level simulation and model-level simulation. Hardware-level simulation is generally more accurate but has limited generality and performance due to the need to simulate the underlying logic of specific hardware architectures. Notable works in this area include NVIDIA SASSIFI for fault injection simulation on GPUs [9] and fault simulation on FPGAs [8][10][11][12]. These error simulation methods often require tens to thousands of times the normal execution time. On the other hand, model-level evaluation and simulation have better performance, making them widely studied in previous works. Some notable works in this area include [1][3][2][13][5][4]. Some works have shown that accurate hardware-level reliability results can be obtained through model-level simulation. For example, in Are [2], the authors obtained consistent measurements with silicon measurement by injecting errors at the model level. Yi He et al. [7] mapped hardware unit error rates to model neurons to obtain accurate model-level evaluation results. Xinghua Xue et al. [14] improved the accuracy of computational evaluation by focusing on operations. Some works aim to improve the performance of error simulation. For example, PyTorchFI [1] optimized the implementation of fault injection simulation, reducing the additional time overhead of single-point fault injection to a negligible level. The closest state-of-the-art tools to our work are PyTorchFI and Ares, which offer more comprehensive functionality compared to other works. Table I shows a summary of their features. For fault evaluation, recent works have proposed improved statistical metrics and mathematical modeling analysis to further reduce the number of error simulations required. In HarDNN [15], the authors explored various surrogate test metrics to replace simple model accuracy measurements, resulting in a 10-times reduction in simulation count under the same simulation accuracy. BinFI [16] models error propagation and introduces binary search to reduce the number of simulations. [17] achieved a two-order-of-magnitude speedup in fault evaluation by using statistical modeling. Previous fault injection frameworks did not consider these optimizations, whereas our framework's flexibility allows researchers to conveniently perform these evaluations. After fault evaluation, safety-critical systems often require fault-tolerant design. Fault-tolerant design can be applied at both the software and hardware levels, such as adjusting models for fault tolerance or introducing additional hardware redundancy computations [18][19][20][21][22]. These solutions include Selective Hardening [8], Algorithm-Based Fault Tolerance [23], adjustment of quantization parameter settings [6], adjustment of activation layer values to limit numerical magnitude [24], fault-tolerant retraining [25], and more. Evaluating these solutions requires a more flexible fault injection framework. ## III MRFI Framework ### _MRFI Overview_ The overall structure of MRFI is illustrated in Figure 1. The framework as a whole can be divided into two parts: the configuration part and the execution modules, which are further divided into several functional modules. MRFI provides two main approaches to configure different experimental requirements: EasyConfig for simple and preliminary experiments, and a detailed error injection configuration tree for more complex needs. For simple experiments, EasyConfig allows users to specify the layers and fault injection method through a config file. This configuration applies uniformly to the specified set of layers, enabling users to conduct fault injection experiments by loading the corresponding error injection configuration, similar to working with a typical PyTorch model. To address complex and precise error injection requirements without modifying the experimental model, MRFI employs a detailed error injection configuration tree. This tree records the error injection configurations for various modules and layers of a model. Users can easily adjust the parameters within the configuration tree to meet their specific needs. MRFI's error injection module then dynamically performs error injection based on the configured settings. The execution modules of MRFI offer multiple commonly used injection methods that encompass the majority of error injection requirements for experiments. For enhanced flexibility, users can also customize the execution module according to their specific needs. The structured configuration approach of MRFI offers several advantages over previous manual error injection implementations. In the traditional manual approach, experimenters typically need to modify both the neural network model code and the error injection parameters to accommodate different error injection requirements. This process is hard especially for modern large-scale models with numerous layers. Additionally, manually adjusting error injection parameters for multiple fine-grained settings in dozens of model layers is cumbersome, making experimental management challenging. MRFI overcomes these issues by decoupling the error injection configuration from the model definition and organizing it into separate modules, facilitating error injection experiments with specific configurations. ### _Integration with PyTorch_ MRFI is built upon PyTorch, the widely adopted neural network training framework. Error injection in MRFI is achieved through PyTorch hook, allowing for seamless integration with the model. PyTorch serves as the foundation for MRFI due to its extensive user base and well-established software ecosystem. Additionally, we have found that PyTorch's dynamic graph approach aligns well with error injection scenarios that necessitate dynamic modification and configuration. The hook function in PyTorch enables dynamic observation and modification of intermediate data within network modules, making it highly suitable for fine-grained error injection experiment configuration. An alternative implementation approach involves adding or replacing layers in the model with fault injection operations. However, this method requires prior knowledge of the original layer implementations, which is impractical given the diverse range of user-defined modules and layers. It is worth noting that error injection at the model level only requires access to the model's weights and feature map information for modification. By leveraging hooks, rewriting of the underlying computation implementation is not necessary. Our execution module also mainly uses PyTorch tensors, which allows the error injection process to be naturally used on the CPU and GPU to maximize performance. ### _Major MRFI Components_ As depicted in Figure 1, MRFI incorporates three key components for fault injection: quantizer, selector, and error model. Additionally, an observer feature is available for monitoring numerical values and their error impact within the model. #### Iii-C1 Quantizer In MRFI, we recognize the significance of quantization methods in evaluating fault tolerance. Quantization is commonly employed during inference for fixed-point or integer computations, differing from the floating-point storage and computation used during model training. Previous studies highlight the varying fault-tolerance characteristics of different numerical representations and the influence of quantization choices on model accuracy and fault tolerance. To facilitate accurate fault simulation for quantized models, MRFI offers multiple configurable quantization options. These simulated quantizations encompass the quantization and de-quantization steps, converting tensors from floating-point to integer format and vice versa. The quantizer serves as a wrapper for the fault injection component, enabling the provision of integer tensors to the selector and error model for simulating integer computation and error occurrence on real hardware. It is worth noting that the quantizer is optional, and users can omit it if they solely require simulations with floating-point models. #### Iii-C2 Selector The selector determines the locations within the tensor where errors are injected. By defining the selector, users can specify the manner in which errors manifest. For example, a fixed position selector can be employed to evaluate the impact of permanent errors. Conversely, a random position selector serves as a random engine to simulate the occurrence of soft errors. Soft errors are often associated with a bit error rate, and the random position selector efficiently generates erroneous positions based on this rate. Users also have the flexibility to customize filtering masks at the selector level or implement custom selectors to simulate fine-grained selective fault-tolerant protection. #### Iii-C3 Error model The error model dictates how errors are injected into the numerical values at the selected error positions. The error model may rely on the original numerical values, such as random bit flips for integers or floating-point numbers, fixed bit flips, or the addition of perturbations following a normal distribution. Alternatively, the error model may be independent of the original numerical values, involving stuck-at 0 faults, faults with specific fixed numerical values, or random uniform integers or floating-point numbers. MRFI incorporates these common error models, while also allowing users to define custom error models conveniently. #### Iii-B4 Observer MRFI provides internal observers to enhance the visibility of numerical values and their error impact within the model. Observers that do not require fault injection can be employed to monitor the distribution of internal activation values. For example, an observer can track the maximum and minimum values to determine the dynamic range of activations, aiding in the determination of model quantization parameters. Another type of observer enables the comparison between fault injection and non-fault injection scenarios. Before initiating fault injection, this observer conducts a golden run comparison analysis. It can utilize a counter to tally the number of numerical values affected by fault injection or employ an RMSE observer to gauge the extent of error propagation. ## IV Experiment Results In this section, we present the results of various error injection experiments conducted using MRFI. Our focus is on demonstrating experimental approaches not covered by previous error injection tools, highlighting the necessity of utilizing a more fine-grained error injection framework. For our experiments, we primarily employ VGG and ResNet models evaluated on the ImageNet dataset. In subsection IV-B, we also utilize a smaller dataset, cifar-10, to visualize error propagation. ### _Basic BER-Accuracy fault inject experiment_ We begin by testing and evaluating MRFI's performance under simple configurations. Specifically, we conduct random bit flipping error injection on the quantization weight of the VGG16 model using the fixed-point quantization settings of 2.12 and 3.13. Additionally, MRFI supports different data types and quantization methods. For comparison, we include Fig. 1: The MRFI tool integrates multiple modules. The configuration part can be used for simple and detailed experiments. The execution module provides a variety of predefined functions. Fig. 2: Relation between bit error rates and classification error rate of different data type. the original 32-bit floating point (f32) and layer-wise range quantization (Qlayer). As illustrated in Figure 2(a)(b), our results of fixed-point quantization with settings 2.12 and 3.13 align with those obtained from Ares [2], exhibiting a significant increase in bit error rates at \(BER=10^{-6}\). In contrast, floating-point types exhibit lower error tolerance, while layered quantization demonstrates superior fault tolerance, corroborating the conclusions from SNR [6]. In Figure 2(c)(d), the injection of activation values exhibits a similar trend, but not entirely the same. While the above experiments could be conducted separately using different fault injection tools in the past, the advantage of MRFI lies in its integration of diverse functionalities within a unified framework. ### _Observing error propagation_ To gain deeper insights into error propagation within the network, MRFI provides a straightforward operation to apply error observers to all network modules. These observers enhance transparency and offer diverse perspectives for in-depth research on error impact. Firstly, we employ a simple equation comparison observer to assess the number of neurons affected by a single injection. We perform one-bit flipping on the activation values and weights of the first convolution layer (conv1) of VGG11, and then calculate the average number of errors across 10,000 input images. The golden run accuracy and accuracy after activation injection both yield \(76.49\%\), while the accuracy after weight injection slightly decreases to \(76.34\%\). As shown in Figure 3, the number of affected neurons increases rapidly along the layers, with nearly all neurons in the fully-connected layers displaying differences from their original values. This indicates the network's resilience to errors, while also highlighting that the number of affected neurons is not a good indicator of the severity of error effects. Next, we evaluate error propagation using more robust metrics. Inspired by [15][17], MRFI provides mean absolute error (MAE) and rooted mean square error (RMSE) observers. In Figure 4, both MAE and RMSE reveal that weight injection has a significantly greater influence than activation value injection when performing single-point injection on the first convolution layer. This finding aligns with the accuracy results. Additionally, although the number of affected neurons rapidly increases during the propagation process, these error measures remain relatively stable. MRFI also includes observers for recording activation and error values directly, facilitating the visualization of internal feature maps in neural networks. Figure 5 showcases the raw neuron values input by LeNet on a single image from the cifar-10 dataset, along with the errors caused by a single activation injection in the first layer. We observe that errors occur in fixed positions across all channels in the convolution layer's feature map, while nearly all neurons in the fully connected layers experience irregular disturbances. ### _Quantization Settings Resilience Study_ Recent studies have highlighted the close relationship between quantization methods and neural network fault tolerance. Therefore, our framework integrates quantization settings into its configuration. In subsection IV-A, we compared the differences between two quantization methods using a simple global quantization setting. With MRFI, we can now quantize each submodule of the network separately to study these differences at a fine-grained level. Figure 6 illustrates the differences in RMSE metrics for various error injections on different layers and blocks of ResNet18. A larger RMSE value indicates greater sensitivity to errors. It is evident that global quantization settings exhibit significant variations in fault tolerance and perform poorly at each layer, resulting in lower fault tolerance than layered quantization. Conversely, layerwise quantization demonstrates stable error resilience. Additionally, we observe that weights are more sensitive to errors during global quantization, whereas weights Fig. 4: Evaluate error propagation by better metrics. Fig. 3: Number of affected neurons of one bit flip on first layer in VGG-11. and activation values exhibit similar sensitivities during layer-wise quantization. The quantization parameters of the model also impact fault tolerance. In MRFI, we employ layerwise quantization and set different quantization scaling factors for each layer of the model. We evaluate accuracy and RMSE in ResNet as an example. As shown in Figure 7, larger scale factors generally lead to worse fault tolerance. In practical deployment scenarios, models are typically quantized after training, and the quantization parameters depend on both model accuracy and target hardware requirements. The experimental differences outlined above emphasize the need for a thorough assessment of the quantization methods' impact when deploying security-critical neural network models. ### _Evaluate Fault-Tolerant Resilience at Different Level_ MRFI's flexible configuration capabilities enable error injection analysis at various levels, providing robust support for selective fault-tolerant design. In this section, we demonstrate the differences in fault tolerance based on bit, channel and pixel. #### Iv-D1 Bit sensitivity evaluation We inject random errors into each bit of the float16 floating-point type and fixed-point 3.13 quantization type of the VGG-11 model, observing the model's accuracy at different injection rates. Figure 8 illustrates the model accuracy for the high-order bits, while the low-order bits demonstrate greater insensitivity to error injection. In float16, the highest bit represents the sign, followed by 5 exponent bits, and finally 10 mantissa bits. From Figure 8, we observe that high-order exponent bits are highly sensitive to errors, whereas error injection into the mantissa bits does not significantly affect the model's accuracy. The sign bit exhibits a sensitivity level lower than that of high exponent bits but higher than that of low exponent and mantissa bits. For fixed-point 3.13 quantization, a regular pattern emerges in the fault tolerance of each bit, with lower bits consistently displaying better fault tolerance than higher bits. #### Iv-D2 Channel sensitivity evaluation Figure 9 showcases the differences in sensitivity indicators for each channel in the activation values of the first three layers of VGG-11. The three convolutional layers contain 64, 128, and 256 feature map channels, respectively. By employing layerwise quantization parameters, the differences in fault tolerance among different layers are small. After sorting the RMSE indicators for each channel in ascending order, we observe that the variance in channel sensitivity within a layer surpasses the variance in sensitivity between layers. This suggests that selective fault-tolerant design at the channel level can yield enhanced fault tolerance outcomes. #### Iv-D3 Pixel sensitivity evaluation It is also possible to evaluate the pixel sensitivity differences of feature maps at the spatial level. We use MRFI to randomly inject errors into each channel of different pixels with different activation values in the ResNet two layers, resulting in the output RMSE as shown in Figure 10. We can see that pixels in the center position are usually more sensitive to errors, which may be related to the Fig. 5: Visualize of LeNet internal layers and error propagation. Fig. 6: The difference in error sensitivity of quantization methods at different network modules. Fig. 7: Fault tolerance under different quantization scale parameter. dataset features of ImageNet, as most targets are located at the center of the image. ### _Performance_ In addition to accuracy, the performance of error injection and simulation in neural networks is a crucial factor for conducting experiments. MRFI has implemented optimizations in error injection, resulting in comparable time costs between error injection and the golden run. Below, we will refer the state of the art tools PyTorchFI and Ares to conduct two similar experiments and measure the time consumption. PyTorchFI has been optimized for single point error injection, making its overhead negligible compared to forward propagation. However, PyTorchFI does not provide random error generation based on injection rate, so we compared it with the random sampling method used by Ares as the baseline. #### Iv-E1 Single point injection Table II presents the evaluation time for single point injection errors on GPUs and CPUs. It demonstrates that the execution time of the MRFI framework can be disregarded relative to the model's computation. This indicates that although our tool is designed for complex injection configurations, it has also achieved target performance close to PyTorchFI. #### Iv-E2 Injection according to bit error rate For random multi-point injection, Ares conducts acceptance-rejection sampling on each bit, while MRFI uses selectors to choose injection error positions based on the expected number calculated using Equation 1. This reduces the number of random number generations required. However, a discrepancy arises when the injection error rate is low, as \(n_{inject}\) is a discrete integer. To address this issue, MRFI adopts the Poisson sampling strategy described in Equation 2, ensuring consistent results in theory. Figure 11 compares the performance and accuracy between direct probability sampling and optimization methods. While using a selector can significantly reduce the cost of sampling calculations, it may introduce jumps at low injection rates. On the other hand, Poisson sampling maintains consistent results with the baseline sampling methodology. \[n_{inject}=\lfloor N_{neurons}\times BER\rceil \tag{1}\] \[N_{inject}\sim Poisson(N_{neurons}\times BER) \tag{2}\] ## V Conclusion In this paper, we have introduced MRFI, an open-source multi-resolution fault injection framework for neural network processing. MRFI enables refined error assessments, considering the impact of model quantization and supporting fine-grained error injection configurations. To simplify configuration, MRFI decompose complex configuration requirements into multiple modules and offers a user-friendly configuration interface. Our experiments have shown that MRFI can evaluate errors from multiple aspects with practical needs. Fig. 11: Comparison of performance and accuracy of different random sampling methods for random multi-point injection. Fig. 8: Bit sensitivity evaluation of VGG-11 among all layers. Fig. 10: Pixel sensitivity evaluation on two convolution layers of ResNet18 using RMSE metric. Fig. 9: Channel sensitivity evaluation on three convolution layers of VGG-11.
2307.07575
A Quantitative Approach to Predicting Representational Learning and Performance in Neural Networks
A key property of neural networks (both biological and artificial) is how they learn to represent and manipulate input information in order to solve a task. Different types of representations may be suited to different types of tasks, making identifying and understanding learned representations a critical part of understanding and designing useful networks. In this paper, we introduce a new pseudo-kernel based tool for analyzing and predicting learned representations, based only on the initial conditions of the network and the training curriculum. We validate the method on a simple test case, before demonstrating its use on a question about the effects of representational learning on sequential single versus concurrent multitask performance. We show that our method can be used to predict the effects of the scale of weight initialization and training curriculum on representational learning and downstream concurrent multitasking performance.
Ryan Pyle, Sebastian Musslick, Jonathan D. Cohen, Ankit B. Patel
2023-07-14T18:39:04Z
http://arxiv.org/abs/2307.07575v1
# A Quantitative Approach to Predicting Representational Learning and Performance in Neural Networks ###### Abstract A key property of neural networks (both biological and artificial) is how they learn to represent and manipulate input information in order to solve a task. Different types of representations may be suited to different types of tasks, making identifying and understanding learned representations a critical part of understanding and designing useful networks. In this paper, we introduce a new pseudo-kernel based tool for analyzing and predicting learned representations, based only on the initial conditions of the network and the training curriculum. We validate the method on a simple test case, before demonstrating its use on a question about the effects of representational learning on sequential single versus concurrent multitask performance. We show that our method can be used to predict the effects of the scale of weight initialization and training curriculum on representational learning and downstream concurrent multitasking performance. ## 1 Introduction One of, if not the, most fundamental question in neural networks research is how representations are formed through learning. In machine learning, this is important for understanding how to construct systems that learn more efficiently and generalize more effectively (Bengio et al., 2013; Witty et al., 2021). In cognitive science and neuroscience, this is important for understanding how people acquire knowledge (Rumelhart et al., 1993; Rogers and McClelland, 2004; Saxe et al., 2019), and how this impacts the type of processing (e.g., serial and control-dependent vs. parallel and automatic) used in performing task(s) (Musslick and Cohen, 2021; Musslick et al., 2020). One important focus of recent work has been on the kinds of inductive biases that influence how learning impacts representations (e.g., weight initialization, regularization in learning algorithms, etc. (Narkhede et al., 2022; Garg and Liang, 2020)) as well as training curricula (Musslick et al., 2020; Saglietti et al., 2022). This is frequently studied using numerical methods, by implementing various architectural or learning biases and then simulating the systems to examine how these impact representational learning (Caruana, 1997; Musslick et al., 2020). Recently, Sahs et al. (2022) introduced a novel analytic approach to this problem, which can be used to predict important inductive bias properties from the network's initialization. Here we extend this approach by combining it with a neural tangent kernel-based analysis in order to qualitatively predict the kinds of representations that are learned, and the consequences this has for processing. We provide an example that uses a neural network model to address how people acquire simple tasks, and the extent to which this leads to serial, control-dependent versus parallel, automatic processing and multitasking capability (Musslick et al., 2016; Musslick and Cohen, 2021; Musslick et al., 2020). We expand upon theoretical results introduced in Sahs et al. (2022), combining them with a neural tangent kernel analysis (Jacot et al., 2018), which allows for prediction of the inductive bias (and resulting representations learned by the network and downstream task performance) from the initial conditions of the network and the training regime. In the remainder of this section, we provide additional background that motivates the example we use. Then, in the sections that follow, we describe the analysis method, its validation in a benchmark setting, and the results of applying it to a richer and more complex example. _Shared versus separated representations and flexibility versus efficiency._ One of the central findings from machine learning research using neural networks is that cross-task generalization (sometimes referred to as transfer learning) can be improved by manipulations that promote the learning of shared representations--that is, representations that capture statistical structure that is shared across tasks (Caruana, 1997; Baxter, 1995; Collobert and Weston, 2008). One way to do so is through the design of appropriate training regimens and/or learning algorithms (e.g., multi-task learning and/or meta-learning; (Caruana, 1997; Ravi et al., 2020)). Another is through the initialization of network parameters; for example, it is known that small random initial weights help promote the learning of shared structure, by forcing the network to start with what amounts to a common initial representation for all stimuli and tasks and then differentiate the representations required for specific tasks and/or stimuli under the pressure of the loss function (Flesch et al., 2021). Interestingly, while shared representations support better generalization and faster acquisition of novel but similar tasks, this comes at a cost of parallel processing capacity, a less commonly considered property of neural networks that determines how many distinct tasks the system can perform _at the same time_--that is, its capacity for concurrent multitasking (Feng et al., 2014; Musslick et al., 2016; Petri et al., 2021). Note that our use of the term "multitasking" here should not be confused with the term "multitask" learning: the former refers to the simultaneous _performance_ of multiple tasks, while the latter refers to the simultaneous acquisition of multiple tasks. These are in tension: if two tasks share representations, they risk making conflicting use of them if the tasks are performed at the same time (i.e., within a single forward-pass); thus, the representations can be used safely only when the tasks are executed serially. This potential for conflict can be averted if the system uses _separate_ representations for each task, which is less efficient but allows multiple tasks to be performed in parallel. This tension between shared vs. separated representations reflects a more general tradeoff between the _flexibility_ afforded by shared representations (more rapid learning and generalization) but at the expense of serial processing, and the _efficiency_ afforded by separated, task-dedicated representations (parallel processing; i.e., multitasking) but at the costs of slower learning and poorer generalization (i.e., greater rigidity; Musslick and Cohen (2021); Musslick et al. (2020)). While this can be thought of as analogous to the tension between interpreted and compiled procedures in traditional symbolic computing architectures, it has not (yet) been widely considered within the context of neural network architectures in machine learning. _Shared versus separated representations and control-dependent versus automatic processing._ The tension between shared and separated representations also relates to a cornerstone of theory in cognitive science: the classic distinction between control-dependent and automatic processing (Posner and Snyder, 1975; Shiffrin and Schneider, 1977). The former refers to "intentional," "top-down," processes that are assumed to rely on control for execution (such as mental arithmetic, or searching for a novel object in a visual display), while the latter refers to processes that occur with less or no reliance on control (from reflexes, such as scratching an itch, to more sophisticated processes such as recognizing a familiar object or reading a word). A signature characteristic of control-dependent processes is the small number of such tasks that humans can perform at the same time--often only one--in contrast to automatic processes that can be performed in parallel (motor effectors permitting). The serial constraint on control-dependent processing has traditionally been assumed to reflect limitations in the mechanism(s) responsible for control _itself_, akin to the limited capacity imposed by serial processing in the core of a traditional computer (Anderson and Lebiere, 2014; Pashler, 1994; Posner and Snyder, 1975). However, recent neural network modeling work strongly suggests an alternative account: that constraints in control-dependent processing reflect the imposition of serial execution on processes that rely on shared representations (Musslick and Cohen, 2021; Musslick et al., 2020). That is, constraints associated with control-dependent processing reflect the _purpose_ rather than an intrinsic _limitation_ of control mechanisms. This helps explain the association of control with flexibility of processing Cohen (2017); Duncan (2001); Goschke (2000); Kriete et al. (2013); Shiffrin and Schneider (1977); Verguts (2017): flexibility is afforded by shared representations, which require control to insure they are not subject to conflicting use by competing processes. It also explains why automaticity--achieved through the development of task-dedicated representations--takes longer to acquire and leads to less generalizable behavior (Logan, 1997). Together, these explain the canonical trajectory of skill acquisition from dependence on control to automaticity: When people first learn to perform a novel task (e.g., to type, play an instrument, or drive a car) they perform it in a serial, control-dependent manner, that precludes multitasking. Presumably this is because they exploit existing representations that can be "shared" to perform the novel task as soon as possible, but at the expense of dependence on control. However, with extensive practice, they can achieve efficient performance through the development of separated, task-dedicated representations that diminish reliance on control and permit performance in parallel with other tasks (i.e., concurrent multitasking; Garner & Dux (2015); Musslick & Cohen, J. D. (2019)). These ideas have been quantified in mathematical analyses and neural network models, and fit to a wide array of findings from over half a century of cognitive science research (Musslick et al., 2020). However, the specific conditions that predispose to, and regulate the formation of shared versus separated representations are only qualitatively understood, and theoretical work has been restricted largely to numerical analyses of learning and processing in neural network models. Some methods have sought to quantify the degree of representation sharing between two tasks in terms of correlations between activity patterns for individual tasks (Musslick et al., 2016, 2020; Petri et al., 2021; 2021) in order to predict multitasking capability. Other methods, that quantify the representational manifold of task representations (Bernardi et al., 2020) have been applied to characterize multitasking capability (Henselman-Petrusek et al., 2019). However, while these methods provide a snapshot of representation sharing at a given point in training, they do not provide direct or analytic insight into the _dynamics_ of learning shared versus separated representations, nor how the inductive bias of a system may affect the representations learned. In this article, we expand upon the ideas introduced in Sahs et al. (2022) to show how the initial condition of a network and the training regime to which it will be subjected can predict the implicit bias and thus the kinds of representations it will learn (e.g., shared vs. separated) and the corresponding patterns of performance it will exhibit in a given task setting. This offers a new method to analyze how networks can be optimized to regulate the balance between flexibility and efficiency. The latter promises to have relevance both for understanding how this is achieved in the human brain, and for the design of more adaptive artificial agents that can function more effectively in complex and changing environments. _Task structure and network architecture._ For the purposes of illustration and analysis, we focus on feedforward neural networks with three layers of processing units that were trained to perform sets of tasks involving simple stimulus-response mappings. Each network was comprised of an input layer, subdivided into pools of units representing inputs along orthogonal stimulus dimensions (e.g., representing colors, shapes, etc.), and an additional pool used to specify which task to perform. All of the units in the input layer projected to all of the units in the hidden layer, which all projected to all units in the output layer, with an additional projection from the task specification input pool to the output layer. The output layer, like the input layer, was divided into pools of units, in this case representing outputs along orthogonal response dimensions (e.g., representing manual, verbal, etc.). Networks were trained in an environment comprised of several feature groups (e.g., shape, size, etc.) and response groups (e.g., verbal, manual, etc.) corresponding to the stimulus and response dimensions along which the pools of input and output units of the networks were organized. Each network was trained to perform a set of tasks, in which each task was defined by a one-to-one mapping from the inputs in one pool (i.e., along one stimulus feature dimension) to the outputs in a specified pool (i.e., along one response dimension), ignoring inputs along all of the other feature dimensions and requiring null outputs along all of the other response dimensions.1 Training and testing could be performed for one task at a time ("single task" conditions), by specifying only that task in the task input pool and requiring the correct output over the task-relevant response dimension and a null response over all others; or with two or more tasks in combination ("multitasking" conditions), in which the desired tasks were specified over the task input units, and the network was required to generate correct responses over the relevant response dimensions and null responses for all others. In all cases, an input was always provided along every stimulus dimension, and the network had to learn to ignore those that were not relevant for performing the currently specified task(s). In each case, the question of interest was how initialization and learning impacted the final connection weights to and from the hidden layer, the corresponding representations the networks used to perform each task, and the patterns of performance in single task and multitasking conditions. Specifically, we were interested in the extent to which the networks learned shared versus separated representations for sets of tasks that shared a common feature dimension; and the extent to which the analytic methods of interest were able to predict, from the initial conditions and task specifications, the types of representations learned, and the corresponding patterns of performance (e.g., speed of learning and multitasking capability). We evaluated the evolution of representations over the course of learning in two ways: using the analytic techniques of interest, and using a recently developed visualization tool to inspect these, each of which we describe in the two sections that follow. ## 2 Understanding and Visualizing Learning Dynamics ### Analyzing Learning Dynamics Using the Neural Tangent Kernel #### 2.1.1 The Neural Tangent Kernel (NTK) Understanding the learning dynamics of a neural network (NN) can be done using a framework known as the NTK. This is based on a kernel function \(K(x,x^{\prime})\) that represents the'similarity' of inputs \(x\) and \(x^{\prime}\) (from here on, we use \(x\) from the training set and \(x^{\prime}\) from the test set); that is, how much influence each individual sample \(x\) from the training set has on the output decision of the NN on a test sample \(x^{\prime}\). This is embodied in a kernel expansion (Jacot et al., 2018). Using gradient descent (GD) on a NN with scalar learning rate \(\eta\) and a \(P\times 1\) vector of real parameters \(\theta\), the parameter update can be written as \[\theta(t+1)=\theta(t)-\eta\frac{dL(\theta)}{d\theta}.\] Taking the gradient flow approximation \(\eta\to 0\) (e.g. as the step size approaches \(0\), resulting in a continuous flow rather than discrete steps) we have \[\dot{\theta}=-\frac{dL(\theta)}{d\theta}\] Assuming our loss depends only on the network output \(\hat{y}\), we can rewrite this as a sum over \(N\) training samples \(\mathcal{D}:=\{(x_{m},y_{m})\}\): \[\dot{\theta}=-\frac{dL}{d\hat{y}}\frac{d\hat{y}}{d\theta}=\sum_{m\in\mathcal{ D}}\frac{dL}{d\hat{y}_{m}}\frac{d\hat{y}_{m}}{d\theta}:=\sum_{m\in\mathcal{D}} \epsilon_{m}\phi_{m},\] where \(\epsilon_{m}\in\mathbb{R}\) is the loss sensitivity and \(\phi_{m}\) is the \(P\times 1\) vector of NTK features (e.g. \(\frac{d\hat{y}_{m}}{d\theta_{p}}\) for each parameter \(p\)) for sample \(x_{m}\). How does the actual NN prediction function change with learning over time? We can answer this by taking total time derivatives yielding \[\dot{\hat{y}}(\theta)=\frac{d\hat{y}(\theta)}{d\theta}^{T}\dot{\theta}=-\frac {d\hat{y}(\theta)}{d\theta}^{T}\frac{dL(\theta)}{d\hat{y}}\frac{d\hat{y}( \theta)}{d\theta},\] where the kernel function \(K(x,x^{\prime};\theta):=\frac{d\hat{y}(x;\theta)}{d\theta}^{T}\frac{d\hat{y}( x^{\prime};\theta)}{d\theta}\). Note that this means the network's time evolution is a kernel function, made up of the NTK at time \(t\) with parameters \(\theta=\theta(t)\) and kernel weights \(\frac{dL(\theta)}{dy}\) Expanding as a sum over the training set we have \[\dot{\epsilon}_{n}(t)=\sum_{m\in\mathcal{D}}K_{mn}(t)\epsilon_{m}(t),\quad \forall n\in\mathcal{D}\] where we have assumed a mean squared error loss for \(L\), which results in the loss sensitivities becoming the prediction errors \(\epsilon_{m}(t):=\frac{dL(\theta)}{dy}=y_{m}-\hat{y}_{m}(t)\). The coefficients coupling the errors are \(K_{mn}(t):=\phi_{m}(t)\cdot\phi_{n}(t)\), also known as the elements of the \(N\times N\) NTK matrix \(K(t)=[K_{mn}(t)]\). If the model is close to linear in the parameters \(\theta\) (i.e., we are in the so-called _kernel_ or _lazy_ training regime Chizat et al. (2019), where the NN's basis functions are fixed for all time), then the NTK will not change much during training, allowing the entire learning to be readily interpretable as a linear kernel machine (Ortiz-Jimenez et al., 2021). In this case, each update to the model is fully interpretable under kernel theory, with each data point influencing how the model evolves (see Fig. 1). But what if the model is not close to the linear/lazy/kernel regime (i.e., it is in the so-called _adaptive regime_?2 In this case the NN's basis functions do change over time, rendering the NTK function time-dependent (in which case we denote it as \(K(x,x^{\prime},t)\)). Tracking the NTK along the learning trajectory/path of the model parameters \(\theta(t)\) yields the Path-integrated NTK (Domingos, 2020). Footnote 2: All modern NNs perform best in the adaptive regime, and there is a significant performance gap between kernel and adaptive regime models Arora et al. (2019). The power of the adaptive regime is that it allows the NN to learn, based on the data, the basis functions that are most useful. In contrast, the kernel regime has fixed basis functions solely determined by architecture and initialization, with no dependence on the data or the task being learned. #### 2.1.2 Path-Integrated NTK (Pntk) Let the PNTK be denoted by \(P(x,x^{\prime};t)\). Then all NNs trained in a supervised setting with gradient descent result in a (pseudo-)kernel machine3 of the form Figure 1: An explanation of a model update using the NTK. Top Left: The model’s prediction at t = 0, 1, final. Top Right: The kernel function (t=0), or influence on the network due to each data point, tied by color. Bottom Left: The changes due to each influence function (t=0), which are weighted by the loss function. Bottom Right: A comparison between the model’s final state and the prediction made using the NTK update. Note that while this is a one step NTK prediction, if the NTK assumptions (kernel regime) hold the NTK can predict arbitrarily far ahead. Footnote 1: We use the notation of [20] to denote the number of nodes in the network. \[\hat{y}(x)=\sum_{m\in\mathcal{D}}P(x,x_{m})+\hat{y}_{0}(x),\] where the initial predictions \(\hat{y}_{0}(x):=\hat{y}(x,t=0)\) and \(P\) is the PNTK pseudo-kernel of the form (Domingos, 2020): \[P(x,x^{\prime}):=\int_{0}^{t}L^{\prime}(y^{\prime}(x^{\prime}),\hat{y}^{\prime} (x^{\prime},t^{\prime}))\frac{d\hat{y}(x,t^{\prime})}{d\theta}\cdot\frac{d\hat{ y}(x^{\prime},t^{\prime})}{d\theta}dt^{\prime}=\int_{0}^{t}L^{\prime}(y^{ \prime}(x^{\prime}),\hat{y}^{\prime}(x^{\prime},t^{\prime}))K(x,x^{\prime},t )dt^{\prime}\] At intermediate learning times we have \[\hat{y}(x,t)=\hat{y}(x,t=0)-\int_{0}^{t}dt^{\prime}\sum_{m\in\mathcal{D}}L^{ \prime}(y_{m},\hat{y}_{m}(\theta(t^{\prime})))K(x,x_{m};\theta(t^{\prime})),\] where our loss function is \(L\) and the loss sensitivity \(L^{\prime}\) is with respect to the predictions \(\hat{y}\) (e.g. L' = \(\frac{dL}{dy}\)). Thus, the PNTK shows that the NN predictions can be expressed in terms of the NTK, weighted by the loss sensitivity function, along the entire learning path/trajectory. In this article, we use the NTK and PNTK to analyze how representations in the hidden layer of the network evolve during learning of the task(s). The NTK allows a decomposition of the instantaneous changes in the predictions of the NN over training inputs and training time (e.g. how \(\hat{y}\) can be decomposed over \(x_{m}\in\mathcal{D}\) at any point in time), whereas the PNTK provides an integral over those predicted effects over a specified time window (typically from 0 to \(t\)). We can analyze the NTK and PNTK, grouped in various ways (e.g., by input dimensions, tasks, and/or output dimensions) in order to fully characterize how a NN undergoing training acquires representations of the relevant information over the course of learning. ### Visualizing Learning Dynamics Using M-PHATE We used Multislice PHATE (or M-PHATE; Gigante et al. (2019)) to visualize the evolution of representational manifolds over the course of learning. M-PHATE is a dimensionality reduction algorithm for time-series data, that extends the successful PHATE algorithm (Moon et al., 2019) to visualize internal network geometry, and that can be used to capture temporal dynamics. It does so by using longitudinal (time series) data to generate a multislice graph, and then uses PHATE to dimensionally reduce the pairwise affinity similarity kernel of the graph. By applying this to the hidden unit activations of neural networks, it can be used to visualize the representational manifolds over the course of training. Furthermore, by grouping analyses--for example, according to feature dimensions, tasks, or response dimensions--M-PHATE can be used to reveal how representations evolve that are sensitive to these factors. It is important to note that the M-PHATE analysis works by analyzing the _hidden_ layer activities. In contrast, the NTK kernel computes similarities using the whole network's gradients. This means that the results of the two methods are are not directly comparable, but qualitative comparisons can be made. ## 3 Validation of NTK and PNTK Analyses of Learning in Simple Networks We begin with a validation of NTK and PNTK analyses, by using them to predict the evolution of representations in a linear network which are tractable to standard analytic methods, the results of which can be used as a benchmark. Specifically, we use the results from Saxe, McClelland, and Ganguli (henceforth SMG; Saxe et al. (2013)), which show that for a linear NN with a bottleneck hidden layer, the network will learn representations over that layer that correspond to singular values of the weight matrix, in sequence, each learned with a rate proportional to the magnitude of the singular value, up until the dimensionality of the bottleneck layer. Here, we show that NTK and PNTK analyses can be used to qualitatively predict this behavior from the initial conditions of the network (i.e., its initial weights and training set). We take a simple case for illustrative purposes, using a network with an input dimensionality of 4, a bottleneck (hidden layer) dimensionality of 3, and an output dimensionality of 5. A target linear transformation \(W_{target}\) is generated, and then used to generate random training data \(y=W_{target}x\), where \(x\) is randomly drawn from white noise. We call this the SMG task, and replicate their results, showing behavior qualitatively similar to that reported in their previous work (Fig 2). What can a PNTK analysis tell us over and above the original analysis? We consider two approaches to answering this question. The first exploits the fact that we are considering a simple linear system, and thus inputs can be broken down by input dimension. This allows us to compute a PNTK value that predicts how a change in each individual input dimension affects each individual output dimension across examples, which can then be compared to the true \(W_{target}\) (Fig 3). We focus on two time points: \(t=190\), that falls in the middle of the period during which the first singular vector is being acquired; and \(t=770\), that falls in the middle of the period during which the second singular vector is being acquired. The PNTK analysis confirms that the first singular vector of \(W_{target}\) is being learned at \(t=190\), the second is being learned at \(t=770\), and the first singular vector is well learned (e.g. learning acquired is significant) by \(t=190\),4 while both are well learned (e.g. the first is also remembered) by \(t=770\). Footnote 4: What we mean by a singular vector ‘is being learned’ at time t is that it is the top singular vector of the NTK(t), while ‘is well learned’ means that it singular value (of PNTK(t)) is significant (compared to the maximum from \(W\)). This means that a well learned singular vector can also continue to be learned, while a singular vector being learned may or may not be well learned at a particular time. See Fig 6 markers for a visualization relating to this The foregoing analysis, although easy and clear, is limited to linear systems. To assess the applicability of our analyses to non-linear networks, in our second approach we numerically compare the singular vectors of the full NTK and PNTK (at specific time points \(t=190,770\)) against the projections of the data \(x\) into the coordinate system spanned by the singular vectors of \(W_{target}\). This allows us to compare how much each data point contributes to the NTK or PNTK compared to how much it would contribute if it was perfectly learning the modes of \(W_{target}\), an approach that works for linear or nonlinear systems. These results are comparable to those of the analysis of the linear system (Fig 4), providing support for the generality of the NTK and PNTK analyses to non-linear networks. Finally, we conduct another analysis using the PNTK, examining how the learning of each mode changes progressively over time. The PNTK allows us to examine the patterns that are being learned at each time point, by examining the eigenvectors of the NTK. Consistent with the previous work (Saxe et al., 2013), the analysis confirms that eigenvectors are learned one at a time, with larger ones learned first. More interestingly, secondary learning (e.g., the mode that is being acquired at the second fastest rate, and is the second eigenvalue/vector pair of the NTK) reveals relevant patterns, with transitions occurring at times Figure 2: Loss over time in the SMG task for training and testing data (see text for network description). Note the tiered learning, with loss dropping over some regions of time while remaining near constant in others. Figure 3: Differences between SVD singular vectors of \(W_{target}\) compared to NTK and PNTK, at times \(t=190\) and \(770\). At time \(170\), the PNTK (top right) shows that the first singular vector has, for the most part, been learned, though it is still being fine-tuned, as shown by the NTK (top left), prior to learning of the second singular vector. At time \(770\), the NTK (bottom left) shows the second singular vector is being learned (notice we are comparing against the _second_ singular vector of \(W_{target}\)), while the PNTK (bottom right) shows that the first two singular vectors have been incorporated by the model. Figure 4: Comparisons between projections of \(x\) into singular vectors of \(W_{target}\) and singular vectors of NTK and Path NTK at times \(t=190,770\). At time \(170\), the NTK (top left) shows us the first mode is being learned while the Path NTK (top right) shows that the 1st mode has already been well incorporated overall. At time \(770\), the NTK (bottom left) shows the second mode is being learned (notice we are comparing against the _second_ mode of \(W_{target}\)), while the PNTK (bottom right) shows that the first mode is still remembered. dictated by the primary learning switching singular vectors (e.g. when the primary singular vector is learned and switches to learning the second singular vector, the secondary learning switches from learning the second singular vector to learning the third singular vector; Fig 5). These results align with changes in performance of the network. Fig 6 shows the primary learning of eigenvectors and eigenvalues over time along with model performance. This reveals that the two are closely linked, with changes in NTK singular values _anticipating_ model singular vectors aligning with the true task and accompanying decreases in task loss. Figure 5: Match between NTK learning (singular vector 1 - primary, singular vector 2 - secondary) and singular vectors of \(W_{target}\). Primary learning shows a progression, where larger singular values and vectors are learned first, while the secondary learning shows a more intricate pattern with switches tied to the primary learning. In summary, the PNTK analysis is consistent with the results reported by SMG for a linear network, using a technique that is extendable to non-linear networks. It is important to emphasize that the PNTK analysis is _predictive_, in that the results are derived only from the conditions of the network at the time point to which the analysis is applied, but predict the representational organization of the network following subsequent learning given the training regime. Of course, the SMG theory was also predictive, but only works in the linear regime--the PNTK can readily be expanded to nonlinear applications. It also reveals interesting new patterns, particularly in the secondary learning dynamics of the network, implying that some groundwork for learning higher modes is in place before their primary learning begins. ## 4 Application of NTK and PNTK Analyses to Learning and Performance in Nonlinear Networks In the preceding section, we validated the use of NTK and PNTK analyses of learning dynamics in simple networks. Here, we explore using this technique to examine representational learning and its relationship to network performance in a more complex nonlinear network, that addresses how initial conditions influence the development of shared versus separated representations and its impact on parallel task execution (i.e., concurrent multitasking). ### Model #### 4.1.1 Network Architecture The network used for all further experiments is shown in Fig. 7 (cf. Musslick et al. (2020)). It had two sets of input units: a stimulus set, \(x_{1}\), used to represent stimulus features; and a task set, \(x_{2}\), used to indicate which task(s) should be performed on a given trial. The stimulus set was further divided into \(g_{1}\) pools of units, each of which was used to represent an independent stimulus dimension comprised of \(m\) features along each dimension. Accordingly, each pool was comprised of \(m\) units, with each feature represented as a one-hot input pattern over the group. The task set was comprised of single pool with a number of units equal to the number of tasks that could be specified (see below), and one unit used to represent each task. Both sets of input units projected to a single set of hidden units, with connection weights \(w_{1}\) and \(w_{2}\) for the stimulus set and task set, respectively. The H units in the hidden layer used a sigmoidal activation function \(\phi\), producing an activation vector of \[h=\phi(w_{1}x_{1}+w_{2}x_{2}+b_{1})\] where \(b_{1}=-2\) is a fixed bias, ensuring that the units were inhibited if no input is was provided (see Section 4.1.3). All of the hidden units, as well as the input units in the task set, projected to all of units in the Figure 6: Comparison between NTK learning and model loss. Left: Loss vs Overlap between NTK singular vectors and \(W_{target}\) singular vectors. Right: Loss vs PNTK singular values. Dotted lines show the location of \(t=190,770\), which are the two points used for further analysis above. output layer, with weights \(v_{1}\) and \(v_{2}\), respectively. The output layer, like the stimulus set of the input layer, was divided into \(g_{2}\) pools of units, each of which was used to represent an independent response dimension comprised of \(m\) responses along each dimension. Thus, each pool was comprised of \(m\) units with each response represented as a one-hot input pattern over the set. Like the hidden layer, the output layer used a sigmoidal activation function \(\phi\), along with output bias \(b_{2}=b_{1}\), leading to a final output of \[y=\phi(v_{1}h+v_{2}x_{2}+b_{2})\] or, in terms of inputs only \[y=\phi(v_{1}\phi(w_{1}x_{1}+w_{2}x_{2}+b_{1})+v_{2}x_{2}+b_{2})\] Note that task input \(x_{2}\) appears twice here, as there are two independent pathways involving \(x_{2}\) (one projecting to the hidden layer and the other to the output layer). #### 4.1.2 Task Environment As described above, a task was defined as a one-to-one mapping from the features along a single stimulus dimension to the responses of a single output dimension, reflecting response mappings in classic multitasking paradigms (e.g., Pashler 1994). This corresponded to the mapping of the \(m\) input units from the specified pool \(g_{1}\) of the stimulus group \(x_{1}\) to the associated \(m\) output unit in the specified pool \(g_{2}\) of the output units. In aggregate, this yielded \(g_{1}\cdot g_{2}\) tasks, and thus the task set \(x_{2}\) had that many units. For a given trial, a single feature unit was activated in each pool of the stimulus set \(x_{1}\) (i.e., each of the \(g_{1}\) input pools had one of its \(m\) units activated). For performance of a single task, only a single unit was activated in the task set \(x_{2}\). The network was then required to activate the output unit in the response pool corresponding to the input unit activated in the stimulus pool specified by the task unit activated in \(x_{2}\), and to suppress activity of all other output units. For example, task 1 consisted of mapping the \(m\) units of input pool \(g_{1}=1\) to the \(m\) units of the output pool \(g_{2}=1\); as only one one of the \(m\) units was active, the task consisted of mapping the active \(m\)th element of \(g_{1}\) to the m\(th\) element of \(g_{2}\), while outputting null responses elsewhere. For multitasking performance, two or more units in the task set were activated, and the network was required to activate the response corresponding to the input for each task specified, and suppress all other output units. Multitasking was restricted to only those tasks that shared neither an input set nor output set (see Lesnick et al. (2020) for a more detailed consideration of "legal multitasking"). Figure 7: Network architecture and task environment. (A) Network: The input layer is partitioned into two sets, \(x_{1}\) for stimulus inputs and \(x_{2}\) for specification of task(s) to be performed. The stimulus set is further partitioned into four pools, each representing a stimulus dimension comprised of \(m=3\) feature units. Both input groups project to the hidden layer, comprised of \(H=200\) non-linear processing units. Both the hidden and task input units project to the output layer. The output layer is comprised of three pools of non-linear processing units, each representing a response dimension comprised of \(m=3\) response units. (B) Task: black lines show the mappings from each stimulus pool to each response pool that make up the twelve tasks on which the network was trained. Each line represents a one-to-one-mapping that the network had to learn, associating each feature within a given stimulus pool to a corresponding response in the output pool for a given task. We report results for a network that implemented four stimulus dimensions and three response dimensions (i.e., stimulus pools \(g_{1}=4\) and output pools \(g_{2}=3\)).5 This yielded a total of 12 tasks (\(x_{2}=12\)). Since each stimulus dimension had three features, and each response dimension had three possible responses (i.e., \(m=3\)), in total the network had 24 input units (\(x_{1}=12\) stimulus input, and \(x_{2}=12\) task input units) and 12 output units, as well as \(H=200\) hidden units.6 Footnote 5: We chose a different number of stimulus and response pools to be able to distinguish partitioning of the hidden unit representations according to input versus output dimensions, or both. Footnote 6: The number of hidden units was chosen to avoid imposing a representational bottleneck on the network, thus allowing it the opportunity to learn separate representations for the mappings of each of the twelve tasks. This was done to insure that any tendencies for the network to learn lower dimensional representation were more likely to reflect factors of interest (viz., initialization and/or training protocols) and could not be attributed to limited representational resources. #### 4.1.3 Initialization and Training In the experiments, we manipulated the initialization of all connection weights between a _standard initialization_ condition (random uniform distribution in [-1,.1]) and a _large initialization_ condition (random uniform distribution in [-1, 1]). All biases were set to \(b_{i}=-2\) to encourage learning of an attentional scheme over the task weights in which activation of a task input unit placed processing units to which it projected in the hidden and output layers in a more sensitive range of their nonlinear processing functions 7. No layer-specific normalization (e.g., by batch) was used. For all experiments, networks tasks were always sampled uniformly from all available tasks. However, in each we manipulated whether training was restricted to performance of only one task at a time (_single task_ condition) or required performance of multiple tasks simultaneously (_multitasking_ condition), as described in the individual experiments below. In all cases, the network was trained with stochastic gradient descent (SGD) using a base learning rate of.01 for 10000 epochs, with parameters found via hyper-parameter search.8 Footnote 7: This exploits the nonlinearity of the activation functions to implement a form of multiplicative gating without the need for any additional specialized attentional mechanisms; see Cohen et al. (1990); Musslick et al. (2020) for relevant discussions). Footnote 8: As the PNTK analyzes a specific network instantiation, all NTK-based and MPHATE-based visualizations (except where otherwise noted) are based on one trial. We re-ran each experiment at least five times to confirm that there were no major qualitative changes in the results and to generate correlation metrics over multiple experiments. Experimental results are averaged over 10 trials ### Predicting Impact of Standard vs. Large Initialization on Representational Learning #### 4.2.1 Effect of Initialization on Representational Learning It has previously been observed that lower initial weights promote the formation of representational sharing among tasks that share the same input and/or output dimensions (Flesch et al., 2021; Musslick et al., 2017; 2020), consistent with other findings from work in machine learning (Sahs et al., 2022; Ding et al., 2014). Here, we sought first to validate this finding in the present architecture, and visualize it using M-PHATE, and then evaluate the extent to which it could be predicted by the PNTK analysis. To do so, we compared the standard initialization with the large initialization under the single task training condition. Fig 8 shows an M-PHATE plot of how the patterns of activity over the hidden units evolve over the course of training. The top row shows this for the standard initialization condition, with each panel showing the patterns of hidden unit activity grouped (averaged) along different dimensions. There is clear structure in the groupings, which reflects the sharing of representations for tasks that use the same inputs or outputs. For example, grouped by task (the leftmost panel), there are four clusters of three tasks each, with each cluster comprised of tasks that share the same inputs, confirmed by examining the individual elements. Similarly, grouped by input (the second panel from the left) there are three clusters of four tasks each ), with each cluster corresponding to within-group position across the four pools. Notice that the grouping here gradually decoheres over time (as the clusters are transient, we show a zoomed in inset showing this phenomenon in Fig 8 (inset). Finally, grouped by output (the rightmost panel), there are three clusters of tasks that share the same output. Both effects can be seen in the _Task by Inputs_ grouping (third panel from the left), in which three clusters appear early in training (dark dots), each of which is comprised of tasks Figure 8: M-PHATE visualization of hidden unit activity in the network over course of training. Dots correspond to the relative positions of the patterns of hidden unit activities (each averaged over all input stimuli that share the same feature by which they are grouped, as explained below) at each epoch in training (darker colors represent earlier epochs in training and lighter colors later epochs; see legend to the right), with blue lines showing connections across time. Plots in the top row show standard initialization condition, and in the bottom row large initialization condition. Plots in each column show hidden unit activities grouped (averaged) along dimensions indicated by the label (e.g., in the leftmost column, labelled _Task_, hidden unit activations are grouped by task, with each dot corresponding to the average pattern of hidden unit activity over all inputs for a given task). Notice that, in all cases, in the standard initialization condition (top row) hidden unit representations exhibit highly organized structure, whereas in the large initialization (bottom row) they exhibit substantially less structure (see text for additional discussion). Inset shows M-PHATE visualization of hidden unit activity in the network with the standard initialization at t = 3 for the grouped by inputs configuration. This zoomed in view shows the transient clustering into 3 groups of 4, which collapses over time. that share the same output, followed later (lighter dots) by a separation into subclusters of tasks that share the same inputs. The early organization by outputs followed later with organization by inputs is consistent with the tendency, in multilayered networks without layer-specific weight normalization, for weights closest to the output layer to experience the steepest initial gradients and therefore the earliest effects of learning.9 These observations corroborate the general principle that lower initial weights promote representational sharing in environments for which tasks share structure. Footnote 9: To confirm this account, and rule out the possibility that early organization by outputs was because the lower dimensional structure of the outputs (three dimensions) made it easier to learn than the input structure (four dimensions), we conducted the same experiment on a network that had fewer input dimensions (three) than output dimensions (four), and observed similar results (see Appendix, Section A.3.1). The lower panels in Fig 8 show the results for the large initialization condition. These are in stark contrast to those for the standard initialization condition, showing little if any structure: each task develops its own representations that are roughly equidistant from the others, irrespective of shared inputs and/or outputs. The one deviation from this pattern is for grouping by output (rightmost panel), in which three clusters emerge, once again presumably reflecting the early and strong influence of the gradients on weights closest to the output of a multilayered network in the absence of any layer-specific form of weight normalization. Together, the observations above provide strong confirmation that, in this network architecture as in many others, lower initial weights promote the development of shared representations for tasks that share structure (i.e., input or output dimensions), and showcase the utility of M-PHATE for clearly and concisely visualizing such qualitative effects. In the sections that follow, we apply NTK analyses to show that downstream performance can be predicted quantitatively from the initial conditions. #### 4.2.2 Use of NTK to Predict Representational Learning First, we conduct an NTK analysis of the standard initialization network, following initialization but prior to training (i.e., \(T=0\)), to assess whether this can anticipate the effects of learning. The output of the NTK analysis is a 500x500 matrix, corresponding to the 500 training inputs across all tasks. The M-PHATE observations shown in Fig 8 suggest that, over the course of training, the representations learned by the network's hidden units came to be clustered according to both the four input dimensions (shared across tasks) and their mapping to each of the three output dimensions (according to task). To determine whether this organization was predicted by, and can be observed in the NTK analysis, we carried out two variants of this analysis: one in which individual training passes were sorted by the current input (aggregated over tasks), and the other sorted by task (aggregated over inputs). In both cases, the NTK analysis is calculated per output, yielding a total of nine NTK analyses (three units \(m\) per output set \(g\)). For comparison, we also carried out the NTK analysis without sorting. In contrast to the sorted analyses (shown in Fig 9), the unsorted analyses did not reveal any discernible structure (see Fig 12 in Appendix). Fig 9 shows the results of the NTK analyses for the primary eigenvector (i.e., the one with the largest eigenvalue) in the standard initialization and high initialization condition at \(T=0\), sorted as described above. These reveal clustering effects in the standard initialization that correspond closely to those that emerged in the hidden units over training, as observed in the M-PHATE plots in Fig 8. Each plot shows the weighting for each training pattern on the eigenvector. When these are sorted by input features (left panels), the pattern of weightings for a given response (\(m\)) is the same across output pools (\(g_{2}\)) in the standard init case, consistent with the use of the same input representations across all three tasks. Complementing this, when training patterns are sorted by task (right panels), the pattern of weightings for a given response is different for each output pool in the standard init case, indicating the role of the task units in selecting which of the four input dimensions should be mapped to that output pool for each given task. Critically, this structure within the standard init is visible in the NTK analysis _prior to training_ (i.e., at \(T=0\)) in the standard initialization condition but _not_ the large initialization condition. Further details of other secondary analysis are provided in the Appendix. In the standard-initialization condition, structure is visible in the NTK analysis before any training occurs. This raises the question: to what extent is this specifically predictive of the effects that emerge during Figure 9: First eigenvector of the NTK analysis for the output units prior to training, showing the 1st eigenvector over each training input for each output unit, with each plot’s input indices (x-axis) ordered either by the relevant task (sorted by inputs; left panels) or by relevant input (sorted by tasks, right panels), across both the standard initialization (top panels) and large initialization (bottom panels). The 9 plots within each panel are organized by output pool \(g_{2}\) and response unit \(m\) within each pool. Notice the strong clustering in _both_ standard init cases (see text for interpretation), but neither of the large init cases. training? To address this, we analyzed the extent to which the groupings from the initial NTK analysis predicted the structure observed in the M-PHATE hidden representations over the course of training (that is, the extent to which the NTK analysis conducted at \(T=0\), integrating only the first time step, predicted M-PHATE clustering for t\(>\)0). For the NTK analysis grouped by input, the NTK groups code for subgroup position within each task, as seen in Fig 9. This can easily be expressed by the M-PHATE grouping as well. For the NTK analysis grouped by task, the grouping clearly aligns with the output pool relevant for each task, as seen in Fig 9. However, as previously discussed, the M-PHATE analysis uses the hidden layer activations, and thus cannot include output dimension information. Instead, we predict that the M-PHATE analogously uses the relevant input pool. Based on these grouping schemes, we can test the extent to which the organization predicted from the NTK plots prior to training (at \(T=0\)) predict the patterns of clustering that emerge in the M-PHATE plot at different points during training (\(T\)\(>\)=1). We measured the correspondence between these measures using the Adjusted Rand distance metric for between group memberships, as shown in Fig 10. The results indicate that PNTK accurately predicts M-PHATE structure when examined both by task and inputs. The task-grouped predictions reach a complete match in grouping by the end of training. The input-grouped predictions also align cleanly with the trajectory of representational structure in the M-PHATE analysis, reaching a prefect match in grouping early in training when structure is clearly observed in the M-PHATE analyses, followed by a diminution of the effect that parallels the dissolution of structure observed in the M-PHATE analyses. ## 5 Predicting the Effect of Initialization and Training Curriculum on Processing The results reported above affirm the usefulness of the NTK and PNTK analyses in predicting representational learning, both in linear and non-linear networks. They also reaffirm the premise that initialization with small random weights favors representational sharing among tasks that share common structure (e.g., input and/or output dimensions). In this section, we report a further evaluation this effect, and the ability of the NTK and PNTK analyses to predict not only the effects of initialization on representational learning, but also on performance. Specifically, building on previous work (Musslick et al., 2016; Musslick and Cohen, 2021), we tested the hypotheses that: i) insofar as the standard initialization condition favors representational sharing, it should be associated with faster learning of new single tasks (due to more effective generalization), but at the cost a compromised ability to acquire parallel processing capacity (i.e., poorer concurrent multitasking capability) relative to the large initialization condition; and ii) this can be predicted Figure 10: Overlap between groups predicted from PNTK (at \(t=0\)) and groups observed from M-PHATE analysis (input and task) across time (mean Adjusted Rand metric \(\pm\) s.d. across trials; see text for details of analysis). The PNTK predictions for both groups are accurate, although the input-grouped M-PHATE only aligns during the earlier stages of training. from the NTK analysis at the start of training.10 To test this, we evaluated the acquisition of multitasking performance via fine tuning of networks first trained on single task performance in each of the two initialization conditions. For each comparison, we generated two networks from the same random initialization, with the large initialization having layer 1 weights that were uniformly multiplied up by a factor of 10. We posited that although a neural network trained in the large initialization condition (and therefore biased to learn separated representations) would take longer to learn during initial single task training, it would be faster to acquire the capacity for concurrent multitasking during subsequent fine tuning on that ability, as compared to a network trained in the standard initialization condition (and hence biased to learn shared representation). Critically, we also tested the extent to which the NTK and PNTK analyses, carried out on the network _before_ initial single task training, could accurately predict end of training generalization loss and even the impact of fine tuning on concurrent multitasking performance that occurred _after_ the initial training. Footnote 10: While it is plausible that this should be the case, given that NTK and PNTK predict patterns of representational learning and the latter determine performance, nevertheless since neither of these relationships is perfect, it is possible that NTK and/or PNTK predict a different component of the variance in representational learning than is responsible for performance. ### Effects of Initialization on Acquisition of Multitasking Capability To test the hypotheses outlined above, we first trained networks on single task performance in the standard and large initialization conditions. We then followed this with "fine-tuning" of each resulting network on concurrent multitasking, using the same number of training examples and epochs in each case. Specifically, we trained each network to simultaneously execute, with equal probability, either 1, 2, or 3 tasks, randomly sampled from all valid combinations (e.g. non-overlapping inputs or outputs) of the selected number of tasks. Fig 11 shows the results for networks in the standard and large initialization conditions, both during initial single task training (left panels) and during subsequent fine tuning on concurrent multitasking performance (right panels). The upper panels show a direct comparison of the mean and standard deviation of generalization losses. While the basic effects are observed here, overall performance varied across different pairs of networks, as a function of the particular _pattern_ of initial weights assigned to them (which was the same for each pair, and simply scaled differently for the standard and large initialization conditions). The lower panels of Fig 11 show the mean of direct comparisons between each pair of networks, that controls for differences in overall performance across the pairs. As predicted (and consistent with previous results (Flesch et al., 2021; Musslick et al., 2017; 2020), the standard initialization condition led to better generalization performance over the course of single task training, due to the development of shared representations (see Fig 8, upper panels). However, those presented an obstacle to the subsequent acquisition of concurrent multitasking performance, presumably because separated (task dedicated) representations had to now be learned _de novo_. Conversely, networks in the large initialization condition exhibited poorer overall generalization performance during single task training, due to a bias toward the learning of more separated representations (as predicted by the PNTK analyses; see Fig 8, lower panels), but it was better predisposed for the subsequent acquisition of concurrent multitasking performance, as is clearly observed in the right panel of Fig 11. ### Predicting performance from the PNTK analysis Next, we tested the extent to which an PNTK analysis applied to the network prior to initial single task training could predict performance during subsequent multitask tuning. To do so, we: i) created ten pairs of networks, each with a different set of weights generated for the standard and large initialization conditions (as described above; ii) applied k-means clustering with 12 groups to the multidimensional PNTK analysis of each network prior to training; and iii) quantified the clustering quality using the silhouette method (Baarsch and Celebi, 2012), with a higher value reflecting a greater degree of sharing among representations. We then trained each network using the procedure describe above, initially on single tasks, and then on multitask fine tuning. Finally, for each pair of networks, we correlated the silhouette score for the network in each condition with the difference in generalization performance between the two conditions (standard - large initialization) at the end of each training phase. If representational structure predicted by the PNTK analyses was responsible for generalization performance after each phase of training, then the correlations should be negative following single-task and positive following multitask fine tuning. This is because the standard Figure 11: Top: Generalization performance (mean loss \(\pm\) s.d. across trials) during single task training in the standard and large initialization conditions (left), followed by fine tuning in multitasking in each condition (right). Bottom: Difference in generalization performance (mean[loss of large initialization loss of standard initialization] \(\pm\) s.d. across trials) during single task training (left), followed by fine tuning on current multitasking (right). During single task training, while the large initialization shows faster initial improvements in performance, it is quickly overtaken by the standard initialization condition. However, during subsequent fine tuning on concurrent multitasking, the large initialization condition shows a clear and sustained advantage. initialization should generate higher silhouette scores (more shared representations) and correspondingly lower test loss relative to the large initialization condition after single task training (hence the negative correlation), but higher relative test loss following multitask fine tuning (hence the positive correlation); and, conversely, the large initialization should generate lower silhouette scores (more separated representations) and correspondingly higher test loss relative to the standard initialization condition after single task training (and thus, again, a negative correlation), but lower relative test loss following multitask fine tuning (again a positive correlation). The results are consistent with these predictions: the correlation was \(r=-.881\) following single task training, and \(r=.973\) following multitask fine tuning. This suggests that the PNTK analysis, carried out _prior to any training_, was able to reliably predict theoretically anticipated effects of initialization on generalization performance in the network observed after two distinct phases of training. This not only confirms that the PNTK analysis, carried out _prior to any training_, is able to predict the kinds of representations learned by the network in response to different initializations, but also that it can be used to predict the patterns of generalization performance associated with those representations observed in the network after two distinct phases of training. ## 6 Discussion and Conclusions In this article, we show how a novel analysis method that examines the gradients of the network at the outset of training (determined by its initial weights and training curriculum), can be used to predict features of the representations that are subsequently learned through training, as well as the impact these have on network performance. Specifically, we show that NTK and PNTK analyses predict the extent to which a standard initialization scheme (small random weights) biases learning toward a generalizable code that groups similar inputs together (i.e., using shared representations), whereas large weight initialization predisposes the network to learn distinct representations for each task configuration (i.e., separated representations). We also confirm that, whereas the bias toward shared representations leads to improved generalization performance in the single task setting, this leads to destructive interference that impairs multitasking performance when more than one task is performed concurrently. Conversely, the large initialization scheme favors the formation of distinct task-specific representations, that facilitates the acquisition of multitasking capability. Importantly, we show that these effects (i.e., the eventual task or input groupings) can be predicted from the NTK eigenvectors as early as the first iteration of training, indicating that the types of representation that will be learned and their consequences on performance can be characterized before training has begun. Here, we focused on relatively simple networks, tasks, and training regimes. Evaluating the extent to which our results extend to more complex network architectures, tasks and forms of training remains an important direction for future research. We expect that this technique may be a fruitful way to advance the probing and understanding of inductive biases that influence the learning and use of representations in neural networks (Woodworth et al., 2020; Goyal & Bengio, 2022). This, in turn, may help lay the foundation for a better understanding of the respective costs and benefits of representation sharing in both biological and artificial neural network architectures. The work presented here, and previous theoretical work on which it builds Feng et al. (2014); Musslick et al. (2020), suggests that sharing representations between tasks limits a network's capacity for multitasking. This has received empirical support in neuroscientific research. For example, neuroimaging studies have provided evidence that the multitasking capability of human participants is inversely related to representational overlap between tasks (Nijboer et al., 2014), and that improvements in multitasking capability are accompanied by increases in representational separation Garner and Dux (2015). The present work may aid in the development of methods that allow neuroscientists to predict the learning of shared versus separate representations before they occur. Such methods would open new paths for the quantification of individual differences or the effective evaluation of training procedures for human multitasking. Along similar lines, the work presented here may help inform the design more effective artificial systems, by providing an efficient means of predicting the impact that initial conditions and training curriculum will have on downstream parallelization of performance.
2305.10664
Posterior Inference on Shallow Infinitely Wide Bayesian Neural Networks under Weights with Unbounded Variance
From the classical and influential works of Neal (1996), it is known that the infinite width scaling limit of a Bayesian neural network with one hidden layer is a Gaussian process, when the network weights have bounded prior variance. Neal's result has been extended to networks with multiple hidden layers and to convolutional neural networks, also with Gaussian process scaling limits. The tractable properties of Gaussian processes then allow straightforward posterior inference and uncertainty quantification, considerably simplifying the study of the limit process compared to a network of finite width. Neural network weights with unbounded variance, however, pose unique challenges. In this case, the classical central limit theorem breaks down and it is well known that the scaling limit is an $\alpha$-stable process under suitable conditions. However, current literature is primarily limited to forward simulations under these processes and the problem of posterior inference under such a scaling limit remains largely unaddressed, unlike in the Gaussian process case. To this end, our contribution is an interpretable and computationally efficient procedure for posterior inference, using a conditionally Gaussian representation, that then allows full use of the Gaussian process machinery for tractable posterior inference and uncertainty quantification in the non-Gaussian regime.
Jorge Loría, Anindya Bhadra
2023-05-18T02:55:00Z
http://arxiv.org/abs/2305.10664v3
Posterior Inference on Infinitely Wide Bayesian Neural Networks under Weights with Unbounded Variance ###### Abstract From the classical and influential works of Neal (1996), it is known that the infinite width scaling limit of a Bayesian neural network with one hidden layer is a Gaussian process, _when the network weights have bounded prior variance_. Neal's result has been extended to networks with multiple hidden layers and to convolutional neural networks, also with Gaussian process scaling limits. The tractable properties of Gaussian processes then allow straightforward posterior inference and uncertainty quantification, considerably simplifying the study of the limit process compared to a network of finite width. Neural network weights with unbounded variance, however, pose unique challenges. In this case, the classical central limit theorem breaks down and it is well known that the scaling limit is an \(\alpha\)-stable process under suitable conditions. However, current literature is primarily limited to forward simulations under these processes and the problem of posterior inference under such a scaling limit remains largely unaddressed, unlike in the Gaussian process case. To this end, our contribution is an interpretable and computationally efficient procedure for posterior inference, using a _conditionally Gaussian_ representation, that then allows full use of the Gaussian process machinery for tractable posterior inference and uncertainty quantification in the non-Gaussian regime. ## 1 Introduction Gaussian processes (GPs) have been studied as the infinite width limit of Bayesian neural networks with priors on network weights that have finite variance (Neal, 1996). This presents some key advantages over Bayesian neural networks with finite widths that usually require computation intensive Markov chain Monte Carlo (MCMC) posterior calculations (Neal, 1996) or variational approximations (Goodfellow et al., 2016, Chapter 19); in contrast to straightforward posterior inference and probabilistic uncertainty quantification afforded by the GP machinery (Williams and Rasmussen, 2006). In this sense, the work of Neal (1996) is foundational. The technical reason for this convergence to a GP is due to an application of the central limit theorem under the bounded second moment condition. More specifically, given an \(I\) dimensional input \(\mathbf{x}\) and a one-dimensional output \(y(\mathbf{x})\), a \(K\) layer feedforward deep neural network (DNN) with \(K-1\) hidden layers is defined by the recursion: \[z_{j}^{(l+1)}(\mathbf{x}) =g\left(b_{j}^{(l)}+\sum_{i=1}^{p_{l}}w_{ij}^{(l)}z_{i}^{(l)}( \mathbf{x})\right),\quad l=1,\ldots,K-1, \tag{1}\] \[y(\mathbf{x}) =\sum_{j=1}^{p_{K}}w_{j}^{(K)}z_{j}^{(K)}(\mathbf{x}), \tag{2}\] where \(z^{(1)}\equiv\mathbf{x},\ p_{1}=I,\ p_{K}=D\) and \(g(\cdot)\) is a nonlinear activation function. Thus, the network repeatedly applies a linear transformation to the inputs at each layer, before passing it through a nonlinear activation function. Sometimes a nonlinear transformation is also applied to the final hidden layer to the output layer, but in this paper it is assumed the output is a linear function of the last hidden layer. Neal (1996) considers the case of a Bayesian neural network with a single hidden layer, i.e., \(K=2\). So long as the hidden to output weights \(w^{(2)}\) are independent and identically distributed Gaussian, or at least, have a common bounded variance given by \(c/p_{2}\) for some \(c>0\), and \(g(\cdot)\) is bounded, an application of the classical central limit theorem shows the network converges to a GP as the number of hidden nodes \(p_{2}\rightarrow\infty\). Recently, Neal's result has been extended to prove fully connected multi-layer feedforward networks (Lee et al., 2018) and convolutional neural networks (Garriga-Alonso et al., 2019) also converge to GPs. This is useful for uncertainty quantification by designing emulators for deep neural networks (DNNs) based on GPs, since the behavior of finite-dimensional DNNs for direct uncertainty quantification is much harder to characterize. In contrast, once a convergence to GP can be ensured, well established tools from the GP literature (see, e.g., Williams and Rasmussen, 2006) can be brought to the fore to allow straightforward posterior inference. The induced covariance function depends on the choice of the nonlinear activation function \(g(\cdot)\), and is in general anisotropic. However, it can be worked out in explicit form under a variety of activation functions for both shallow (Neal, 1996; Cho and Saul, 2009) and deep (Lee et al., 2018) feedforward neural networks, where for deep networks usually a recursive formula is available that expresses the covariance function of a given layer conditional on the layer just below it. The benefit of depth is that it allows a potentially very rich covariance function at the level of the observed data, even if the covariances in each layer conditional on the layer below are simple. Viewing a GP as a prior on the function space, this allows for a rich class of prior structures. However, the process is still Gaussian in all these cases and our intention in this paper is a departure from the Gaussian world. ### Challenges posed by network weights with unbounded prior variance Although the GP literature has been immensely influential for uncertainty quantification in DNNs, it is obvious that a DNN does not converge to a GP if the final hidden to output layer weights are allowed to have unbounded variance, e.g., belonging to \(t\) or others in the stable family, such that the scaling limit distribution is non-Gaussian (Gnedenko and Kolmogorov, 1954). This was already observed by Neal (1996) who admits: _"in contrast to the situation for Gaussian process priors, whose properties are captured by their covariance functions, I know of no simple way to characterize the distributions over functions produced by the priors based on non-Gaussian stable distributions."_ Faced with this difficulty, Neal (1996) confines himself to forward simulations from DNNs with \(t\) weights, and yet, observes that the network realizations under these weights demonstrate very different behavior (e.g., large jumps) compared to normal priors on the weights. This is not surprising, since Gaussian processes, with their almost surely continuous sample paths, are not necessarily good candidate models for functions containing sharp jumps, perhaps explaining their lack of popularity in certain application domains, e.g., finance, where jumps and changepoints need to be modeled (see, e.g., Chapter 7 of Cont and Tankov, 2004). Another key benefit of priors with polynomial tails, pointed out by Neal (1996), is that it allows a few hidden nodes to make a large contribution to the output, while drowning out the others, akin to feature selection. In contrast, in the GP limit, the contributions of individual nodes are averaged out. Thus, there are clear motivations for developing computationally feasible posterior inference machinery under these non-Gaussian limits. Neal (1996) further hints that it may be possible to prove an analogous result using priors that do not have finite variance. Specifically, suppose the network weights are given symmetric \(\alpha\)-stable priors. If \(X\) is an \(\alpha\)-stable random variable, the density does not in general have a closed form, but the characteristic function is \(\phi_{X}(t)=\exp[it\mu-\nu^{\alpha}|t|^{\alpha}\{1-i\beta\text{sign}(t)\omega(t; \alpha)\}]\), where \(\omega(t;\alpha)=\tan(\alpha\pi/2)\), for \(\alpha\neq 1\) and \(\omega(t;\alpha)=-(2/\pi)\log[t]\), for \(\alpha=1\). Here \(\mu\in\mathbb{R}\) is called the shift parameter, \(\alpha\in(0,2]\) is the index parameter, \(\beta\in[-1,1]\) is the symmetry parameter, and \(\nu>0\) is the scale parameter (Samorodnitsky and Taqu, 1994, p. 5). Throughout, we use a zero shift (\(\mu=0\)) stable variable, and denote it by \(X\sim S(\alpha,\beta,\nu)\). Here \(\beta=0\) corresponds to the symmetric case, and when \(\beta=1,\alpha<1,\nu=1\), the random variable is strictly positive, which we denote by \(S^{+}(\alpha)\). Der and Lee (2005) confirm Neal's conjecture by establishing that the scaling limit of a shallow neural network under \(\alpha\)-stable priors on the weights is an \(\alpha\)-stable process. Proceeding further, Peluchetti et al. (2020) show that the limit process for infinitely wide DNNs with infinite-variance priors is also an \(\alpha\)-stable processes. However, both Der and Lee (2005) and Peluchetti et al. (2020) only consider the forward process and neither considers posterior inference. Inference using \(\alpha\)-stable densities is not straightforward, and some relevant studies are by Samorodnitsky and Taqqu (1994), Lemke et al. (2015), and more recently by Nolan (2020). The main challenge is that a covariance function is not necessarily defined, precluding posterior inference analogous to the GP case, for example, using the _kriging_(Stein, 1999) machinery. To this end, our contribution lies in using a representation of the characteristic function of symmetric \(\alpha\)-stable variables as a normal scale mixture, that then allows a _conditionally Gaussian_ representation. This makes it possible to develop posterior inference and prediction techniques under stable priors on network weights using a latent Gaussian framework. ### Summary of main contributions Our main contributions consist of: 1. An explicit characterization of the posterior predictive density function under infinite width scaling limits for shallow (one hidden layer) Bayesian neural networks under stable priors on the network weights, using a conditionally Gaussian representation. 2. An MCMC algorithm for posterior inference and prediction, with publicly available code. 3. Numerical experiments in one and two dimensions that validate our procedure by obtaining better posterior predictive properties for functions with jumps and discontinuities, compared to both Gaussian processes and Bayesian neural networks of finite width. 4. A real world application to the air quality data in the city of York, where our results show a smaller prediction error in out-of-sample observations. ## 2 Infinite width limits of Bayesian neural networks under weights with unbounded variance Consider the case of a shallow, one hidden layer network, with the weights of the last layer being independent and identically distributed with symmetric \(\alpha\)-stable priors. Our results are derived under this setting using the following proposition of Der and Lee (2005). **Proposition 1**.: _(_Der and Lee, 2005_)__. Let the network specified by Equations (1) and (2), with a single hidden layer \((K=2)\), have i.i.d. hidden-to-output weights \(w_{j}^{(2)}\) distributed as a symmetric \(\alpha\)-stable with scale parameter \((\nu/2)^{1/2}p_{2}^{-1/\alpha}\). Then \(y(\mathbf{x})\) converges in distribution to a symmetric \(\alpha-\)stable process \(f(\mathbf{x})\) as \(p_{2}\to\infty\). The finite dimensional distribution of \(f(\mathbf{x})\), denoted as \((f(\mathbf{x}_{1}),\ldots,f(\mathbf{x}_{n}))\) for all \(n\), where \(\mathbf{x}_{i}\in\mathbb{R}^{I}\), is multivariate stable and admits a characteristic function:_ \[\phi(\mathbf{t})=\exp\left\{-(\nu/2)^{\alpha/2}\mathbb{E}[|\langle\mathbf{t}, \mathbf{g}\rangle|^{\alpha}]\right\}, \tag{3}\] _where angle brackets denote the inner product, \(\mathbf{g}=\left(g(\mathbf{x}_{1}),\ldots,g(\mathbf{x}_{n})\right)\), and \(g(\mathbf{x})\) is a random variable with the common distribution (across \(j\)) of \(z_{j}^{(2)}(\mathbf{x})\)._ Following Neal (1996), assume for the rest of the paper that the activation function \(g(\cdot)\) corresponds to the sign function: \(\mathrm{sign}(z)=1\), if \(z>0\); \(\mathrm{sign}(z)=-1\), if \(z<0\); and \(\mathrm{sign}(0)=0\). For \(\mathbf{z}\in\mathbb{R}^{I}\) we define \(g(\mathbf{z})=\mathrm{sign}\left(b_{0}+\sum_{i=1}^{I}w_{i}z_{i}\right)\), where \(b_{0}\) and \(w_{i}\) are i.i.d. standard Gaussian variables. The next challenge is to compute the expectation within the exponential in Equation (3). To resolve this, we break it into simpler cases. Define \(\Lambda\) as the set of all possible functions \(\tau:\{\mathbf{x}_{1},\ldots,\mathbf{x}_{n}\}\to\{-1,+1\}\). Noting that each \(\mathbf{x}_{j}\) can be mapped to two possible options: \(+1\) and \(-1\), indicates that there are \(2^{n}\) elements in \(\Lambda\). For each \(\ell=1,\ldots,2^{n}\), consider \(\tau_{\ell}\in\Lambda\), the event \(A_{\ell}=\{\tau_{\ell}(\mathbf{x}_{j})=g(\mathbf{x}_{j})\}_{j=1}^{n}\), and the probability \(q_{\ell}=\mathbb{P}(A_{\ell})\). By definition \(\{A_{\ell}\}_{\ell=1}^{2^{n}}\) is a set of disjoint events. Next, using the definition of the expectation of discrete disjoint events we obtain: \[\mathbb{E}[|\langle\mathbf{t},\mathbf{g}\rangle|^{\alpha}]=\sum_{\ell=1}^{2^ {n}}q_{\ell}\left|\sum_{j=1}^{n}t_{j}\tau_{\ell}(\mathbf{x}_{j})\right|^{ \alpha}. \tag{4}\] ### Computation of \(q_{\ell}\) and \(\tau_{\ell}\) Since the size of \(\Lambda\) is \(2^{n}\), indicating an exponential complexity of naive enumeration, we further simplify Equation (4). When the input points are arranged in a way that \(\tau_{\ell}\) is not possible, then \(q_{\ell}\) must be zero. We can identify the elements in \(\Lambda\) with positive probabilities by considering arbitrary values of \(b_{0},w_{1},\ldots,w_{I}\). The corresponding \(\tau\) function is determined by: \(\tau(\mathbf{x}_{j})=\mathrm{sign}(b_{0}+w_{1}x_{j1}+\cdots+w_{I}x_{j1})\), for each \(j\). This corresponds to labeling with \(+1\) the points above a hyperplane, and with \(-1\) the points that lie below the hyperplane. When \(I=1\), without loss of generality, let \(x_{1}<\cdots<x_{n}\). In this case \(\Lambda\) corresponds to the possible changes in sign that can occur between the input variables, which is equal to \(n\). Specifically, the sign change can occur before \(x_{1}\), between \(x_{1}\) and \(x_{2}\),..., between \(x_{n-1}\) and \(x_{n}\), and after \(x_{n}\). A similar argument is made in Example 2.1.1 of Der and Lee (2005), suggesting the possibility of considering more than one dimensions. For \(I>1\), Harding (1967) studies the possible partitions of \(n\) points in \(\mathbb{R}^{I}\) by an \((I-1)\)-dimensional hyperplane--which corresponds to our problem, and determines that for points in general configuration there are \(O(n^{I})\) partitions. Goodman and Pollack (1983) give an explicit algorithm for finding the elements of \(\Lambda\) that have non-zero probabilities in any possible configuration. We summarize their algorithm for \(I=2\) as Algorithm S.1 in Supplementary Section S.2. This algorithm runs in a computational time of order \(n^{I}\log(n)\), which is reasonable for moderate \(I\). For the rest of the article, we denote the cardinality of elements in \(\Lambda\) that have positive probability by \(L\), with the understanding that \(L\) will depend on the input vectors \(\mathbf{x}_{i}\) that are used and their dimension. This solves the issue of computing deterministically the values of \(\tau_{\ell}\) that have positive probability. Next we compute the probability \(q_{\ell}\) for the determined \(\tau_{\ell}\). For \(I=1\), the \(q_{\ell}\)s correspond to probabilities obtained from a Cauchy cumulative density function, which we state explicitly in Supplementary Section S.1. For general dimension of the input \(I>1\), the value of \(q_{\ell}\) is given by \(\mathbb{P}(\mathbf{Z}^{(\tau_{\ell})}>0)\), where the \(n\)-dimensional Gaussian vector \(\mathbf{Z}^{(\tau_{\ell})}\) has \(i\)-th entry given by \(\tau_{\ell}(\mathbf{x}_{i})(b_{0}+\sum_{j=1}^{I}w_{j}x_{ij})\). This implies that \(\mathbf{Z}^{(\tau_{\ell})}\sim\mathcal{N}_{n}(0,\mathbf{\Sigma}^{(\tau_{\ell} )})\), where the (possibly singular) variance matrix is \(\Sigma^{(\tau_{i,j})}_{i,j}=\tau_{\ell}(\mathbf{x}_{i})\tau_{\ell}(\mathbf{x}_ {j})(1+\sum_{k=1}^{n}x_{ik}x_{jk})\). This means we can compute \(q_{\ell}=\mathbb{P}(\mathbf{Z}^{(\tau_{\ell})}>0)\) using for example the R package mvtnorm, which implements the method of Genz and Bretz (2002) for evaluating multivariate Gaussian probabilities. Since the \(q_{\ell}\)s require independent procedures to be computed, this is easily parallelized after obtaining the partitions. A characterization of the posterior predictive density under stable network weights using a conditionally Gaussian representation While the previous section demonstrated the characteristic function of Equation (4) can be computed, the resulting density, obtained via its inverse Fourier transform, does not necessarily have a closed form, apart from specific values of \(\alpha\), such as \(\alpha=2\) (Gaussian), \(\alpha=1\) (Cauchy) or \(\alpha=0.5\) (inverse Gaussian). In this section we show that a _conditionally Gaussian_ characterization of the density function is still possible for the entire domain of \(\alpha\in(0,2]\), facilitating posterior inference. First, note that the result of Der and Lee (2005) is obtained assuming that there is no intrinsic error in the observation model, i.e., they assume the observations are obtained as \(y_{i}=f(\mathbf{x}_{i})\), and the only source of randomness is the network weights. We generalize this to more realistic scenarios and consider an additive error term, known as the nugget effect in spatial statistics (Stein, 1999, p. 94). That is, we consider the observation model \(y_{i}=f(\mathbf{x}_{i})+\varepsilon_{i}\), where the error terms \(\varepsilon_{i}\) are independent identically distributed normal random variables with constant variance \(\sigma^{2}\). Using the expression for the expectation in the characteristic function from Proposition 1, we derive the full probability density function, as specified in the following theorem, with proof in Appendix A.1. **Theorem 1**.: _For real-valued observations \(\mathbf{y}=(y_{1},\ldots,y_{n})\) under the model \(y_{i}=f(\mathbf{x}_{i})+\varepsilon_{i};\) where \(\varepsilon_{i}\overset{i.i.d.}{\sim}\mathcal{N}(0,\sigma^{2})\) and \(f(\cdot)\) is as specified in Proposition 1, denote the matrix \(\mathbf{X}=[\mathbf{x}_{1},\ldots,\mathbf{x}_{n}]^{T}\). The probability density function of \((\mathbf{y}\mid\mathbf{X})\) is:_ \[p(\mathbf{y}\mid\mathbf{X})=(2\pi)^{-n/2}\int_{(\mathbb{R}^{+})^{L}}\exp \left(-\frac{1}{2}\mathbf{y}^{T}\mathbf{Q}^{-1}\mathbf{y}\right)\det(\mathbf{ Q})^{-1/2}\prod_{\ell=1}^{L}p_{S^{+}}(s_{\ell})ds_{\ell},\] _where \(p_{S^{+}}\) is the density for a positive \(\alpha/2\)-stable random variable, and \(\mathbf{Q}\) is a positive definite matrix with probability one that depends on \(\{s_{\ell}\}_{\ell=1}^{L}\). Specifically, \(\mathbf{Q}\) has diagonal entries \(\sigma^{2}+\nu\sum_{\ell=1}^{L}q_{\ell}^{2/\alpha}s_{\ell}\), and the entry \((i,j)\) is given by \(\nu\sum_{\ell=1}^{L}q_{\ell}^{2/\alpha}s_{\ell}\tau_{\ell}(\mathbf{x}_{i})\tau _{\ell}(\mathbf{x}_{j})\), for \(i\neq j\)._ Theorem 1 is the main machinery we need for posterior inference. We emphasize that \(\mathbf{Q}\) is a matrix with random entries, conditional on \(\{s_{\ell}\}_{\ell=1}^{L}\); and \(\{q_{\ell}\}_{\ell=1}^{L}\) and \(\{\tau_{\ell}\}_{\ell=1}^{L}\) are deterministic. Further, the input variables \(\mathbf{X}\) are also deterministic. Theorem 1 implies the hierarchical Gaussian model: \[\mathbf{y}\mid\mathbf{X},\{s_{\ell}\}_{\ell=1}^{L}\sim\mathcal{N}_{n}(0, \mathbf{Q}),\ s_{\ell}\stackrel{{ i.i.d.}}{{\sim}}S^{+}(\alpha/2).\] Each of the \(\tau\)s defines a level set for the points that lie in the \(+1\) side in contraposition to those that lie in the \(-1\) side. A forward simulation of this model is a weighted sum of the \(\tau\)s, with corresponding positive weight for those that lie closer and a negative weight for the points that lie further. In a similar vein, we present a corollary to interpret the distribution of the covariance matrix. **Corollary 1**.: _The marginal distribution of the diagonal entries of the matrix \(\mathbf{Q}\) is \(\sigma^{2}+\nu S^{+}(\alpha/2)\), where the \(\sigma^{2}\) acts as a shift parameter, and the marginal distribution of the entry \(i,j\) in the \(\mathbf{Q}\) matrix is \(S(\alpha/2,\nu,2p_{ij}-1)\), where \(p_{ij}=\sum_{\ell:\tau_{\ell}(\mathbf{x}_{i})=\tau_{\ell}(\mathbf{x}_{j})}q_{\ell}\), the probability that \(\mathbf{x}_{i}\) and \(\mathbf{x}_{j}\) lie on the same side of the hyperplane partition. Further, the entries of \(\mathbf{Q}\) are not independent._ Proof.: For \(\{\mathbf{Q}\}_{ii}-\sigma^{2}\), we apply Property 1.2.1 of Samorodnitsky and Taqqu (1994), which we refer as the closure property, to obtain \(\nu S^{+}(\alpha/2)\). Next for \(\{\mathbf{Q}\}_{ij}\), we split the summation in two cases: \(\tau_{\ell}(\mathbf{x}_{i})=\tau_{\ell}(\mathbf{x}_{j})\), and \(\tau_{\ell}(\mathbf{x}_{i})\neq\tau_{\ell}(\mathbf{x}_{j})\). Using the closure property in the separate splits, we obtain \(\{\mathbf{Q}\}_{ij}\sim S(\alpha/2,\nu p_{ij}^{2/\alpha},1)-S(\alpha/2,\nu(1- p_{ij})^{2/\alpha},1)\). The result follows by applying the closure property once more. The entries of \(\mathbf{Q}\) are not independent, as they are obtained from a linear combination of the independent variables \(\{s_{\ell}\}_{\ell=1}^{L}\). The value of Corollary 1 does not lie in a numerical or computational speed-up, since the obtained marginals are not independent, but rather in the interpretability that it lends to the model. Explicitly, it indicates that when the points lie closer their conditional covariance is more likely to be positive and when they lie farther apart the covariance is more likely to be negative (see Proposition 1.2.14 of Samorodnitsky and Taqqu, 1994). Now that the probability model is clear, we proceed to the next problem of interest: prediction. To this end, we present the following proposition, characterizing the posterior predictive density. **Proposition 2**.: _Consider a vector of \(n\) real-valued observations \(\mathbf{y}=(y_{1},\ldots,y_{n})\), each with respective input variables \(\mathbf{x}_{1},\ldots,\mathbf{x}_{n}\in\mathbb{R}^{I}\), under the model \(y_{i}=f(\mathbf{x}_{i})+\varepsilon_{i};\varepsilon_{i}\stackrel{{ i.i.d.}}{{\sim}} \mathcal{N}(0,\sigma^{2}),\) and \(m\) new input variable locations: \(\mathbf{x}_{1}^{*},\ldots,\mathbf{x}_{m}^{*}\in\mathbb{R}^{I}\), with future observations at those locations denoted by \(\mathbf{y}^{*}=(\mathbf{y}_{1}^{*},\ldots,\mathbf{y}_{m}^{*})\). Denote the matrices \(\mathbf{X}=[\mathbf{x}_{1},\ldots,\mathbf{x}_{n}]^{T}\) and \(\mathbf{X}^{*}=[\mathbf{x}_{1}^{*},\ldots,\mathbf{x}_{m}^{*}]^{T}\). The posterior distribution at these new input variables satisfies the following properties:_ 1. _The conditional posterior of_ \(\mathbf{y}^{*}\mid\mathbf{y},\mathbf{X},\mathbf{X}^{*},\mathbf{Q}\) _is an_ \(m\)_-dimensional Gaussian. Specifically:_ \[\mathbf{y}^{*}\mid\mathbf{y},\mathbf{X},\mathbf{X}^{*},\mathbf{Q}\sim\mathcal{ N}_{m}(\boldsymbol{\mu}^{*},\boldsymbol{\Sigma}^{*}),\] (5) _where_ \(\boldsymbol{\mu}^{*}=\mathbf{Q}_{*,1:n}\mathbf{Q}_{1:n,1:n}^{-1}\mathbf{y}\)_, and_ \(\boldsymbol{\Sigma}^{*}=\mathbf{Q}_{*,*}-\mathbf{Q}_{*,1:n}\mathbf{Q}_{1:n,1:n} ^{-1}\mathbf{Q}_{1:n,*}\)_, using_ \(\mathbf{Q}\) _as previously defined for the_ \(n+m\) _input variables, and denoting by_ \({}^{*}\)_' the entries_ \((n+1):(n+m)\)_._ 2. _The posterior predictive density at the_ \(m\) _new locations conditional on the observations_ \(\mathbf{y}\)_, is given by:_ \[p(\mathbf{y}^{*}\mid\mathbf{y},\mathbf{X},\mathbf{X}^{*})=\int_{(\mathbb{R}^{ +})^{L}}p(\mathbf{y}^{*}\mid\mathbf{y},\mathbf{X},\mathbf{X}^{*},\mathbf{Q})p( \mathbf{Q}\mid\mathbf{y},\mathbf{X})d\mathbf{Q},\] (6) _where_ \(p(\mathbf{y}^{*}\mid\mathbf{y},\mathbf{X},\mathbf{X}^{*},\mathbf{Q})\) _is the conditional posterior density of_ \(\mathbf{y}^{*}\)_,_ \(\mathbf{Q}\) _is as previously described for the_ \(n+m\) _input variables, and the integral is over the values determined by_ \(\{s_{\ell}\}_{\ell=1}^{L}\)_._ Proof.: The first is an immediate application of Theorem 1 and the conditional density of a multivariate Gaussian. The second part follows from a standard application of marginal probabilities. An MCMC algorithm to sample from the posterior predictive distribution Dealing with \(\alpha\)-stable random variables includes the difficulty that the moments of the variables are only finite up to an \(\alpha\) power. Specifically, for \(\alpha<2\), if \(X\sim S(\alpha,\nu,\beta)\), then \(\mathbb{E}[|X|^{r}]=\infty\) if \(r\geq\alpha\), and is finite otherwise (Samorodnitsky and Taqqu, 1994, Property 1.2.16). To circumvent dealing with potentially ill-defined moments, we propose to sample from the full posterior. For fully Bayesian inference, we assign \(\sigma^{2}\) a half-Cauchy prior (Gelman, 2006) and iteratively sample from the posterior predictive distribution by cycling through \((\mathbf{y}^{*},\mathbf{Q},\sigma^{2})\) in an MCMC scheme, as described in Algorithm 1, which has computational complexity of the order of \(\mathcal{O}(T[(n+m)^{I}n^{2}+m^{3}])\), where \(T\) is the number of MCMC simulations used. The method of Chambers et al. (1976) is used for simulating the stable variables. An implementation of our algorithms is freely available online. ``` 0: Vector of \(n\) real-valued observations \(\mathbf{y}\) with \(I\)-dimensional input variables \(\mathbf{X}\in\mathbb{R}^{n\times I}\), new input variables \(\mathbf{X}^{*}\in\mathbb{R}^{m\times I}\), and number of MCMC iterations \(T\). 0: Posterior predictive samples \(\{\mathbf{y}_{t}^{*}\}_{t=1}^{T}\) Obtain \(\Lambda\) for \((\mathbf{X},\mathbf{X}^{*})\) using Algorithm S.1. Compute \(\{q_{\ell}\}_{\ell=1}^{L}\) as described in Section 2.1. Initialize \(\mathbf{Q}_{0}\) using independent samples of \(s_{\ell}\) from the prior distributions. for\(t=1,\ldots,T\)do Simulate \(\mathbf{Q}_{t}\mid\mathbf{y},\mathbf{Q}_{t-1}\) using Algorithm S.2. Compute \(\boldsymbol{\mu}_{t}^{*}\) and \(\boldsymbol{\Sigma}_{t}^{*}\) using \(\mathbf{Q}_{t}\) in Part 1 of Proposition 2. Simulate \(\mathbf{y}_{t}^{*}\mid(\mathbf{y},\mathbf{Q}_{t})\sim\mathcal{N}_{m}(\boldsymbol {\mu}_{t}^{*},\boldsymbol{\Sigma}_{t}^{*})\). endfor return\(\{\mathbf{y}_{t}^{*}\}_{t=1}^{T}\). ``` **Algorithm 1** A Metropolis-Hastings sampler for the posterior predictive distribution There are two hyper-parameters in our model: \(\alpha,\nu\). We propose to select them by cross validation on a grid of \((\alpha,\nu)\), and selecting the result with smallest mean absolute error (MAE). Another possible way to select \(\alpha\) is by assigning a prior. The natural choice for \(\alpha\) is a uniform prior on \((0,2)\), however the update rule would need to consider the densities of the \(L\) such \(\alpha/2\)-stable densities \(p_{S^{+}}\), which would be computationally intensive as there is no closed form expression for this density apart from specific values of \(\alpha\). A prior for \(\nu\) could be included but a potential issue of identifiability emerges, similar to what has been identified for the Matern kernel (Zhang, 2004). Our proposed method avoids dealing with these issues, which we leave open for future research. ## 4 Numerical experiments in one and two dimensions To validate our method, we compare it against the predictions obtained from three methods. The first two are methods for Gaussian processes that correspond to the two main approaches in GP inference: maximum likelihood with a Gaussian covariance kernel (Dancik and Dorman, 2008), and an MCMC based Bayesian procedure using the Matern kernel (Gramacy and Taddy, 2010); the third method is a two-layer Bayesian neural network (BNN) using a single hidden layer of 100 nodes with Gaussian priors, implemented in pytorch(Paszke et al., 2019), and fitted via a variational approach. The choice of a modest number of hidden nodes is intentional, so that we are away from the inifinite width GP limit, and the finite-dimensional behavior can be visualized. The respective implementation are in the R packages mlegp, tgp, and the python libraries pytorch and torchbnn. The estimates used from these methods are respectively the kriging estimate, posterior median and posterior mean. We tune our method by cross-validation over a grid of \((\alpha,\nu)\). We use point-wise posterior median as the estimate, and report the values with smallest mean absolute error (MAE) and the optimal parameters. Results on uncertainty quantification, timing, and additional simulations are in Supplementary Section S.3. We use a data generating mechanism of the form \(y=f(x)+\varepsilon\), where the \(f\) is the true function. The overall summary is that when \(f\) has at least one discontinuity, our method performs better at prediction than the competing methods, and when \(f\) is continuous the proposed method performs just as well as the other methods. This provides empirical support that the assumption of _continuity_ of the true function cannot be disregarded in the _universal approximation_ property of neural networks (Hornik et al., 1989), and the adoption of infinite variance prior weights might be a crucial missing ingredient for successful posterior prediction when the truth is discontinuous. ### Experiments in one dimension We consider a function with three jumps: \(f(x)=5\times\mathbf{1}_{\{x\geq 1\}}+5\times\mathbf{1}_{\{-1\leq x<0\}}\), to which we add a Gaussian noise with \(\sigma=0.5\). We consider \(x\in[-2,2]\), with 40 equally spaced points as the training set, and 100 equally spaced points in the testing set. We display the two-panel Figure 1, showing the comparisons between the four methods. The boxplots in the left panel show that the proposed method - which we term _"Stable,"_ has the smallest prediction error. The right panel shows that the BNN, the GP based fully Bayesian, and maximum likelihood methods have much smoother predictions than the Stable method. This indicates the inability of these methods to capture sharp jumps as well as the Stable method, which very clearly captures them. The Stable method obtains the smallest cross validation error for this case with \(\alpha^{*}=1.1\) and \(\nu^{*}=1\). ### Experiments in two dimensions We consider the function: \(f(x_{1},x_{2})=5\times\mathbf{1}_{\{x_{1}>0\}}+5\times\mathbf{1}_{\{x_{2}>0\}}\), with additive Gaussian noise with \(\sigma=0.5\), and observations on an equally-spaced grid of 49 points in the square \([-1,1]^{2}\). In Figure 2 we display the boxplots and contour plots for all methods for out-of-sample prediction on an equally spaced grid of \(9\times 9\) points in the same square. The methods that employ Gaussian processes (GP Bayes and GP MLE) and BNN seem to have smoother transitions between the different quadrants, whereas the Stable method captures the sharp jumps better. This is reinforced by the prediction errors displayed in the left panel. For this example, the Stable method obtains the smallest cross validation error with \(\alpha^{*}=1.1,\nu^{*}=1\). Figure 1: _Left:_ Boxplots of mean absolute error of out-of-sample prediction over test points, and _Right:_ predicted values over 100 points on a regular grid on \([-2,2]\). Training points in black dots. Figure 2: _Left:_ Boxplots of mean absolute error (MAE) of out-of-sample prediction over test points, and _Right:_ predicted values over a \(9\times 9\) grid on \([-1,1]^{2}\). ## 5 A demonstration of out of sample prediction using York air quality data Measurements in parts per million (ppm) on the level of nitrogen dioxide (\(\mathrm{NO}_{2}\)), a known environmental pollutant, are available in the city of York, UK, 1 at different locations. We use the data from July 2020, to obtain the mean absolute error in out-of-sample prediction. We split the outcomes randomly into two parts: validation and training, comprising of 60 and 128 observations respectively. To select the hyper-parameters in the Stable method we use random splits of the training set, and obtain the optimal point \((\alpha^{*},\nu^{*})=(1.9,1)\) by cross validation. We compare it to the three methods described in Section 4, and display the results in Table 1, with the Stable method performing the best. We include visualizations in Supplementary Section S.4. Footnote 1: [https://data.yorkopendata.org/dataset/diffusion-tubes-locations](https://data.yorkopendata.org/dataset/diffusion-tubes-locations) ## 6 Conclusions and future work We develop a novel method for posterior inference and prediction for infinite width limits of shallow (one hidden layer) BNNs under weights with infinite prior variance. While the \(\alpha\)-stable forward scaling limit in this case has been known in the literature (Der and Lee, 2005; Peluchetti et al., 2020), the lack of a covariance function precludes the inverse problem of feasible posterior inference and prediction, which we overcome using a conditionally Gaussian representation. There is a wealth of literature on the universal approximation property of both shallow and deep neural networks, following the pioneering work of Hornik et al. (1989), but they work under the assumption of a _continuous_ true function. Our numerical results demonstrate that when the truth has jump discontinuities, it is possible to obtain much better results with a BNN using weights with unbounded prior variance. The fully Bayesian posterior also allows straightforward probabilistic uncertainty quantification for the infinite width scaling limit under \(\alpha\)-stable priors on network weights. Several future directions could naturally follow from the current work. The most immediate is perhaps an extension to posterior inference for deep networks under stable priors, where the width of each layer simultaneously approaches infinity, and we strongly suspect this should be possible. Developing analogous results under non-i.i.d. or tied weights to perform posterior inference under the scaling limits for Bayesian convolutional neural networks should also be of interest. Finally, one may of course investigate alternative activation functions, such as the hyperbolic tangent, which will lead to a different characteristic function for the scaling limit. ## Supplementary Material The supplementary material contains technical details, numerical results and computer code to reproduce the simulation results on Github at: [https://github.com/loria/alphastableNNet](https://github.com/loria/alphastableNNet). ## Appendix A Appendix ### Proof of Theorem 1 Our derivations rely on Equation 5.4.6 of Uchaikin and Zolotarev (1999), which states that for \(\alpha_{0}\in(0,1)\) and for all positive \(\lambda\) one has: \(\exp(-\lambda^{\alpha_{0}})=\int_{0}^{\infty}\exp(-\lambda t)p_{S^{+}}(t)dt,\) where \(p_{S^{+}}\) is the density function of a positive \(\alpha_{0}\)-stable random variable. Using \(\lambda=\nu z^{2}\) and \(\alpha_{0}=\alpha/2\) and the fact that \(z^{2}=|z|^{2}\), we obtain for \(\alpha\in(0,2)\) that: \[\exp(-\nu^{\alpha/2}|z|^{\alpha})=\int_{0}^{\infty}\exp(-\nu z^{2}t)p_{S^{+}}( t)dt, \tag{7}\] \begin{table} \begin{tabular}{l c c c c} \hline & Stable & GP MLE & GP Bayes & Bayes NNet \\ \hline MAE & 0.57 & 0.59 & 0.58 & 0.59 \\ \hline \end{tabular} \end{table} Table 1: Mean absolute error of predictions in the York \(\mathrm{NO}_{2}\) air quality data set, by method. where \(p_{S^{+}}\) is the density function of a positive \(\alpha/2\)-stable random variable and \(z\in\mathbb{R}\). By Equation (4) of Der and Lee (2005), and the characteristic function of independent normally distributed error terms with a common variance \(\sigma^{2}\), we have that: \[\phi_{\mathbf{y}}(\mathbf{t}) =\exp\left(-\sum_{\ell=1}^{L}2^{-\alpha/2}\nu^{\alpha/2}q_{\ell} \left|\sum_{j=1}^{n}t_{j}\tau_{\ell}(\mathbf{x}_{j})\right|^{\alpha}-\frac{1} {2}\sum_{j=1}^{n}\sigma^{2}t_{j}^{2}\right)\] \[=\prod_{\ell=1}^{L}\exp\left(-2^{-\alpha/2}\nu^{\alpha/2}q_{\ell} \left|\sum_{j=1}^{n}t_{j}\tau_{\ell}(\mathbf{x}_{j})\right|^{\alpha}\right) \times\exp\left(-\frac{1}{2}\sum_{j=1}^{n}\sigma^{2}t_{j}^{2}\right)\] \[=\prod_{\ell=1}^{L}\int_{0}^{\infty}\exp\left(-\frac{1}{2}\nu s_{ \ell}q_{\ell}^{2/\alpha}\left(\sum_{j=1}^{n}t_{j}\tau_{\ell}(\mathbf{x}_{j}) \right)^{2}\right)p_{S^{+}}(s_{\ell})ds_{\ell}\times\exp\left(-\frac{1}{2} \sum_{j=1}^{n}\sigma^{2}t_{j}^{2}\right)\] \[=\prod_{\ell=1}^{L}\int_{0}^{\infty}\exp\left(-\frac{1}{2}\nu s_{ \ell}q_{\ell}^{2/\alpha}\mathbf{t}^{T}\mathbf{M}_{\ell}\mathbf{t}\right)p_{S^ {+}}(s_{\ell})ds_{\ell}\times\exp\left(-\frac{1}{2}\sum_{j=1}^{n}\sigma^{2}t_ {j}^{2}\right),\] where the third line follows by using Equation (7), and in the last line we define \(\mathbf{M}_{\ell}\) as the matrix with ones in the diagonal and with the \((i,j)\)th entry given by \(\tau_{\ell}(\mathbf{x}_{i})\tau_{\ell}(\mathbf{x}_{j}),\ i\neq j\). Next, using the fact that the densities are over the independent variables \(\{s_{\ell}\}_{\ell=1}^{L}\) we bring the product inside the integrals and employ the property of the exponential to obtain: \[\phi_{\mathbf{y}}(\mathbf{t}) =\int_{(\mathbb{R}^{+})^{L}}\exp\left(-\frac{1}{2}\sum_{j=1}^{n}t _{j}^{2}\sigma^{2}-\frac{1}{2}\nu\sum_{\ell=1}^{L}s_{\ell}q_{\ell}^{2/\alpha} \mathbf{t}^{T}\mathbf{M}_{\ell}\mathbf{t}\right)\prod_{\ell=1}^{L}p_{S^{+}}(s _{\ell})ds_{\ell}\] \[=\int_{(\mathbb{R}^{+})^{L}}\exp\left(-\frac{1}{2}\mathbf{t}^{T} \mathbf{Q}\mathbf{t}\right)\prod_{\ell=1}^{L}p_{S^{+}}(s_{\ell})ds_{\ell},\] using on the second line the definition of \(\mathbf{Q}\). The required density is now obtained by the use of the inverse Fourier transform on the characteristic function: \[p(\mathbf{y}\mid\mathbf{X}) =\int_{\mathbb{R}^{n}}\phi_{\mathbf{y}}(\mathbf{t})\exp(i( \mathbf{t},\mathbf{y}))\prod_{j=1}^{n}dt_{j}\] \[=\int_{\mathbb{R}^{n}}\left\{\int_{(\mathbb{R}^{+})^{L}}\exp \left(-\frac{1}{2}\mathbf{t}^{T}\mathbf{Q}\mathbf{t}\right)\prod_{\ell=1}^{L}p _{S^{+}}(s_{\ell})ds_{\ell}\right\}\exp(i(\mathbf{t},\mathbf{y}))\prod_{j=1}^{ n}dt_{j}\] \[=\int_{(\mathbb{R}^{+})^{L}}\left\{\int_{\mathbb{R}^{n}}\exp \left(-\frac{1}{2}\mathbf{t}^{T}\mathbf{Q}\mathbf{t}\right)\exp(i(\mathbf{t}, \mathbf{y}))\prod_{j=1}^{n}dt_{j}\right\}\prod_{\ell=1}^{L}p_{S^{+}}(s_{\ell}) ds_{\ell},\] where the second line follows by the derived expression for the characteristic function, and the third line follows by Fubini's theorem since all the integrals are real and finite. We recognize that the term \(\exp(-(1/2)\mathbf{t}^{T}\mathbf{Q}\mathbf{t})\) corresponds to a multivariate Gaussian density with covariance matrix \(\mathbf{Q}^{-1}\), though it is lacking the usual determinant term. After completing it, we obtain the density and can use the characteristic function of Gaussian variables to finally obtain the result: \[p(\mathbf{y}\mid\mathbf{X})=(2\pi)^{-n/2}\int_{(\mathbb{R}^{+})^{L}}\exp \left(-\frac{1}{2}\mathbf{y}^{T}\mathbf{Q}^{-1}\mathbf{y}\right)\det( \mathbf{Q})^{-1/2}\prod_{\ell=1}^{L}p_{S^{+}}(s_{\ell})ds_{\ell}.\] In using \(\mathbf{Q}^{-1}\) freely, we assumed through the previous steps that \(\mathbf{Q}\) is positive-definite. We proceed to prove this fact. Note that \(\mathbf{Q}\) is obtained from the sum of \(L\) rank-one matrices and a diagonal matrix, where each of the rank-one matrices is \(q_{\ell}^{2/\alpha}s_{\ell}\nu\tau_{\ell}\boldsymbol{\tau}_{\ell}^{T}\), denoting by \(\boldsymbol{\tau}_{\ell}\) the vector with entries \((\tau_{\ell}(\mathbf{x}_{1}),\ldots,\tau_{\ell}(\mathbf{x}_{n}))\). Consider a non-zero vector \(\mathbf{w}\in\mathbb{R}^{n}\). Then: \[\mathbf{w}^{T}\mathbf{Q}\mathbf{w}=\mathbf{w}^{T}\left(\sigma^{2}\mathbf{I}+ \nu\sum_{\ell=1}^{L}s_{\ell}q_{\ell}^{2/\alpha}\boldsymbol{\tau}_{\ell}^{T} \boldsymbol{\tau}_{\ell}\right)\mathbf{w}\] \[=\sigma^{2}\mathbf{w}^{T}\mathbf{w}+\nu\sum_{\ell=1}^{L}s_{\ell}q_{ \ell}^{2/\alpha}\mathbf{w}^{T}\boldsymbol{\tau}_{\ell}\boldsymbol{\tau}_{\ell}^ {T}\mathbf{w}\] \[=\sigma^{2}\sum_{j=1}^{n}w_{j}^{2}+\nu\sum_{\ell=1}^{L}s_{\ell}q_ {\ell}^{2/\alpha}\left(\sum_{j=1}^{n}w_{j}\tau_{\ell}(x_{j})\right)^{2}\] \[>0,\] which implies that \(\mathbf{Q}\) is positive-definite with probability 1. ## Acknowledgments Bhadra is supported by U.S. National Science Foundation grant DMS-2014371.
2301.08292
Quantum HyperNetworks: Training Binary Neural Networks in Quantum Superposition
Binary neural networks, i.e., neural networks whose parameters and activations are constrained to only two possible values, offer a compelling avenue for the deployment of deep learning models on energy- and memory-limited devices. However, their training, architectural design, and hyperparameter tuning remain challenging as these involve multiple computationally expensive combinatorial optimization problems. Here we introduce quantum hypernetworks as a mechanism to train binary neural networks on quantum computers, which unify the search over parameters, hyperparameters, and architectures in a single optimization loop. Through classical simulations, we demonstrate that of our approach effectively finds optimal parameters, hyperparameters and architectural choices with high probability on classification problems including a two-dimensional Gaussian dataset and a scaled-down version of the MNIST handwritten digits. We represent our quantum hypernetworks as variational quantum circuits, and find that an optimal circuit depth maximizes the probability of finding performant binary neural networks. Our unified approach provides an immense scope for other applications in the field of machine learning.
Juan Carrasquilla, Mohamed Hibat-Allah, Estelle Inack, Alireza Makhzani, Kirill Neklyudov, Graham W. Taylor, Giacomo Torlai
2023-01-19T20:06:48Z
http://arxiv.org/abs/2301.08292v1
# Quantum HyperNetworks: Training Binary Neural Networks in Quantum Superposition ###### Abstract Binary neural networks, i.e., neural networks whose parameters and activations are constrained to only two possible values, offer a compelling avenue for the deployment of deep learning models on energy- and memory-limited devices. However, their training, architectural design, and hyperparameter tuning remain challenging as these involve multiple computationally expensive combinatorial optimization problems. Here we introduce quantum hypernetworks as a mechanism to train binary neural networks on quantum computers, which unify the search over parameters, hyperparameters, and architectures in a single optimization loop. Through classical simulations, we demonstrate that of our approach effectively finds optimal parameters, hyperparameters and architectural choices with high probability on classification problems including a two-dimensional Gaussian dataset and a scaled-down version of the MNIST handwritten digits. We represent our quantum hypernetworks as variational quantum circuits, and find that an optimal circuit depth maximizes the probability of finding performant binary neural networks. Our unified approach provides an immense scope for other applications in the field of machine learning. + Footnote †: Work done before joining AWS. + Footnote †: Work done before joining AWS. ## I Introduction The availability of high quality data sources along with algorithmic and hardware advances for training neural networks have paved the way for a new generation of large models displaying unprecedented accuracy across a wide array of technologically and scientifically relevant tasks. These advances crucially depend on the availability of specialized computational resources such as graphics and tensor processing units, which demand a high electricity consumption. In particular, a set of key but computationally expensive elements in the modern machine learning (ML) workflow include hyperparameter optimization and neural architecture search. Traditionally, these operate via an outer optimization loop which searches through the hyperparameter and architectural state spaces guided by the model's performance on a validation set, and an inner optimization which adjusts the parameter of the neural network on a training set. Such a nested optimization process remains the most computationally demanding task in the modern ML workflow and entails an unsustainable carbon footprint, which calls for computationally efficient hardware and algorithms to train and search for neural architectures [1]. Neural networks with binary parameters and activations (BiNNs) partially alleviate these issues as they are computationally efficient, hardware-friendly, and energy efficient. Beyond a direct 32-fold reduction of the memory footprint with respect to a full-precision neural network, BiNNs can exploit specialized hardware implementations that simultaneously increase computational speed [2] and improve their energy efficiency [3]. Another benefit of very low-precision neural networks is their improved robustness against adversarial attacks while matching the performance of full-precision models in the worst cases [4]. While in principle it is possible to binarize trained continuous-variable neural networks, such a procedure typically leads to significant accuracy losses, which makes it preferable to directly learn their binary parameters. The ML community has developed approaches to the use of BiNNs which bypass the infeasible discrete optimization of their training through a re-framing of the problem in the conventional domain of gradient descent algorithms. These include post-quantization of conventionally trained neural networks, as well as deterministic and stochastic relaxations of the original problem both for parameter tuning [5; 6; 7; 8] and architecture search [9]. In spite of these advances, the combined optimization of a BiNN's parameters and their associated hyperparameter and architecture searches remain computationally demanding as these involve solving multiple nested combinatorial optimization problems or their associated relaxations. Quantum computing, which aims at exploiting quantum interference and entanglement to enable the solution to a wide array of classically intractable computations, provides an alternative approach to the training of neural networks [10; 11; 12; 13; 14; 15; 16; 17; 18; 19; 20]. In particular, variational quantum algorithms (VQAs) have emerged as a potential strategy to obtain quantum computational advantage on near-term quantum devices [21; 22]. These algorithms employ parameterized quantum circuits that can adapt to current experimental constraints such as the limited number and connectivity of the qubits, gate infidelities, and coherent and incoherent errors that limit the accuracy of practically realizable quantum circuits [21; 22]. Here we promote hypernetworks-networks that generate the weights of another network [23]-to quantum hypernetworks, i.e., quantum states that generate the weights of a neural network. Quantum hypernetworks offer an alternative approach to the training of BiNNs through a unification of the parameter, hyperparameter, and architecture searches in a single optimization loop. A quantum hypernetwork, here implemented through a parameterized quantum circuit of variable depth, is trained to search over an augmented space comprising the parameters of the neural network, its hyperparameters, and any desired architectural choices with an eye on improving the overall efficiency of the BiNN workflow. Through classical simulations, we show that quantum hypernetworks with short depth and limited connectivity can jointly optimize BiNNs' hyperparameters, architectural choices, and parameters for toy classification problems including a two-dimensional Gaussian dataset and a scaled-down version of the MNIST handwritten digits. We find that the probability of finding performant BiNNs is maximized at a specific circuit depth, which suggests that an optimal use of entanglement and quantum effects decrease the probability that the optimization finds poor local minima. Through a Fourier analysis, we reveal that the objective functions used to train the BiNNs are predominantly local. This observation, together with our numerical experiments, suggests that quantum hypernetworks built from local low-depth circuits with limited connectivity, all of which are common features to most currently available quantum computers, can be effective at training BiNNs. Our analysis indicates that the locality of the objective function may not induce tractability problems related to the presence of barren plateaus which interfere with the accurate estimation of the gradients used during the optimization of the circuits. ## II Results ### Variational Quantum HyperNetworks To encode the problem in a form suitable to optimization by a quantum computer, we consider quantum states composed of \(N\) qubits written in the computational basis corresponding to the eigenstates of tensor products of the Pauli operator \(\hat{\sigma}_{i}^{z}\) acting on qubits \(i\), namely \[|\Psi\rangle=\sum_{\sigma_{1},\ldots,\sigma_{N}}\Psi(\sigma_{1},\ldots,\sigma_ {N})|\sigma_{1},\ldots,\sigma_{N}\rangle, \tag{1}\] where \(\hat{\sigma}_{i}^{z}|\sigma_{1},\ldots,\sigma_{i},\ldots,\sigma_{N}\rangle=(2 \sigma_{i}-1)|\sigma_{1},\ldots,\sigma_{i},\ldots,\sigma_{N}\rangle\), and \(\sigma_{i}\in\{0,1\}\). A quantum hypernetwork is a quantum state \(|\Psi\rangle\) where each basis element \(|\mathbf{\sigma}\rangle=|\sigma_{1},\ldots,\sigma_{N}\rangle\) is associated with a specific configuration of an augmented model comprising the parameters of a BiNN, its hyperparameters, and any desired architectural choices to be encoded in the quantum hypernetwork. As quantum superposition is the feature of a quantum system whereby it exists in several separate states, i.e., all the different BiNNs encoded in Eq. 1, our approach can be understood as training BiNNs in quantum superposition. In Fig. 1(a) we represent a quantum hypernetwork encoding a small binary linear feed-forward network with a two-dimensional input and one-dimensional output. The BiNN is characterized by 2 weights (qubits \(\sigma_{1}\) and \(\sigma_{2}\)), a bias (qubit \(\sigma_{3}\)), and an activation function. To encode architectural choices, e.g., the selection of activation function from two possibilities \(f_{1}\) or \(f_{2}\), we make the activation function qubit dependent (qubit \(\sigma_{4}\) in Fig. 1(a-b)), i.e., \(f(x)\to f(x,\sigma)\), where, e.g., \[f(\mathbf{x};\sigma)=\begin{cases}f_{1}(\mathbf{x})&\text{if}\ \sigma=0\\ f_{2}(\mathbf{x})&\text{if}\ \sigma=1.\end{cases}\] As explored below, other architectural choices and hyperparameters can be similarly encoded through the use of additional qubits. A design principle for a quantum algorithm aiming at training classical neural networks may consist of the preparation of a quantum state \(|\Psi\rangle\) (i.e. the hypernetwork) that assigns high amplitudes \(\Psi(\sigma_{1},\ldots,\sigma_{N})\) to basis states \(|\sigma_{1},\ldots,\sigma_{N}\rangle\) encoding neural networks with a low cost function \(C\) quantifying their performance \[C\left(\mathbf{w}\right)=\frac{1}{N_{t}}\sum_{i=1}^{N_{s}}\mathcal{L}\left(\text{ NN}(\mathbf{x}_{i};\{\mathbf{w}\}),\mathbf{y}_{i}\right). \tag{2}\] Here \(N_{s}\) is the size of the training dataset composed of input \(x_{i}\) and output \(y_{i}\) variables, \(\mathcal{L}\) is a loss function, and \(\text{NN}(\mathbf{x}_{i};\mathbf{w})\) represents an augmented neural network model. The augmented model parameters \(\mathbf{w}=\{w_{1},\ldots,w_{N}\}\), include the neural network weights, biases, hyperparameters, and architectural choices. The cost function corresponds to an \(N\)-bit real Boolean function \(C:\{0,1\}^{N}\rightarrow\mathbb{R}\), which the quantum algorithm aims to minimize. The weights and biases take the values \(2\sigma_{i}-1\in\{-1,1\}\). The simplest and currently most experimentally friendly approach to carry out this optimization using quantum resources is through a VQA. VQA employs a classical optimizer acting on a parameterized quantum circuit, with the purpose of finding solutions to a problem encoded in an objective function, which in our setting corresponds to \(C\left(\mathbf{w}\right)\). A key element to a VQA is the encoding of the objective function, achieved by promoting Eq. (2) to a quantum operator. A natural choice is to promote the parameters of the BiNN to a set of Pauli matrices \(\mathbf{w}\rightarrow\mathbf{\hat{\sigma}_{z}}=(\hat{\sigma}_{1}^{z},\hat{\sigma}_{2}^{z},\ldots,\hat{\sigma}_{N}^{z})\), which, in turn, promotes the objective function \(C\left(\mathbf{w}\right)\) to an operator \(\hat{C}\). Here \(\hat{\sigma}_{i}^{z}\) is the Pauli matrix \(\begin{pmatrix}1&0\\ 0&-1\end{pmatrix}\) acting on qubit \(i\), the diagonal cost operator \[\hat{C}=\begin{pmatrix}C(\mathbf{w}_{1})&0&\cdots&0\\ 0&C(\mathbf{w}_{2})&\cdots&0\\ \vdots&\vdots&\ddots&\vdots\\ 0&0&\cdots&C(\mathbf{w}_{2^{N}})\end{pmatrix}, \tag{3}\] and \(\mathbf{w}_{1},\ldots,\mathbf{w}_{2^{N}}\) are all the \(2^{N}\) possible BiNN. This encoding is flexible and other operator choices, including off-diagonal operators, are possible. We construct a quantum hypernetwork \(\ket{\Psi}\) through a parameterized quantum circuit \(U(\mathbf{\theta})\) with continuous parameters \(\mathbf{\theta}\) such that \(\ket{\Psi}\rightarrow\ket{\Psi_{\mathbf{\theta}}}=U(\mathbf{\theta})\ket{0}^{ \mathbf{\bigotimes}\,n}\). We aim at finding solutions to the training of the BiNN solving for \[\mathbf{\theta}^{*}=\arg\min_{\mathbf{\theta}}\ E\left(\mathbf{\theta}\right), \tag{4}\] where \(E\left(\mathbf{\theta}\right)=\bra{\Psi_{\mathbf{\theta}}}\hat{C}\ket{\Psi_{\mathbf{ \theta}}}\). From an ML perspective, this approach can be understood as a stochastic relaxation of the discrete optimization problem. That is, instead of directly searching for the optimal binary parameters, we introduce a joint distribution over the parameters and architectural choices encoded by the quantum state \(\ket{\Psi_{\mathbf{\theta}}}\). Measuring the quantum state (see Fig. 1(b)) produces trial binary parameters and architectural choices and gives access to estimates of the learning objective \(E(\mathbf{\theta})\). We express \(U(\mathbf{\theta})\) as the product of \(L\) unitary blocks of the form \(U(\mathbf{\theta})=U_{L}\left(\mathbf{\theta}_{L}\right)\cdots U_{1}\left(\mathbf{\theta}_ {1}\right)\). We restrict ourselves to one of the simplest and most widely available circuits in current quantum computing platforms, namely those implementable in quantum devices with a linear connectivity: \[U_{k}\left(\mathbf{\theta}_{k}\right) =\prod_{m=1+k\text{ mod }2,\text{ step }2}^{N-2+k\text{ mod }2}\text{ CX}(m,m+1) \tag{5}\] \[\prod_{j=1}^{N}\text{RY}(j,\theta_{y,j,k})\text{RZ}(j,\theta_{z, j,k}).\] Here \(\text{CX}(m,j)\) denotes a control-X gate acting on the control \(m\) and target \(j\) qubits. The parameterized single-qubit unitaries \(\text{RY}(j,\theta_{y,j,k})\) and \(\text{RZ}(j,\theta_{z,j,k})\) at block \(k\) are given by \(e^{i\theta_{y,j,k}\theta_{j}^{y}}\) and \(e^{i\theta_{z,j,k}\theta_{j}^{z}}\), respectively. The symbol \(i\) is the imaginary unit. The parameters of the circuit are \(\mathbf{\theta}=\{\theta_{\alpha,j,k}\}\), where \(\alpha=y,z\), \(j=1,\ldots,N\), and \(k=1,\ldots,L\). We illustrate a quantum circuit with \(L=2\) and \(N=4\) in Fig. 1(b), where the green boxes synthesize the combined effect of \(\text{RY}(j,\theta_{y,j,k})\) and \(\text{RZ}(j,\theta_{z,j,k})\). In our experiments, we consider even \(L=2\times N_{\text{layer}}\) and define a layer (see encircled blocks in Fig. 1(b)) as 2 unitary blocks, so that the circuit in Fig. 1(b) contains \(N_{\text{layer}}=1\) layers. In addition, we also consider one of the simplest possible quantum states, namely an entanglement-free product state ansatz, where \(U(\mathbf{\theta})_{\text{prod.}}=\prod_{j=1}^{N}\text{RY}(j,\theta_{y,j,1})\text{ RZ}(j,\theta_{z,j,1})\). The latter have been shown effective at solving quadratic unconstrained binary optimization problems [24; 25]. ### Optimization We optimize the Eq. (4) via a gradient-based method where \(E\left(\mathbf{\theta}\right)\) and its gradient \(\nabla_{\mathbf{\theta}}E\left(\mathbf{\theta}\right)\) are evaluated through measuring the quantum hypernetwork \(\ket{\Psi_{\mathbf{\theta}}}\) followed by a classical optimizer that iteratively updates its parameters. At the end of the optimization, we expect that \(\ket{\Psi_{\mathbf{\theta}}}\) assigns high amplitudes to BiNNs with low cost function, i.e., good architectural choices, parameters and hyperparameters. Figure 1: **Quantum HyperNetworks** (a) The different BiNN’s configurations can be encoded in the computational basis \(\mathbf{\sigma}\) of a quantum state \(\ket{\Psi}\), which is defines a quantum hypernetwork. (b) The quantum hypernetwork can be constructed via a parameterized quantum circuit which upon measuring produces BiNN configurations. Different qubits \(\sigma_{i}\) are interpreted as parameters, hyperparameters and architectural choices of the BiNN. In an experimental setting, the estimation of the gradients \(\nabla_{\mathbf{\theta}}E\left(\mathbf{\theta}\right)\) makes use of the parameter-shift rule [26, 27]. It follows that the entries of the gradient are given by \[\frac{\partial E\left(\mathbf{\theta}\right)}{\partial\theta_{\alpha,j,k}}=\frac{1} {2}\left[E(\mathbf{\theta}_{\alpha,j,k}^{+})-E(\mathbf{\theta}_{\alpha,j,k}^{-}) \right], \tag{6}\] where the elements of the shifted parameter vector \(\mathbf{\theta}_{\alpha jk}^{\pm}\) are such that \(\theta_{\beta,m,l}^{\pm}=\theta_{\beta,m,l}\pm\frac{\pi}{2}\delta_{\alpha, \beta}\delta_{m,j}\delta_{k,l}\). Thus, the calculation of the gradient corresponds to the evaluation of a shifted version of the objective function \(E(\mathbf{\theta})\), which can be estimated by preparing and measuring the same quantum circuit used to compute the original objective with shifted circuit parameters. In a quantum experiment, functions of the form \(E(\mathbf{\theta})\) are estimated via averages over the measurement outcomes of projective measurements, e.g., \[E\left(\mathbf{\theta}\right) =\langle\Psi_{\mathbf{\theta}}|\hat{C}|\Psi_{\mathbf{\theta}}\rangle \tag{7}\] \[=\sum_{\sigma_{1},\sigma_{2},\ldots,\sigma_{N}}|\Psi_{\mathbf{ \theta}}(\sigma_{1},\sigma_{2},\ldots,\sigma_{N})|^{2}C(\sigma_{1},\sigma_{2 },\ldots,\sigma_{N})\] \[=\mathbb{E}_{\mathbf{\sigma}\sim|\Psi_{\mathbf{\theta}}|^{2}}\left[C( \mathbf{\sigma})\right]\approx\frac{1}{N_{qc}}\sum_{i=1}^{N_{qc}}C(\mathbf{\sigma}_{i}),\] where \(N_{qc}\) configurations \(\mathbf{\sigma}_{i}\) are distributed according to \(|\Psi_{\mathbf{\theta}}|^{2}\). The estimate of \(E(\mathbf{\theta})\approx\frac{1}{N_{qc}}\sum_{i=1}^{N_{qc}}C(\mathbf{\sigma}_{i})\) is evaluated classically by computing \(C(\mathbf{\sigma})\) on the BiNNs \(\mathbf{\sigma}\sim|\Psi_{\mathbf{\theta}}|^{2}\) sampled by the quantum computer. In contrast, we use classical simulations based on tensor networks (TN) [28] implemented through the PastaQ.jl package [29]. The TN techniques allow for the exact evaluation of expectations and their gradients through automatic differentiation (AD) provided by the package Zygote.jl [30]. To optimize \(E(\mathbf{\theta})\) we use the limited-memory Broyden-Fletcher-Goldfarb-Shanno (LBFGS) algorithm [31]. ### Gaussian dataset with a choice of activation We first consider the training of a small BiNN binary classifier with a two-dimensional input, a three-dimensional hidden layer, and a single output depicted in Fig. 2(a). We would like to simultaneously train the parameters, as well as an architectural choice, here the selection of activation function \(f\), which in our example can be a sigmoid or a rectified linear unit (ReLU): \[f(\mathbf{x};\sigma)=\begin{cases}S(\mathbf{x})&\text{if}\ \sigma=0\\ \text{ReLU}(\mathbf{x})&\text{if}\ \sigma=1.\end{cases}\] Here \(S(\mathbf{x})=1/(1+e^{-\mathbf{x}})\) and \(\text{ReLU}(\mathbf{x})=\max(\mathbf{x},0)\) are applied element-wise on the components of the arrays \(\mathbf{x}\). The activation function in the output layer is \(f_{\text{out}}(\mathbf{x})=S(\mathbf{x})\). We train the BiNN on a toy dataset drawn from a two-dimensional mixture of 4 Gaussian distributions shown in Fig. 2(b). The samples are drawn from the red (squares) Gaussian with probability \(1/2\) and from each of the blue (circles) Gaussians with probability \(1/6\). Each data point is labeled according to whether it was drawn from the red or blue Gaussians, and we aim to train the BiNNs to classify any point in the plane accordingly. The BiNN is characterized by 13 binary parameters and a binary variable \(\sigma_{14}\) codifying the architectural choice of activation function, i.e. \(N=14\) variables. For small BiNNs, a training dataset, and an objective function \(C\left(\mathbf{w}\right)\), it is possible to compute the optimal BiNN configuration by enumerating all the \(2^{N}\) BiNNs and choosing the one with the smallest \(C\left(\mathbf{w}\right)\). In our example, the best configuration yields the decision boundary shown in Fig. 2(b), where the optimal BiNN classifies points in the green region as coming from the red Gaussian and points in the orange region as coming from the blue Gaussians. The optimal choice of activation function is the ReLU. Now we explore solving the problem via quantum optimization. We consider the circuit ansatz shown in Fig. 1 with varying number of layers \(N_{\text{layer}}=1,2,3,4\), as well as a product state ansatz. We randomly and independently initialize all the parameters of the circuits from a uniform distribu Figure 2: **BiNNs applied to a Gaussian dataset.** (a) A BiNN with two dimensional input, a three dimensional hidden layer, and one output. (b) The decision boundary drawn by our BiNN after training on a two-dimensional mixture of 4 Gaussian distributions with two labels. (c) A kernel density estimation (KDE) of the probability that a quantum circuit (product state and with different number of layers) achieves an average cost \(E(\theta)\). The bottom row of this panel corresponds to the density of configurations with a cost \(C(\mathbf{w})\) after filtering for low-cost configurations. (d) The probability of finding the lowest objective \(C(\mathbf{w^{\star}})\) within \(\epsilon=0.03\) for the different quantum circuits. tion \(\theta_{\alpha,i,k}\sim U(0,2\pi)\). We first note that all the circuit ansatze have sufficient expressive power to represent the optimal solution, which is simply the product state. In our numerical experiments, we find that all of our ansatze can find the optimal solution, including the product state ansatz, with varying degree of success. The success rate of the optimization depends on the interplay between the initialization of the circuit parameters and the depth of the circuit. To understand the typical behaviour of the optimization procedure and to shed light onto the role of the circuit depth, we perform the circuit optimization for a number \(N_{\mathrm{optim}}=200\) of independent initializations. In Fig. 2(c) we summarize the results of these optimizations through a kernel density estimation (KDE) of the probability density function that the optimization finds an average objective \(E(\mathbf{\theta})\) for different circuit depths. In addition, through full enumeration, we compute a KDE of the 200 top performing BiNN with the lowest \(C(\mathbf{w})\) (the bottom row of Fig. 2(c)). This can be interpreted as the density of configurations at a particular "\(E\) level" that a BiNN can take, and is analogous to the density of states in condensed matter physics. Since we only take the 200 lowest objective function BiNNs, this means that the probability assigned by the KDE to each value \(C(\mathbf{w})\) is significantly overestimated. We observe that most solutions found by all circuits considered here are concentrated near the optimal configuration of weights and hyperparameters \(\mathbf{w}^{*}\), for which \(C(\mathbf{w}^{*})\approx 0.008\) (see the encircled densities in Fig. 2(c)). This is in spite of the fact that the density of solutions with low \(C\) is significantly small, which indicates that the quantum optimization is effective. However, the frequency with which solutions with low objective function are found varies as a function of the circuit depth. To probe this behaviour, we estimate the probability that a certain circuit depth finds solutions with precision \(E(\mathbf{\theta}-C(\mathbf{w}^{*})<\epsilon)\) by counting the solutions found by the VQA meeting the precision condition. This is shown in Fig. 2(d). As noted earlier, even a product state circuit finds accurate solutions. A circuit with 1 layer (see Fig. 1) doubles the number of variational parameters and decreases the probability to find accurate solutions which indicates that the optimization of the variational parameters \(\mathbf{\theta}\) is more prone to getting stuck in local minima than a product state circuit. Upon increasing the depth, we note that for 2 and 3 layers, the probability to find accurate solutions reaches a maximum but eventually decreases for 4 layers. Circuits with layers composed of entangling gates and multiple (optimally for \(N_{\mathrm{layer}}=3,4\)) layers of parameterized single-qubit gates provide an advantage as these enhance the success of finding good solutions with respect to a product state. ### Gaussian dataset with a choice of activation and dimension of hidden layer Next we consider the simultaneous optimization of the BiNN's parameters, a hyperparameter (hidden layer dimension \(N_{hid}\)) and the architectural choice non-linearity. We encode the choice of \(N_{hid}\in\{2,3\}\) through an additional qubit \(\sigma_{N_{hid}}\). A wider set of choices of \(N_{hid}\) is possible through the use of more qubits. We encode these choices through a single function \(\mathrm{NN}(\mathbf{x}_{i};\mathbf{w})\) that evaluates the BiNN's output as a function of weights and biases, and the choices of non-linearity and \(N_{hid}\). The choice of qubit assignment of the BiNN's parameters and nonlinearity are presented in Fig. 3(a), where the qubits encircled in blue are left unused in the evaluation of the BiNN output for \(N_{hid}=2\) but are used for \(N_{hid}=3\). The results of the optimization procedure are displayed in Fig. 3(b-c), which display a behaviour similar to the experiments in Fig. 2(c-d). While the optimization is successful, the probability of finding low-energy solutions is reduced with respect to the original optimization task in Fig. 2. As noted in Fig. 2, while even a product state circuit finds accurate solutions with high probability, there exists an optimal circuit depth that significantly enhances the probability of a finding the optimal solution, eventually decreasing upon further increasing depth. This effect is due to the optimization becoming Figure 3: **BiNNs with two layers with width and nonlinearity hyperparameters on the Gaussian toy dataset.** (a) An illustration of the weights, biases, hyperparameters within a flattened list for two different numbers of hidden neurons \(N_{hid}=2,3\). Blue color means that the corresponding parameter is not used. (b) Similarly to Fig. 2(c), we show the KDE for different quantum circuits’ objectives in the top five rows, as well as the density of configurations in the bottom row. (c) In a similar fashion to Fig. 2(d), we show the probability of success within a threshold \(\epsilon=0.03\) for each quantum circuit. more prone to finding local minima and not to the ansatz' expressive power, as deeper circuits are more expressive than shallower ones. ### Scaled-down MNIST Finally, to investigate the performance of quantum optimization for a representative dataset, we consider training a simple logistic regression model with binary parameters and a cross-entropy loss, as shown in Fig. 4(a). The training data corresponds to a subset of MNIST images of zeros and ones scaled down to \(L\times L=4\times 4\) pixels. We explore solving the training problem via quantum optimization with the circuit depths \(N_{\text{layer}}=1,2,3\) as well as with a product state circuit. As in our previous example, we run the optimization for \(N_{\text{optim}}=200\) independent initializations. The results are shown in Fig. 4(b). While optimization via a product state ansatz attains optimal solutions with nearly 60% success rate, the rate is enhanced for circuits with an optimal number of entangling layers, which display a 90% chance of success for \(N_{\text{layer}}=2,3\). This backs up our previous observation that entanglement plays an important role in the optimization procedure. As seen in Fig. 4(b-c) our circuits enhance the probability of finding the optimal solution going beyond simply increasing of the expressive power of the circuit ansatz. ### Fourier analysis of \(C\) In spite of the similarities between the MNIST and Gaussian mixture examples in terms of problem size \(N\) and task, we note that the probability of finding solutions with low cost function is higher for the MNIST task. To shed light onto the origin of these differences in optimization performance, we examine the structure of the objective functions \(C\) through a Fourier analysis. As pointed out by Torta _et al._ [19], due to the non-linearities of the BiNNs and the loss function \(\mathcal{L}\), the objective function \(C\) and its quantum extension \(\hat{C}\) may contain highly non-local, all-to-all multi-variable interactions. Beyond understanding the differences in optimization performances across different tasks, the locality of \(C\) plays an important role in the optimization of the circuit as a highly non-local \(C\) may lead to exponentially vanishing gradients in Eq. 6, which can severely impede the optimization of the circuit [32]. The Fourier transform of the real boolean function \(C\) and its quantum extension \(\hat{C}\) provides a natural strategy to investigate the locality of the objective function \(C\). First, \(\hat{C}\) can be represented by an Ising Hamiltonian given by sums of tensor products of Pauli \(\sigma_{i}^{z}\) operators weighted by \(C\)'s Fourier expansion coefficients [33]. Thus, for an \(N\)-bit real function \(C:\{0,1\}^{N}\rightarrow\mathbb{R}\), we can decompose \(\hat{C}|\sigma\rangle=C(\sigma)|\sigma\rangle\) as \[\hat{C}=\sum_{\hat{\sigma}_{1},\dots,\hat{\sigma}_{N}}f(\hat{\sigma}_{1},\dots \hat{\sigma}_{N})\bigotimes_{i=1}^{N}\hat{\sigma}_{i}, \tag{8}\] where \(\hat{\sigma}_{i}=\{\mathbf{1},\hat{\sigma}_{i}^{z}\}\). Here the Fourier coefficients are given by \(f(\hat{\sigma}_{1},\dots\hat{\sigma}_{N})=\frac{1}{2^{N}}\text{Tr}\left[\hat{ C}\otimes_{i=1}^{N}\hat{\sigma}_{i}\right]\in\mathbb{R}\). This follows from the fact that the tensor products of Pauli operators and the identity form an orthogonal basis for the vector space of \(2^{N}\times 2^{N}\) complex matrices, in particular the subspace of diagonal operators such as \(\hat{C}\), for which only the \(2\times 2\) identity matrix \(\mathbf{1}\) and \(\sigma_{i}^{z}\) are required in the expansion. We evaluate the \(N\)-bit function \(f(\hat{\sigma}_{1},\dots\hat{\sigma}_{N})\) and define the amplitude \[W(S)=\sum_{\hat{\sigma}_{1},\dots\hat{\sigma}_{N}}|f(\hat{\sigma}_{1},\dots \hat{\sigma}_{N})|^{2}\delta_{S,S(\hat{\sigma}_{1},\dots\hat{\sigma}_{N})}. \tag{9}\] as the total sum of the Fourier coefficients squared associated with diagonal Pauli strings with weight \(S\). Here the weight \(S(\hat{\sigma}_{1},\dots\hat{\sigma}_{N})\in\{0..N\}\) of an \(N\)-length Pauli string \(\bigotimes_{i=1}^{N}\hat{\sigma}_{i}\) corresponds to the number of non-identity Pauli matrices in it. The structure of the function \(W(S)\) reflects the locality of the effective Ising Hamiltonian. For instance, when \(W(S)\neq 0\) only for \(S=0,1\) means that the effective Ising Hamiltonian corresponds to a set of local fields acting independently on the variables \(\sigma_{i}\). In contrast, if \(W(S)\neq 0\) for \(S=0,1,2\) means that the Ising Hamiltonian contains only pairwise interactions and local fields, etc. Speaking Figure 4: **BiNNs for the reduced MNIST dataset.** (a) The BiNN used to classify the reduced MNIST dataset. (b) A KDE of \(E(\mathbf{\theta})\) resulting from repeating the optimization procedure 200 times. The optimizations are performed for a product state, as well as for circuits with 1,2, and 3 layers. We also show the density of configurations with a cost \(C(\mathbf{w})\). (c) A plot of the probability of success within a threshold \(\epsilon=5\times 10^{-5}\) for the different quantum circuit architectures. informally, \(W(S)\) defines how well we can approximate \(\hat{C}\) with a polynomial of degree \(S\). In Fig. 5(a-c) we show \(W(S)\) for the tasks of classification of Gaussians with function activation search (a), Gaussians with activation function and hidden dimension search (b), and logistic regression of MNIST with binary weights (c). For all systems, the highest \(W(S)\) happens at \(S=0\), which corresponds to a simple constant shift in the effective Hamiltonian. As the weight \(S\) increases, the amplitude \(W(S)\) is seen to decrease exponentially fast even for moderate \(S\). This means that all the objectives \(C\) are essentially local, which bodes well for circuit optimization as the locality of \(C\) will not induce barren plateaus [32]. For the Gaussian mixture tasks, we see that the most important contributions to \(W\) occur at \(S=2,3\) with the highest values occurring at \(S=2\), which means that the effective Hamiltonian is nearly an Ising Hamiltonian with pairwise interactions. Instead, for MNIST the most dominant non-trivial contribution comes from \(S=1\), which means that the effective Hamiltonian is a set of local fields acting on the binary weights of the model. This in part explains why the quantum optimization of the MNIST task is superior since the solution of a fully independent set of binary variables coupled to local fields can be found by independently optimizing the energy of each binary variable. This means that a product state is perfectly suited to find it with high probability, as we have found. Additionally, these observations support the idea that short-depth circuits with one- and two-qubit gates can tackle the optimization of the BiNNs without resorting to full implementations of unitaries of the form \(e^{i\hat{C}}\), which have been typically prescribed in earlier proposals for training neural networks using quantum computers [14; 19]. ### Overfitting and model selection In contrast with the standard ML workflow where the hyperparameter and architectural choices are optimized based on the model's performance on a validation set, we have defined an augmented model encapsulating the parameters, hyperparameters and architecture of a neural network, which we jointly optimize on a training dataset. We now briefly explore the generalization and overfitting behaviour of the augmented model and investigate how the resulting trends can guide the selection of an optimal augmented model. As an example, we revisit the training of a BiNN with architectural choice of non-linearity to the the mixture of Gaussians dataset as a testbed to explore overfitting and generalization. To amplify overfitting, we simultaneously bring the Gaussians spatially closer to each other with respect to the example in Fig. 2 and decrease the size of the training dataset. As a function of the training iterations, we investigate the behaviour of \(\overline{E(\mathbf{\theta})}\), which is an average of \(E(\mathbf{\theta})\) over 100 independent realizations of training datasets of sizes \(N_{s}=2,4,6,8\). We also consider training datasets with \(N_{s}=10^{3}\), significantly larger than the dimensionality of the input (\(d=2\)). We fix the total number of circuit training iterations to 50 and the choose a large validation set of size 1000. Overall, we find that the augmented model adheres to the anticipated behaviour of an ML model. In all of our examples, the average training curves on the training sets are monotonically decreasing. For small training sets, e.g. \(N_{s}=2\), the validation set curve initially decreases and later on increases, which suggests that the simple "early stopping" strategy may be employed to choose optimal models located at the minimum of the validation curve as a way to avoid overfitting [34]. For \(N_{s}>2\), the validation curves exhibit a monotonic decreasing behaviour as a function of training iterations, which is the typical dynamics for large training sets \(N_{s}\) where the dynamics is less prone to overfitting. As expected, the generalization gap, i.e. the difference between the validation and training set curves near the end of the training, decreases quickly as a function of the \(N_{s}\) and is seen to grow small for large datasets \(N_{s}=10^{3}\), as expected. ## III Discussion We have introduced quantum hypernetworks, variational quantum circuits that search for optimal BiNNs over an augmented space comprising its parameters, hyperparameters, and any desired architectural choices, in Figure 5: **Fourier analysis of \(\hat{C}\)**. The amplitudes \(W(S)\) associated with Pauli string weights \(S\) for (a) the classification of Gaussians with activation function search, (b) the classification of gaussians with the hidden neurons and activation function search, (c) the logistic regression of reduced MNIST. a single optimization loop. Using classical simulations, we have shown that quantum hypernetworks effectively find optimal parameters, hyperparmeters and architectural choices with high probability on toy classification problems including a two-dimensional Gaussian dataset and a scaled-down version of the MNIST handwritten digits. We find that the probability of finding performant BiNNs is tied to the circuit depth, and consequently, to the amount of entanglement supported by the circuit. This indicates that entanglement and quantum effects play a role and decrease the probability that the optimization finds poor local minima. Even though expressing quantum hypernetworks in terms circuits with a simple linear connectivity have proven successful in our setting, other ansatze constructed considering knowledge of the problem, e.g., circuit designs adaptively grown guided by the objective function and gate availability [35], may simultaneously shorten the circuit depth and significantly improve the effectiveness and scalability of our approach. To explore training large models beyond what's feasible with limited-size quantum processors, it is natural to consider a layer-by-layer optimization of the BiNN, which would operate analogously to the density matrix renormalization group algorithm [36]. Additionally, distributed quantum computing [37], as well as a multi-basis encoding of the problem [38], may extend the scalability of our approach to larger ML models. The application of fault tolerant quantum algorithms may also prove useful to the success of the unified training strategy presented here and may lead to provable speedups [17]. Our approach naturally connects with Bayesian inference as the the quantum hypernetwork \(|\Psi_{\mathbf{\theta}}\rangle\) defines a probability distribution over the weights of the BiNNs, a defining property of a Bayesian neural network. A full Bayesian approach prescribes the evaluation of the posterior distribution over the parameters, which is fundamentally intractable in our setting. It may be possible, however, to estimate the evidence lower bound [39] by performing a decomposition of the circuit distribution, taking inspiration from Titsias and Ruiz [40], Molchanov _et al._[41]. Additionally, although we have arrived at our unified strategy through a variational quantum optimization lens, our approach suggests that it is possible to introduce classical or quantum-inspired hypernetworks based on, e.g., recurrent neural networks or product states [25; 42], where a variational Bayesian approach to BiNN optimization is possible. Quantum computers are currently reaching the ability to vastly outperform supercomputers' energy efficiency by many orders of magnitude over classical computers [43], so it stands to reason that the efficiency and energetic consumption of complex tasks in the ML workflow such as neural network training and hyperparameter search may be significantly reduced through the use of quantum computational resources. A combination of the energy efficiency of BiNN's classical operation with the energetic advantages of quantum devices for their training along with the unified single-loop optimization introduced here may offer a compelling approach to train large ML models with a reduced carbon footprint in the future. ###### Acknowledgements. We acknowledge Maciej Koch-Janusz, Roeland Wiersema, Roger Melko, and Behnam Javanparast for discussions. JC acknowledges support from the Natural Sciences and Engineering Research Council (NSERC), the Shared Hierarchical Academic Research Computing Network (SHARCNET), Compute Canada, and the Canadian Institute for Advanced Research (CIFAR) AI chair program. Resources used in preparing this research were provided, in part, by the Province of Ontario, the Government of Canada through CIFAR, and companies sponsoring the Vector Institute www.vectorinstitute.ai/#partners.
2310.18918
Hyperbolic Graph Neural Networks at Scale: A Meta Learning Approach
The progress in hyperbolic neural networks (HNNs) research is hindered by their absence of inductive bias mechanisms, which are essential for generalizing to new tasks and facilitating scalable learning over large datasets. In this paper, we aim to alleviate these issues by learning generalizable inductive biases from the nodes' local subgraph and transfer them for faster learning over new subgraphs with a disjoint set of nodes, edges, and labels in a few-shot setting. We introduce a novel method, Hyperbolic GRAph Meta Learner (H-GRAM), that, for the tasks of node classification and link prediction, learns transferable information from a set of support local subgraphs in the form of hyperbolic meta gradients and label hyperbolic protonets to enable faster learning over a query set of new tasks dealing with disjoint subgraphs. Furthermore, we show that an extension of our meta-learning framework also mitigates the scalability challenges seen in HNNs faced by existing approaches. Our comparative analysis shows that H-GRAM effectively learns and transfers information in multiple challenging few-shot settings compared to other state-of-the-art baselines. Additionally, we demonstrate that, unlike standard HNNs, our approach is able to scale over large graph datasets and improve performance over its Euclidean counterparts.
Nurendra Choudhary, Nikhil Rao, Chandan K. Reddy
2023-10-29T06:11:49Z
http://arxiv.org/abs/2310.18918v1
# Hyperbolic Graph Neural Networks at Scale: ###### Abstract The progress in hyperbolic neural networks (HNNs) research is hindered by their absence of inductive bias mechanisms, which are essential for generalizing to new tasks and facilitating scalable learning over large datasets. In this paper, we aim to alleviate these issues by learning generalizable inductive biases from the nodes' local subgraph and transfer them for faster learning over new subgraphs with a disjoint set of nodes, edges, and labels in a few-shot setting. We introduce a novel method, Hyperbolic GRAph Meta Learner (H-GRAM), that, for the tasks of node classification and link prediction, learns transferable information from a set of support local subgraphs in the form of hyperbolic meta gradients and label hyperbolic promoters to enable faster learning over a query set of new tasks dealing with disjoint subgraphs. Furthermore, we show that an extension of our meta-learning framework also mitigates the scalability challenges seen in HNNs faced by existing approaches. Our comparative analysis shows that H-GRAM effectively learns and transfers information in multiple challenging few-shot settings compared to other state-of-the-art baselines. Additionally, we demonstrate that, unlike standard HNNs, our approach is able to scale over large graph datasets and improve performance over its Euclidean counterparts. ## 1 Introduction Graphs are extensively used in various applications, including image processing, natural language processing, chemistry, and bioinformatics. With modern graph datasets ranging from hundreds of thousands to billions of nodes, research in the graph domain has shifted towards larger and more complex graphs, e.g., the nodes and edges in the traditional Cora dataset [29] are in the order of \(10^{3}\), whereas, the more recent OGBN datasets [17] are in the order of \(10^{6}\). However, despite their potential, Hyperbolic Neural Networks (HNNs), which capture the hierarchy of graphs in hyperbolic space, have struggled to scale up with the increasing size and complexity of modern datasets. HNNs have outperformed their Euclidean counterparts by taking advantage of the inherent hierarchy present in many modern datasets [4; 10; 13]. Unlike a standard Graph Neural Network (GNN), a HNN learns node representations based on an "anchor" or a "root" node for the entire graph, and the operations needed to learn these embeddings are a function of this root node. Specifically, HNN formulations [13] depend on the global origin (root node) for several transformation operations (such as Mobius addition, Mobius multiplication, and others), and hence focusing on subgraph structures to learn representations becomes meaningless when their relationship to the root node is not considered. Thus, state-of-the-art HNNs such as HGCN [4], HAT [15], and HypE [8] require access to the entire dataset to learn representations, and hence only scale to experimental datasets (with \(\approx\)\(10^{3}\) nodes). Despite this major drawback, HNNs have shown impressive performance on several research domains including recommendation systems [32], e-commerce [9], natural language processing [11], and knowledge graphs [5; 8]. It is thus imperative that one develops methods to scale HNNs to larger datasets, so as to realize their full potential. To this end, we introduce a novel method, **Hyperbolic GRAph Meta Learner (H-GRAM)**, that utilizes meta-learning to learn infor mation from local subgraphs for HNNs and transfer it for faster learning on a disjoint set of nodes, edges, and labels contained in the larger graph. As a consequence of meta-learning, H-GRAM also achieves several desirable benefits that extend HNNs' applicability including the ability to transfer information on new graphs (inductive learning), elimination of over-smoothing, and few-shot learning. We experimentally show that H-GRAM can scale to graphs of size \(\mathcal{O}(10^{6})\), which is \(\mathcal{O}(10^{3})\) times larger than previous state-of-the-art HNNs. To the best of our knowledge, there are no other methods that can scale HNNs to datasets of this size. Recent research has shown that both node-level and edge-level tasks only depend on the local neighborhood for evidence of prediction [18; 19; 42]. Inspired by the insights from such research, our model handles large graph datasets using their node-centric subgraph partitions, where each subgraph consists of a root node and the \(k\)-hop neighborhood around it. In H-GRAM, the HNN formulations establish the root node as the local origin to encode the subgraph. We theoretically show that, due to the locality of tangent space transformations in HNNs (more details in Section 3), the evidence for a node's prediction can predominantly be found in the immediate neighborhood. Thus, the subgraph encodings do not lose a significant amount of feature information despite not having access to a "global" root node. However, due to the node-centric graph partitioning, the subgraphs are non-exhaustive, i.e., they do not contain all the nodes, edges, and labels, as previously assumed by HNNs. Thus, to overcome the issue of non-exhaustive subgraphs, we formulate four meta-learning problems (illustrated in Figure 1) that learn inductive biases on a support set and transfer it for faster learning on a query set with disjoint nodes, edges, or labels. Our model learns inductive biases in the meta-training phase, which contains two steps - HNN update and meta update. HNN updates are regular stochastic gradient descent steps based on the loss function for each support task. The updated HNN parameters are used to calculate the loss on query tasks and the gradients are accumulated into a meta-gradient for the meta update. In the meta-testing phase, the models are evaluated on query tasks with parameters post the meta updates, as this snapshot of the model is the most adaptable for faster learning in a few-shot setting. Our main contributions are as follows: Figure 1: Meta-learning on hyperbolic neural networks. The procedure consists of two phases - (i) meta-training to update the parameters of the HNNs and learn inductive biases (meta gradients and label protonets), and (ii) meta-testing that initializes the HNNs with the inductive biases for faster learning over new graphs with a disjoint set of nodes, edges, or labels. 1. We theoretically prove that HNNs rely on the nodes' local neighborhood for evidence in prediction, as well as, formulate HNNs to encode node-centric local subgraphs with root nodes as the local origin using the locality of tangent space transformations. 2. We develop Hyperbolic GRAph Meta Learner (H-GRAM), a novel method that learns meta information (as meta gradients and label protents) from local subgraphs and generalize it to new graphs with a disjoint set of nodes, edges, and labels. Our experiments show that H-GRAM can be used to generalize information from subgraph partitions, thus, enabling scalability. 3. Our analysis on a diverse set of datasets demonstrates that our meta-learning setup also solves several challenges in HNNs including inductive learning, elimination of over-smoothing, and few-shot learning in several challenging scenarios. ## 2 Related Work This section reviews the relevant work in the areas of hyperbolic neural networks and meta learning. **Hyperbolic Neural Networks:** Due to their ability to efficiently encode tree-like structures, hyperbolic space has been a significant development in the modeling of hierarchical datasets [43; 44]. Among its different isometric interpretations, the Poincare ball model is the most popular one and has been applied in several HNN formulations of Euclidean networks including the recurrent (HGRU [13]), convolution (HGCN [4]), and attention layers (HAT [15]). As a result of their performance gains on hierarchical graphs, the formulations have also been extended to applications in knowledge graphs for efficiently encoding the hierarchical relations in different tasks such as representation learning (MuRP [1], AttH [5]) and logical reasoning (HypE [8]). However, the above approaches have been designed for experimental datasets with a relatively small number of nodes (in the order of \(10^{3}\)), and do not scale to real-world datasets. Hence, we have designed H-GRAM as a meta-learning algorithm to translate the performance gains of HNNs to large datasets in a scalable manner. **Graph Meta-learning:** Few-shot meta-learning transfers knowledge from prior tasks for faster learning over new tasks with few labels. Due to their wide applicability, they have been adopted in several domains including computer vision [14; 34], natural language processing [22] and, more recently, graphs [18; 39]. One early approach in graph meta-learning is Gated Propagation Networks [23] which learns to propagate information between label prototypes to improve the information available while learning new related labels. Subsequent developments such as MetaR [7], Meta-NA [41] and G-Matching [39] relied on metric-based meta learning algorithms for relational graphs, network alignment and generic graphs, respectively. These approaches show impressive performance on few-shot learning, but are only defined for single graphs. G-Meta [18] extends the metric-based techniques to handle multiple graphs with disjoint labels. However, the method processes information from local subgraphs in a Euclidean GNN, and thus, is not as capable as hyperbolic networks in encoding tree-like structures. Thus, we model H-GRAM to encode hierarchical information from local subgraphs and transfer it to new subgraphs with disjoint nodes, edges, and labels. ## 3 The Proposed H-GRAM Model In this section, we define the problem setup for different meta-learning scenarios and describe our proposed model, H-GRAM, illustrated in Figure 2. For better clarity, we explain the problem setup for node classification and use HGCN as the exemplar HNN model. However, the provided setup can be extended to link prediction or to other HNN models, which we have evaluated in our experiments. The preliminaries of hyperbolic operations and meta-learning are provided in Appendix A. ### Problem Setup Our problem consists of a group of tasks \(\mathcal{T}_{i}\in\mathcal{T}\) which are divided into a support set \(\mathcal{T}^{s}\) and query set \(\mathcal{T}^{q}\), where \(\mathcal{T}^{s}\cap\mathcal{T}^{q}=\phi\). Furthermore, each task \(\mathcal{T}_{i}\) is a batch of node-centric subgraphs \(S_{u}\) with a corresponding label \(Y_{u}\) (class of root node in node classification or root link in link prediction). The subgraphs \(S_{u}\) could be the partitions derived from a single graph or multiple graphs, both denoted by \(\mathcal{G}^{\cup}=\mathcal{G}^{s}\cup\mathcal{G}^{q}\). We also define \(Y_{s}=\{Y_{u}\in\mathcal{T}^{s}\}\) and \(Y_{q}=\{Y_{u}\in\mathcal{T}^{q}\}\) as the set of labels in the support and query set respectively. The primary goal of meta-learning is to learn a predictor using the support set, \(P_{\theta_{*}}(Y_{s}|\mathcal{T}^{s})\) such that the model can quickly learn a predictor \(P_{\theta}(Y_{s}|\mathcal{T}^{s})\) on the query set. Following literature in this area [18], the problem categories are defined as follows: 1. **Single graph, shared labels \(\langle\mathbf{SG,SL}\rangle\)**: The objective is to learn the meta-learning model \(P_{\theta_{*}\rightarrow\theta}\), where \(Y_{s}=Y_{q}\) and \(|\mathcal{G}^{s}|=|\mathcal{G}^{q}|=1\). It should be noted that the tasks are based on subgraphs, so \(|\mathcal{G}^{s}|=|\mathcal{G}^{q}|=1\implies|\mathcal{T}^{s}|=|T^{q}|=1\). Also, this problem setup is identical to the standard node classification task considering \(\mathcal{T}^{q}_{i}\in D_{test}\) to be the test set. 2. **Single graph, disjoint labels \(\langle\mathbf{SG,DL}\rangle\)**: This problem operates on the same graph in the support and query set, however unlike the previous one, the label sets are disjoint. The goal is to learn the model \(P_{\theta_{*}\rightarrow\theta}\), where \(|\mathcal{G}^{s}|=|\mathcal{G}^{q}|=1\) and \(Y_{s}\cap Y_{q}=\phi\). 3. **Multiple graphs, shared labels \(\langle\mathbf{MG,SL}\rangle\)**: This problem setup varies in terms of the dataset it handles, i.e., the dataset can contain multiple graphs instead of a single one. However, our method focuses on tasks which contain node-centric subgraphs, and hence, the model's aim is the same as problem 1. The aim is to learn the predictor model \(P_{\theta_{*}\rightarrow\theta}\), where \(Y_{s}=Y_{q}\) and \(|\mathcal{G}^{s}|,|\mathcal{G}^{q}|>1\). 4. **Multiple graphs, disjoint labels \(\langle\mathbf{MG,DL}\rangle\)**: In this problem, the setup is similar to the previous one, but only with disjoint labels instead of shared ones, i.e., learn a predictor model \(P_{\theta_{*}\rightarrow\theta}\), where \(Y_{s}\cap Y_{q}=\phi\) and \(|\mathcal{G}^{s}|,|\mathcal{G}^{q}|>1\). From the problem setups, we observe that, while they handle different dataset variants, the base HNN model operates on the \((S_{u},Y_{u})\) pair. So, we utilize a hyperbolic subgraph encoder and prototypical labels to encode \(S_{u}\) and get a continuous version of \(Y_{u}\) for our meta-learning algorithm, respectively. ### Hyperbolic Subgraph Encoder In previous methods [16; 18; 38], authors have shown that nodes' local neighborhood provides some informative signals for the prediction task. While the theory is not trivially extensible, we use the local tangent space of Poincare ball model to prove that the local neighborhood policy holds better for HNN models. The reason being that, while message propagation is linear in Euclidean GNNs [42], it is exponential in HNNs. Hence, a node's influence, as given by Definition 1, outside its neighborhood decreases exponentially. **Definition 1**.: _The influence of a hyperbolic node vector \(x^{\mathbb{H}}_{v}\) on node \(x^{\mathbb{H}}_{u}\) is defined by the influence score \(\mathcal{I}_{uv}=exp_{0}^{c}\left(\left\|\frac{\partial\log_{0}^{c}\left(x^{ \mathbb{H}}_{u}\right)}{\partial\log_{0}^{c}\left(x^{\mathbb{H}}_{v}\right)} \right\|\right)\)._ Figure 2: An overview of the proposed H-GRAM meta-learning framework. Here, the input graphs \(\mathcal{G}^{\mathbb{O}}\) are first partitioned into node-centric subgraph partitions. We theoretically show that encoding these subgraph neighborhoods is equivalent to encoding the entire graph in the context of node classification and link prediction tasks. H-GRAM then uses an HGCN encoder to produce subgraph encodings, which are further utilized to get label prototypes. Using the HGCN gradient updates and label prototypes, the HNN model’s parameters \(P_{\theta^{*}}\) is updated through a series of weight updates and meta updates for \(\eta\) meta-training steps. The parameters are then transferred to the meta-testing stage \(P_{\theta^{*}\rightarrow\theta}\) and further trained on \(\mathcal{D}^{s}_{test}\) and evaluated on \(\mathcal{D}^{q}_{test}\). **Definition 2**.: _The influence of a graph \(\mathcal{G}\) with set of vertices \(\mathcal{V}\) on a node \(u\in\mathcal{V}\) is defined as \(\mathcal{I}_{\mathcal{G}}(u)=exp_{0}^{c}\left(\left(\sum_{v\in\mathcal{V}}log_{0} ^{c}\left(\mathcal{I}_{uv}\right)\right)\)._ **Theorem 1**.: _For a set of paths \(P_{uv}\) between nodes \(u\) and \(v\), let us define \(D_{g\mu}^{p_{i}}\) as the geometric mean of nodes' degree in a path \(p_{i}\in P_{uv}\), \(p_{uv}\) as the shortest path, and \(\mathcal{I}_{uv}\) as the influence of node \(v\) on \(u\). Also, let us say \(D_{g\mu}^{min}=min\left\{D_{g\mu}^{p_{i}}\forall p_{i}\in P_{uv}\right\}\), then the relation \(\mathcal{I}_{uv}\leq exp_{u}^{c}\left(K/\left(D_{g\mu}^{min}\right)\|^{p_{uv} }\right\|\right)\) (where \(K\) is a constant) holds for message propagation in HGCN models._ Theorem 1 shows that the influence of a node decreases exponent-of-exponentially (\(exp_{u}^{c}=\mathcal{O}(e^{n})\)) with increasing distance \(\|p_{uv}\|\). Thus, we conclude that encoding the local neighborhood of a node is sufficient to encode its features for label prediction. **Definition 3**.: _The information loss between encoding an entire graph \(\mathcal{G}\) and a subgraph \(S_{u}\) with root node \(u\) is defined as \(\delta_{\mathbb{H}}(\mathcal{G},S_{u})=exp_{0}^{c}\left(log_{0}^{c}\left( \mathcal{I}_{\mathcal{G}}(u)\right)-log_{0}^{c}\left(\mathcal{I}_{\mathcal{S} _{u}}(u)\right)\right)\)._ **Theorem 2**.: _For a subgraph \(S_{u}\) of graph \(\mathcal{G}\) centered at node \(u\), let us define a node \(v\in\mathcal{G}\) with maximum influence on \(u\), i.e., \(v=\arg\max_{t}(\{\mathcal{I}_{u}t,t\in\mathcal{N}(u)\setminus u\})\). For a set of paths \(P_{uv}\) between nodes \(u\) and \(v\), let us define \(D_{g\mu}^{p_{i}}\) as the geometric mean of degree of nodes in a path \(p_{i}\in P_{uv}\), \(\|p_{uv}\|\) is the shortest path length, and \(D_{g\mu}^{min}=min\left\{D_{g\mu}^{p_{i}}\forall p_{i}\in P_{uv}\right\}\). Then, the information loss is bounded by \(\delta_{\mathbb{H}}(\mathcal{G},S_{u})\leq exp_{u}^{c}\left(K/\left(D_{g\mu}^{ min}\right)\|^{p_{uv}\|+1}\right)\) (where \(K\) is a constant)._ Theorem 2 shows that encoding the local subgraph is a \(e^{\|p_{uv}\|}\) order approximation of encoding the entire graph, and thus, with high enough \(\|p_{uv}\|\), the encodings are equivalent. Note that \(\|p_{uv}\|\) is equivalent to the subgraph's neighborhood size (\(k\) in \(k\)-hop). This shows that encoding a node's local neighborhood is sufficient to encode its features. Theorem proofs are provided in Appendix B. The above theorems provide us with the theoretical justification for encoding local subgraphs into our meta-learning framework. Hence, we partition the input \(\mathcal{G}^{\cup}\) into subgraphs \(S_{u}=V\times E\) centered at root node \(u\), with \(|V|\) nodes, \(|E|\) edges, a neighborhood size \(k\), and the corresponding label \(Y_{u}\). The subgraphs are processed through an \(k\)-layer HGCN network and the Einstein midpoint [33] of all the node encodings are taken as the overall encoding of the subgraph \(S_{u}\). For a given subgraph \(S_{u}=(A,X)\), where \(A\in\mathbb{H}^{\|V\|\times\|V\|}\) is the local adjacency matrix and \(X\in\mathbb{H}^{\|V\|\times m}\) are the node feature vectors of \(m\) dimension, the encoding procedure given can be formalized as: \[h_{u} =HGCN_{\theta^{*}}(A,X)\text{, where }h_{u}\in\mathbb{H}^{\|V\| \times d} \tag{1}\] \[e_{u} =\frac{\sum_{i=1}^{\|V\|}\gamma_{iu}h_{iu}}{\sum_{i=1}^{\|V\|} \gamma_{iu}}\text{, where }\gamma_{iu}=\frac{1}{\sqrt{1-\|h_{iu}\|^{2}}} \tag{2}\] where \(HGCN(A,X)\in\mathbb{H}^{\|V\|\times d}\) is the output of k-layer HGCN with \(d\) output units and \(e_{u}\in\mathbb{H}^{d}\) is the final subgraph encoding of \(S_{u}\). \(\gamma_{iu}\) is the Lorentz factor of the hyperbolic vector \(h_{iu}\) that indicates its weightage towards the Einstein midpoint. ### Label Prototypes Label information is generally categorical in node classification tasks. However, this does not allow us to pass inductive biases from the support set to the query set. Hence, to circumvent this issue, we use prototypical networks [31] as our label encoding. Our approach constructs continuous label prototypes by using the mean of meta-training nodes' features that belong to the label. These prototypes are then employed to classify meta-testing samples based on their similarity to the corresponding meta-training label prototypes. This enables our model to handle new, non-exhaustive labels in an inductive manner, without the need for additional training data. The primary idea is to form continuous label prototypes using the mean of nodes that belong to the label. To this end, the continuous label prototype of a label \(y_{k}\) is defined as \(c_{k}=\frac{\sum_{Y_{u}=y_{k}}\mathcal{Y}_{i}e_{i}}{\sum_{Y_{u}=y_{k}}\mathcal{ Y}_{i}}\), where \(\mathcal{Y}_{i}=\frac{1}{\sqrt{1-\|e_{i}\|^{2}}}\),and \(e_{i}\in\mathbb{H}^{d}\) is encoding of subgraphs \(S_{u}\) with labels \(Y_{u}=y_{k}\). For each \(S_{u}\) with class \(y_{k}\), we compute the class distribution vector as \(p_{k}=\frac{e^{(-d\mathbb{E}(e_{u},e_{k}))}}{\sum_{e}e^{(-d\mathbb{E}_{u}^{2}(e_ {u},e_{k}))}}\), where \(d_{\mathbb{E}}^{c}(e_{u},e_{k})=\frac{2}{\sqrt{c}}\tanh^{-1}\left(\sqrt{c}\|- e_{u}\oplus c_{k}\|\right)\) and the loss for HNN updates \(\mathcal{L}(p,y)=\sum_{j}y_{i}\log p_{j}\), where \(y_{i}\) is the one-hot encoding of the ground truth. The class distribution vector \(p_{k}\) is a softmax over the hyperbolic distance of subgraph encoding to the label prototypes, which indicates the probability that the subgraph belongs to the class \(y_{k}\). The loss function \(\mathcal{L}(p,y)\) is the cross-entropy loss between ground truth labels \(y\) and the class distribution vector \(p\). ### Meta-Learning In the previous section, we learned a continuous label encoding that is able to capture inductive biases from the subgraph. In this section, we utilize the optimization-based MAML algorithm [12] to transfer the inductive biases from the support set to the query set. To this end, we sample a batch of tasks, where each task \(\mathcal{T}_{i}=\{S_{i},Y_{i}\}_{i=1}^{\|\mathcal{T}_{i}\|}\). In the meta-training phase, we first optimize the HNN parameters using the Riemannian stochastic gradient descent (RSGD) [2] on support loss, i.e., for each \(\mathcal{T}_{i}^{s}\in\mathcal{T}_{train}^{s}:\theta_{j}^{*}\gets exp _{\theta_{j}^{*}}^{c}(-\alpha\nabla\mathcal{L}^{s})\), where \(\alpha\) is the learning rate of RSGD. Using the updated parameters \(\theta_{j}^{*}\), we record the evaluation results on the query set, i.e., loss on task \(\mathcal{T}_{i}^{q}\in\mathcal{T}_{train}^{q}\) is \(\mathcal{L}_{i}^{q}\). The above procedure is repeated \(\eta\) times post which \(\mathcal{L}_{i}^{q}\) over the batch of tasks \(\mathcal{T}_{i}^{q}\in\mathcal{T}_{train}^{q}\) is accumulated for the meta update \(\theta^{*}\gets exp_{\theta^{*}}^{c}(-\beta\nabla\sum_{i}\mathcal{L}_{i}^ {q})\). The above steps are repeated with the updated \(\theta^{*}\) and a new batch of tasks till convergence. The final updated parameter set \(\theta^{*}\rightarrow\theta\) is transferred to the meta-testing phase. In meta-testing, the tasks \(\mathcal{T}_{i}^{s}\in\mathcal{T}_{test}^{s}\) are used for RSGD parameter updates, i.e., \(\mathcal{T}_{i}^{s}\in\mathcal{T}_{test}^{s}:\theta_{j}\gets exp_{ \theta_{j}^{*}}^{c}(-\alpha\nabla\mathcal{L}^{s})\) until convergence. The updated parameters \(\theta\) are used for the final evaluation on \(\mathcal{T}_{i}^{q}\in\mathcal{T}_{test}^{q}\). Our meta-learning procedure is further detailed in Appendix C and the implementation code with our experiments is available at [https://github.com/Akirato/HGRAM](https://github.com/Akirato/HGRAM). Details on implementation and broader impacts are provided in Appendices 3.5 and E, respectively. ### Implementation Details H-GRAM is primarily implemented in Pytorch [26], with geopot [21] and GraphZoo [35] as support libraries for hyperbolic formulations. Our experiments are conducted on a Nvidia V100 GPU with 16 GB of VRAM. For gradient descent, we employ Riemannian Adam [28] with an initial learning rate of 0.01 and standard \(\beta\) values of 0.9 and 0.999. The other hyper-parameters were selected based on the best performance on the validation set (\(\mathcal{D}_{val}\)) under the given computational constraints. In our experiments, we empirically set \(k=2,d=32,h=4\), and \(\eta=10\). We explore the following search space and tune our hyper-parameters for best performance. The number of tasks in each batch are varied among 4, 8, 16, 32, and 64. The learning rate explored for both HNN updates and meta updates are \(10^{-2},5\times 10^{-3},10^{-3}\) and \(5\times 10^{-4}\). The size of hidden dimensions are selected from among 64, 128, and 256. The final best-performing hyper-parameter setup for real-world datasets is presented in Table 5. ## 4 Experimental Setup Our experiments aim to evaluate the performance of the proposed H-GRAM model and investigate the following research questions: * Does our hyperbolic meta-learning algorithm outperform the Euclidean baselines on various meta-learning problems? * How does our model perform and scale in comparison to other HNN formulations in standard graph problems? * How does H-GRAM model's performance vary with different few-shot settings, i.e., different values of \(k\) and \(N\)? * What is the importance of different meta information components? We use a set of standard benchmark datasets and baseline methods to compare the performance of H-GRAM on meta-learning and graph analysis tasks. The HNN models do not scale to the large datasets used in the meta-learning task, and hence, we limit our tests to Euclidean baselines. To compare against HNN models, we rely on standard node classification and link prediction on small datasets. Also, we do not consider other learning paradigms, such as self-supervised learning because they require an exhaustive set of nodes and labels and do not handle disjoint problem settings. ### Datasets For the task of meta-learning, we utilize the experimental setup from earlier approaches [18]; two synthetic datasets to understand if H-GRAM is able to capture local graph information and five real-world datasets to evaluate our model's performance in a few-shot setting. * **Synthetic Cycle**[18] contains multiple graphs with cycle as the basis with different topologies (House, Star, Diamond, and Fan) attached to the nodes on the cycle. The classes of the node are defined by their topology. * **Synthetic BA**[18] uses Barabasi-Albert (BA) graph as the basis with different topologies planted within it. The nodes are labeled using spectral clustering over the Graphlet Distribution Vector [27] of each node. * **ogbn-arxiv**[17] is a large citation graph of papers, where titles are the node features and subject areas are the labels. * **Tissue-PPI**[16; 43] contains multiple protein-protein interaction (PPI) networks collected from different tissues, gene signatures and ontology functions as features and labels, respectively. * **FirstMM-DB**[25] is a standard 3D point cloud link prediction dataset. * **Fold-PPI**[43] is a set of tissue PPI networks, where the node features and labels are the conjoint triad protein descriptor [30] and protein structures, respectively. * **Tree-of-Life**[44] is a large collection of PPI networks, originating from different species. ### Baseline Methods For comparison with HNNs, we utilize the standard benchmark citation graphs of Cora [29], Pubmed [24], and Citeseer [29]. For the baselines, we select the following methods to understand H-GRAM's performance compared to state-of-the-art models in the tasks of meta-learning and standard graph processing. * **Meta-Graph**[3], developed for few-shot link prediction over multiple graphs, utilizes VGAE [20] model with additional graph encoding signals. * **Meta-GNN**[40] is a MAML developed over simple graph convolution (SGC) network [36]. * **FS-GIN**[37] runs Graph Isomorphism Network (GIN) on the entire graph and then uses the few-shot labelled nodes to propagate loss and learn. * **FS-SGC**[36] is the same as FS-GIN but uses SGC instead of GIN as the GNN network. * **ProtoNet**[31] learn a metric space over label prototypes to generalize over unseen classes. * **MAML**[12] is a Model-Agnostic Meta Learning (MAML) method that learns on multiple tasks to adapt the gradients faster on unseen tasks. * **HMLP**[13], **HGCN**[4], and **HAT**[15] are the hyperbolic variants of Euclidean multi-layer perceptron (MLP), Graph Convolution Network (GCN), and Attention (AT) networks that use hyperbolic gyrovector operations instead of the vector space model. It should be noted that not all the baselines can be applied to both node classification and link prediction. Hence, we compare our model against the baselines only on the applicable scenarios. ## 5 Experimental Results We adopt the following standard problem setting which is widely studied in the literature [18]. The details of the datasets used in our experiments are provided in Table 1. In the case of synthetic datasets, we use a 2-way setup for disjoint label problems, and for the shared label problems the cycle graph and Barabasi-Albert (BA) graph have 17 and 10 labels, respectively. The evaluation of our model uses 5 and 10 gradient update steps in meta-training and meta-testing, respectively. In the case of real-world datasets, we use 3-shot and 16-shot setup for node classification and link prediction, respectively. For real-world disjoint labels problem, we use the 3-way classification setting. The evaluation of our model uses 20 and 10 gradient update steps in meta-training and meta-testing, respectively. In the case of Tissue-PPI dataset, we perform each 2-way protein function task three times and average it over 10 iterations for the final result. In the case of link prediction task, we need to ensure the distinct nature of support and query set in all meta-training tasks. For this, we hold out a fixed set comprised of 30% and 70% of the edges as a preprocessing step for every graph for the support and query set, respectively. ### RQ1: Performance of Meta-Learning To analyze the meta-learning capability of H-GRAM, we compare it against previous approaches in this area on a standard evaluation setup. We consider two experimental setups inline with previous evaluation in the literature [18]; (i) with synthetic datasets to analyze performance on different problem setups without altering the graph topology, and (ii) with real-world datasets to analyze per formance for practical application. Based on the problem setup, the datasets are partitioned into node-centric subgraphs with corresponding root node's label as the subgraph's ground truth label. The subgraphs are subsequently batched into tasks which are further divided into support set and query set for meta-learning. The evaluation metric for both the tasks of node classification and link prediction is accuracy \(\mathcal{A}=|Y=\hat{Y}|/|Y|\). For robust comparison, the metrics are computed over five folds of validation splits in a 2-shot setting for node classification and 32-shot setting for link prediction. Table 2 presents the five-fold average and 95% confidence interval of our experiments on synthetic and real-world datasets, respectively. From the results, we observe that H-GRAM consistently outperforms the baseline methods on a diverse set of datasets and meta-learning problem setups. For the disjoint labels setting, H-GRAM outperforms the best baseline in both the cases of single and multiple graphs. In the case of synthetic graphs, we observe that subgraph methods of H-GRAM and G-Meta outperform the entire graph encoding based approaches showing that subgraph methods are able to limit the over-smoothing problem [6] and improve performance. Also, we observe that meta-learning methods (ProtoNet and MAML) are unreliable in their results producing good results for some tasks and worse for others, whereas H-GRAM is consistently better across the board. Hence, we conclude that using label prototypes to learn inductive biases and transferring them using MAML meta updates is a more robust technique. We note that H-GRAM, unlike previous HNN models, is able to handle graphs with edges and nodes in the order of millions, as evident by the performance on large real-world datasets including ogbn-arxiv, Tissue-PPI, Fold-PPI, and Tree-of-Life. Our experiments clearly demonstrate the significant performance of H-GRAM in a wide-range of applications and prove the effectiveness of meta-learning in HNN models. \begin{table} \begin{tabular}{l|c c|c c|c c|c c} \hline \hline **Dataset** & **Task** & \(\mathbf{|\mathcal{G}^{\cup}|}\) & \(\mathbf{|V|}\) & \(\mathbf{|E|}\) & \(\mathbf{|X|}\) & \(\mathbf{|Y|}\) \\ \hline Synth. Cycle & Node & 10 & 11,476 & 19,687 & - & 17 \\ Synth. BA & Node & 10 & 2,000 & 7,647 & - & 10 \\ gbn-arxiv & Node & 1 & 169,343 & 1,166,243 & 128 & 40 \\ Tissue-PPI & Node & 24 & 51,194 & 1,350,412 & 50 & 10 \\ FirstMM-DB & Link & 41 & 56,468 & 126,024 & 5 & 2 \\ Fold-PPI & Node & 144 & 274,606 & 3,666,563 & 512 & 29 \\ Tree-of-Life & Link & 1,840 & 1,450,633 & 8,762,166 & - & 2 \\ Cora & N/L & 1 & 2,708 & 5,429 & 1,433 & 7 \\ Pubmed & N/L & 1 & 19,717 & 44,338 & 500 & 3 \\ Citeseer & N/L & 1 & 3,312 & 4,732 & 3,703 & 6 \\ \hline \hline \end{tabular} \end{table} Table 1: Basic statistics of the datasets used in our experiments. The columns present the dataset task (node classification or link prediction), number of graphs \(|\mathbf{|\mathcal{G}^{\cup}|}\), nodes \(|\mathbf{V|}\), edges \(|\mathbf{E|}\), node features \(|\mathbf{X|}\), and labels \(|\mathbf{Y|}\). Node, Link, and N/L indicates whether the datasets are used for node classification, link prediction, and both, respectively. \begin{table} \begin{tabular}{l|c c c c|c c|c c|c c} \hline \hline \multicolumn{1}{c}{} & \multicolumn{6}{c}{**Synthetic Datasets**} & \multicolumn{6}{c}{**Real-world (Node Classification)**} & **Real-world (Link Prediction)** \\ \hline **Task Setup** & \(\mathbf{|SG,DL\rangle}\) & \(\mathbf{(MG,SL)}\) & \(\mathbf{(MG,DL)}\) & \(\mathbf{(SG,DL)}\) & \(\mathbf{(MG,SL)}\) & \(\mathbf{(MG,DL)}\) & \(\mathbf{(MG,SL)}\) & \(\mathbf{(MG,SL)}\) & \(\mathbf{(MG,SL)}\) & \(\mathbf{(MG,SL)}\) \\ **Dataset** & **S. C y** & **S. Ba** & **S. C y** & **S. Ba** & **S. C y** & **S. Ba** & **ogbn-arxiv** & **Tissue-PPI** & **Fold-PPI** & **FirstMM-DB** & **Tree-of-Life** \\ \hline **Meta-Graph** & - & - & - & - & - & - & - & - & - & - \\ **Meta-GNN** & 7.20 & 6.94 & - & - & - & - & 3.36 & - & - & - & - \\ **FS-GIN** & 684 & 7.49 & - & - & - & - & - & - & - & - \\ **FS-GGC** &.574 &.715 & - & - & - & - & - & - & - & - \\ **Procedure** & 821 &.858 &.282 &.657 &.749 &.866 &.372 &.546 &.382 &.779 &.697 \\ **MAML** & 842 &.848 &.511 &.726 &.653 &.844 &.389 &.745 &.482 &.758 &.719 \\ **G-META** &.872 &.867 &.542 &.734 &.767 &.867 &.451 &.768 &.561 &.784 &.722 \\ \hline **H-GRAM** & **.883** & **.873** & **.555** & **.746** & **.779** & **.888** & **.472** & **.786** & **.584** & **.804** & **.742** \\ \hline \hline \end{tabular} \end{table} Table 2: Performance of H-GRAM and the baselines on synthetic and real-world datasets. The top three rows define the task, problem setup (Single Graph (SG), Multiple Graphs (MG), Shared Labels (SL) or Disjoint Labels (DL)) and dataset. The problems with disjoint labels use a 2-way meta-learning setup, and in the case of shared labels, the cycle (S. Cy) and BA (S. BA) graph have 17 and 10 labels, respectively. In our evaluation, we use 5 and 10 gradient update steps in meta-training and meta-testing, respectively. The columns present the average multi-class classification accuracy and 95% confidence interval over five-folds. Note that the baselines are only defined for certain tasks, “-” implies that the baseline is not defined for the task and setup. Meta-Graph is only defined for link prediction. The confidence intervals for the results are provided in Appendix D. ### RQ2: Comparison with HNN models The current HNN formulations of HMLP, HAT, and HGCN do not scale to large datasets, and hence, we were not able to compare them against H-GRAM on large-scale datasets. However, it is necessary to compare the standard HNN formulations with H-GRAM to understand the importance of subgraph encoders and meta-learning. Thus, we utilize the single graph and shared labels setup of H-GRAM to evaluate its performance on citation networks of Cora, Pubmed, and Citeseer for both tasks of node classification and link prediction. We also compare the time taken by our model and other HNNs on varying number of nodes \(\left(|\mathcal{V}|=\{10^{i}\}_{i=1}^{7}\right)\) in the Synthetic BA graph. For this experiment, we also consider a multi-GPU version of H-GRAM that parallelizes the HNN update computations and accumulates them for meta update. From our results, presented in Table 3, we observe that H-GRAM is, on average, able to outperform the best baseline. This shows that our formulation of HNN models using meta-learning over node-centric subgraphs is more effective than the traditional models, while also being scalable over large datasets. The scalability allows for multi-GPU training and translates the performance gains of HNNs to larger datasets. In the results provided in Figure 3, we observe that the time taken by the models is inline with their parameter complexity (HMLP\(\leq\)HGCN\(\leq\)HAT\(\leq\)H-GRAM). However, the traditional HNNs are not able to scale beyond \(|\mathcal{V}|=10^{4}\), whereas, H-GRAM is able to accommodate large graphs. Another point to note is that H-GRAM(multi) is able to parallelize well over multiple GPUs with its time taken showing stability after \(10^{4}\) nodes (which is the size of nodes that a single GPU can accommodate). ### RQ3: Challenging Few-shot Settings To understand the effect of different few-shot learning scenarios, we vary the number of few-shots \(M\) and hops \(K\) in the neighborhood. For the experiment on few-shot classification, we consider the problems of node classification on Fold-PPI dataset and link prediction on FirstMM-DB dataset. We vary \(M=1,2,3\) and \(M=16,32,64\) for node classification and link prediction, respectively, and calculate the corresponding accuracy and 95% confidence interval of H-GRAM. The results for this experiment are presented in Figures 3(a) and 3(b) for node classification and link prediction, respectively. To determine the effect of hops in the neighborhood, we vary \(K=1,2,3\) for the same problem setting and compute the corresponding performance of our model. The results for varying neighborhood sizes are reported in Figure 3(c). In the results on varying the number of few-shots, we observe a linear trend in both the tasks of node classification and link prediction, i.e., a linear increase in H-GRAM's accuracy with an increase in the number of shots in meta-testing. Thus, we conclude that H-GRAM, like other generic learning models, performs better with an increasing number of training samples. In the experiment on increasing the neighborhood size, we observe that in the task of node classification, \(K=3\) shows the best performance, but in link prediction \(K=2\) \begin{table} \begin{tabular}{l|c c|c c|c c} \hline **Dataset** & \multicolumn{2}{c|}{**Cora**} & \multicolumn{2}{c|}{**Pubmed**} & \multicolumn{2}{c}{**Citeseer**} \\ **Task** & **Node** & **Link** & **Node** & **Link** & **Node** & **Link** \\ \hline **HMLP** &.75\(\pm\).029 &.765\(\pm\).047 &.657\(\pm\).045 &.848\(\pm\).038 &.879\(\pm\).078 &.877\(\pm\).090 \\ **HAT** &.796\(\pm\).036 & **.792\(\pm\).038** &.681\(\pm\).034 &.908\(\pm\).038 &.939\(\pm\).034 &.922\(\pm\).036 \\ **HGCN** &.779\(\pm\).026 &.789\(\pm\).030 &.696\(\pm\).029 & **.914\(\pm\).031** & **.950\(\pm\).032** &.928\(\pm\).030 \\ \hline **H-GRAM** & **.827\(\pm\).037** &.790\(\pm\).026 & **.716\(\pm\).029** &.896\(\pm\).025 &.924\(\pm\).033 & **.936\(\pm\).030** \\ \hline \end{tabular} \end{table} Table 3: Comparison with HNN models on standard benchmarks. We compare the Single Graph, Shared Labels (SG,SL) setup of the H-GRAM model to the baselines. The columns report the average multi-class classification accuracy and 95% confidence interval over five-folds on the tasks of node classification (Node) and link prediction (Link) in the standard citation graphs. Figure 3: Time taken (per epoch) by H-GRAM compared to other HNNs with varying number of nodes \(|\mathcal{V}|=\{10^{i}\}_{i=1}^{7}\) in Syn. BA graph. H-GRAM(multi) is the multi-GPU version of H-GRAM. has the best performance, with a significant drop in \(K=3\). Thus, for stability, we choose \(K=2\) in our experiments. The trend in link prediction also shows that larger neighborhoods can lead to an increase in noise, which can negatively affect performance. ### RQ4: Ablation Study In this section, we aim to understand the contribution of the different components in our model. To this end, we compare variants of our model by (i) varying the base HNN model (HMLP, HAT, and HGCN), and (ii) deleting individual meta-learning components - H-ProtoNet implies H-GRAM without meta updates and H-MAML implies H-GRAM without prototypes. The model variants are compared on the real-world datasets and the results are presented in Table 4. The ablation study indicates that meta gradient updates and label prototypes contribute to \(\approx\)16% and \(\approx\)6% improvement in H-GRAM's performance, respectively. This clearly demonstrates the ability of label prototypes in encoding inductive biases and that of meta gradients in transferring the knowledge from meta-training to the meta-testing phase. Additionally, from our study on different HNN bases for H-GRAM, we note that the HGCN base outperforms the other bases of HMLP and HAT by \(\approx\)19% and \(\approx\)2%, respectively. Thus, we choose HGCN as the base in our final model. ## 6 Conclusion In this paper, we introduce H-GRAM, a scalable hyperbolic meta-learning model that is able to learn inductive biases from a support set and adapt to a query set with disjoint nodes, edges, and labels by transferring the knowledge. We have theoretically proven the effectiveness of node-centric subgraph information in HNN models, and used that to formulate a meta-learning model that can scale over large datasets. Our model is able to handle challenging few-shot learning scenarios and also outperform the previous Euclidean baselines in the area of meta-learning. Additionally, unlike previous HNN models, H-GRAM is also able to scale to large graph datasets. \begin{table} \begin{tabular}{l|c c c|c c} \hline **Task** & \multicolumn{4}{c|}{**Node Classification**} & \multicolumn{2}{c}{**Link Prediction**} \\ **Setup** & \(\langle\mathbf{SG},\mathbf{DL}\rangle\) & \(\langle\mathbf{MG},\mathbf{SL}\rangle\) & \(\langle\mathbf{MG},\mathbf{DL}\rangle\) & \(\langle\mathbf{MG},\mathbf{SL}\rangle\) & \(\langle\mathbf{MG},\mathbf{SL}\rangle\) \\ **Dataset** & **ogbn-arxiv** & **Tissue-PPI** & **Fold-PPI** & **FirstMM-DB** & **Tree-of-Life** \\ \hline **H-ProtoNet** &.389\(\pm\).019 &.559\(\pm\).027 &.398\(\pm\).023 &.799\(\pm\).015 &.716\(\pm\).004 \\ **H-MAML** &.407\(\pm\).023 &.762\(\pm\).056 &.502\(\pm\).046 &.777\(\pm\).018 &.739\(\pm\).005 \\ **H-GRAM(HMLP)** &.370\(\pm\).036 &.537\(\pm\).044 &.372\(\pm\).036 &.772\(\pm\).028 &.688\(\pm\).019 \\ **H-GRAM(HAT)** &.462\(\pm\).032 &.777\(\pm\).028 &.573\(\pm\).048 &.794\(\pm\).023 &.732\(\pm\).021 \\ \hline **H-GRAM(ours)** & **.472\(\pm\).035** & **.786\(\pm\).031** & **.584\(\pm\).044** & **.804\(\pm\).021** & **.742\(\pm\).013** \\ \hline \end{tabular} \end{table} Table 4: Ablation study results - H-ProtoNet and H-MAML can be considered H-GRAM’s model variants without meta updates and label prototypes, respectively. H-GRAM(HMLP) and H-GRAM(HAT) represents the variant of H-GRAM with HMLP and HAT as base, respectively. Our final model, presented in the last row, uses HGCN as the base model. The columns report the average multi-class classification accuracy and 95% confidence interval over five-folds on different tasks. Figure 4: Performance of H-GRAM on challenging few-shot settings. The reported accuracies are multi-class classification accuracy averaged over five-fold runs of our model.
2307.16322
RoseNNa: A performant, portable library for neural network inference with application to computational fluid dynamics
The rise of neural network-based machine learning ushered in high-level libraries, including TensorFlow and PyTorch, to support their functionality. Computational fluid dynamics (CFD) researchers have benefited from this trend and produced powerful neural networks that promise shorter simulation times. For example, multilayer perceptrons (MLPs) and Long Short Term Memory (LSTM) recurrent-based (RNN) architectures can represent sub-grid physical effects, like turbulence. Implementing neural networks in CFD solvers is challenging because the programming languages used for machine learning and CFD are mostly non-overlapping, We present the roseNNa library, which bridges the gap between neural network inference and CFD. RoseNNa is a non-invasive, lightweight (1000 lines), and performant tool for neural network inference, with focus on the smaller networks used to augment PDE solvers, like those of CFD, which are typically written in C/C++ or Fortran. RoseNNa accomplishes this by automatically converting trained models from typical neural network training packages into a high-performance Fortran library with C and Fortran APIs. This reduces the effort needed to access trained neural networks and maintains performance in the PDE solvers that CFD researchers build and rely upon. Results show that RoseNNa reliably outperforms PyTorch (Python) and libtorch (C++) on MLPs and LSTM RNNs with less than 100 hidden layers and 100 neurons per layer, even after removing the overhead cost of API calls. Speedups range from a factor of about 10 and 2 faster than these established libraries for the smaller and larger ends of the neural network size ranges tested.
Ajay Bati, Spencer H. Bryngelson
2023-07-30T21:11:55Z
http://arxiv.org/abs/2307.16322v1
RoseNNa: A performant, portable library for neural network inference with application to computational fluid dynamics ###### Abstract The rise of neural network-based machine learning ushered in high-level libraries, including TensorFlow and PyTorch, to support their functionality. Computational fluid dynamics (CFD) researchers have benefited from this trend and produced powerful neural networks that promise shorter simulation times. For example, multilayer perceptrons (MLPs) and Long Short Term Memory (LSTM) recurrent-based (RNN) architectures can represent sub-grid physical effects, like turbulence. Implementing neural networks in CFD solvers is challenging because the programming languages used for machine learning and CFD are mostly non-overlapping, We present the roseNNa library, which bridges the gap between neural network inference and CFD. RoseNNa is a non-invasive, lightweight (1000 lines), and performant tool for neural network inference, with focus on the smaller networks used to augment PDE solvers, like those of CFD, which are typically written in C/C++ or Fortran. RoseNNa accomplishes this by automatically converting trained models from typical neural network training packages into a high-performance Fortran library with C and Fortran APIs. This reduces the effort needed to access trained neural networks and maintains performance in the PDE solvers that CFD researchers build and rely upon. Results show that RoseNNa reliably outperforms PyTorch (Python) and libtorch (C++) on MLPs and LSTM RNNs with less than 100 hidden layers and 100 neurons per layer, even after removing the overhead cost of API calls. Speedups range from a factor of about 10 and 2 faster than these established libraries for the smaller and larger ends of the neural network size ranges tested. + Footnote †: journal: Computer Science ## 1 Introduction Deep learning has received considerable attention due to the availability of data and increasing computational power. Computational fluid dynamics (CFD) practitioners have been developing neural-network-based models to enhance traditional closures models and numerical methods. For example, Fukami et al. [1] implemented a convolutional autoencoder and multilayer perceptron (MLP) to speedup turbulence simulations, and Zhu et al. [2] showed how multiple artificial neural networks (ANNs) can model turbulence at high Reynolds numbers. Of course, there are many other such examples. These trained models show promising results but are often not integrated into high-performance solvers to deploy the model at scale. Since the neural networks are typically constructed via Python-based learning libraries like PyTorch, it is unclear how to most efficiently introduce them into CFD and other PDE solvers written in low-level languages like C and Fortran. Researchers have proposed solutions to bridge the gap between the Python and HPC domains for deep learning. Currently, the most frequently updated Fortran framework for this task is neural-Fortran [3], which supports building, training, and model parallelism in Fortran. However, porting pre-trained neural networks to Fortran using this framework would require understanding their deep learning documentation, manually rewriting the model's architecture, and transferring the trained model's parameters. Other attempts to solve the lack of deep learning support in HPC codebases also focus on manually specifying the architecture or converting neural network models from a single Python library to an HPC-amenable language. For example, Fortran-Keras Bridge (FKB) [4] is derived from neural-Fortran and specializes in Keras-based models, NEURBT [5] focuses on neural networks for classification, FANN [6] describes a C library for multilayer feed-forward networks, and SAGRAD [7] (like NEURBT) implements training in Fortran77. We avoid these drawbacks via a fast and non-intrusive automatic conversion tool. This manuscript presents an open-source library called RoseNNa that achieves these tasks. RoseNNa is available under the MIT license at github.com/comp-physics/roseNNa. As shown in fig. 1, RoseNNa encodes pre-trained neural networks from common machine learning libraries via an ONNX-backend and uses fypp, a Python-to-Fortran metaprogramming language, to generate the library. RoseNNa targets inference of the artificial neural networks used for PDE- and CFD-based modeling, supporting commonly used architectures and activation functions in these areas. These network architectures were revealed via a literature survey of about 25 papers that used neural networks for modeling and numerics tasks. This survey found that MLP implementations consisted of at most 6 hidden layers, and 85% of them have fewer than 15 hidden layers (or dimensionality), and the remaining fraction having fewer than 100 neurons per layer1. We also reviewed 10 articles using LSTM architectures for similar purposes.2 90% of implementations use fewer than 64-time steps in the memory layer and a have a hidden dimension smaller than 32. These numbers provide the architectures that RoseNNa should support with high performance. The results are also consistent with expectations: PDE solvers on discretized grids with many elements that require many Figure 1: RoseNNa (c) is a neural network converter that integrates into the inference process. It encodes the ONNX-converted neural network and transforms it into performant Fortran code with C and Fortran APIs. The user provides the components outside of (c). iterations (or time steps) cannot afford the evaluation of large neural networks since they involve relatively many floating point operations. This manuscript discusses the methodology surrounding RoseNNa and example applications to CFD. Section 2 introduces the architecture of RoseNNa that enables its flexibility and speed. Section 3 describes its user-friendly interface and design, and Section 4 discusses RoseNNa's performance results against Python-based libraries for popular CFD architectures. We conclude in section 5 with a discussion of the primary results and use cases of the RoseNNa tool. ## 2 Design strategy ### Design options RoseNNa follows two main processes: read and interpret the Python-native model (encode, fig. 1 (d)) and reconstruct it in Fortran/C (decode, fig. 1 (e)). The tool decomposes key aspects of a neural network to define its structure: trained weights (values and dimensions), layer functionality, activation functions, and the order of layer connections. Using this encoded information, RoseNNa can reconstruct the functionality of a neural network in Fortran/C. Users first convert their model to a unified format via ONNX [8] (fig. 1 (b)), a library that provides interoperability between machine learning libraries, including sklearn [9], PyTorch [10], TensorFlow [11], and Caffe [12]. These libraries share common characteristics in their intermediary representations and the functionality of a neural network model. Still, they differ in their layer encoding. ONNX unifies these differences. The ONNX-interpreted model is decoded using fypp (fig. 1 (f)), a Python-based pre-processor for Fortran codes. The activation functions (Tanh, ReLU, Sigmoid), model layers (LSTM, convolutions, pooling layers, MLP architectures, and more), and data structures holding model weights are first extracted via fypp and then stored in RoseNNa, specifically in Fortran code. This ensures no speed is lost to reading in needed values while conducting inference. ONNX encodes the model's structure while RoseNNa restores its graph interpretation using fypp. Alternative solutions to Python-to-HPC model conversion are also viable. For example, Python functionality can be integrated into Fortran by running an instance of Python or exposing a model's outputs through APIs. These attempts, however, are susceptible to cascading overhead time issues. The library we present, RoseNNa, removes this overhead and enables quick HPC deployment, features that CFD practitioners require for running simulations. The power of RoseNNa comes from its internal management of neural networks, ONNX backend, and Fortran/C support. Like established linear algebra libraries like BLAS and LAPACK, RoseNNa is a Fortran library. This is an appropriate fit since the library's focus is fast evaluation of rather simple mathematical functions, like small matrix-matrix and matrix-vector products. In addition, with recent updates to the language, Fortran can be readily linked to C, which is also often used for these applications. Fortran compilers are well optimized and can efficiently handle small matrix-matrix multiplies. We found that the optimized Python-based inference speeds for smaller model architectures are similar to the speeds seen in RoseNNa, as shown in fig. 2 and fig. 3. ### Onnx Open Neural Network Exchange (ONNX) [8] is an open-source artificial intelligence (AI/ML) ecosystem that allows for interoperability between preexisting machine learning libraries and provides inference optimizations. During the pre-processing stage, RoseNNa encodes the neural network model. ``` Listing 1.Fypp code to generate a linear layer ``` #:iftup[0]=='Gemm'!===GemmLayer=== calllinear_layer(${tup[1][0]}$, & linLayers(${layer_dict[tup[0]]}$), & ${1-tup[1][1]}$) ``` Listing 2: Corresponding Fortran This entails parsing and storing each layer's order, weights, dimensions, and other functionality in the library. We use ONNX to unify differences between neural network model interpretations and establish a common parser that can be optimized at compile time. Users can convert their model to the ONNX due to its widespread interoperability support. ONNX is often used in research and industry. For example, Someki et al. [13] used ONNX to unify functionality support and Moreno et al. [14] converted a PyTorch model to a TensorFlow graph for compatibility with testing software. Like Rodriguez and Dassatti [15], RoseNNa reconstructs models from deep-learning libraries, enabling model designers to keep their native framework. ### Metaprogramming The transition from model topology encoding fig. 1 (d) to the decoding stage in fig. 1 (e) is performed by a Python-based Fortran pre-processor called fypp [16]. In our implementation, fypp translates a neural network's properties into Fortran code _before_ compile-time, thus exposing compiler optimizations. This decoding process is unique to each neural network, and so is re-run for different neural network models. After interpreting the Python-native model, we store its features and important variable definitions in fypp files. This encoding process stores the layers, activation functions, and weight parameters while preserving their order. We record these layers' specific options, including whether transposing is required and hyperparameter constants. RoseNNa tracks changes in matrix shapes, allowing it to define variables with their appropriate dimensions in Fortran explicitly. It also stores the output names of each layer so they can be referenced during the decoding phase in Fortran. To increase readability, these output names are only defined when the input undergoes dimension changes. The decoding stage (fig. 1 (f)) references each component described above. Using fypp, the layers are defined in order with their respective weights, constants, and other supplementary options. ### RoseNNa capabilities RoseNNa was designed to support a broad range of neural network architectures in CFD. As discussed in section 1, these primarily include MLPs and LSTM RNNs. RoseNNa also supports other architectures, such as convolutional and pooling layers, which are generally popular and could become more broadly used in CFD solvers in the future. One can expand RoseNNa for different architectures and activation functions as needed. Adding these new features to the tool requires only a basic understanding of the architecture functionality, how ONNX encodes it, and following the RoseNNa contributor's guide for implementation. program example use rosenna!import the library implicit none real(c_double), dimension(1,2) :: inputs real(c_double), dimension(1,3) :: output inputs = reshape((/1.0, 1.0/), (/1, 2/), order=[2, 1]) call initialize()!initialize/load in the weights call use_model(inputs, output)!conduct inference, store output end program ``` **Listing 3** Example Fortran90+ program invoking RoseNNA. ## 3 User interface The user will have access to all files that make up the library. RoseNNa is designed for straightforward and non-intrusive integration in existing codebases. As described in the pipeline of fig. 1 (b), the only required input to RoseNNa is an ONNX-format pre-trained neural network model. Simple pre-processing using the metaprogramming language fypp reconstructs the neural network, creating a custom Fortran file with an organized subroutine defining the model's structure. Compiling all core files and the fypp-transcribed file creates a library that can be linked with an existing code (fig. 1 (g)). Using RoseNNa in C, except for defining headers for certain function calls, follows the same procedure. To use this library, one imports RoseNNa, which automatically reads and initializes the parameters encoded from the trained neural network, and then calls the model's forward subroutine with the same inputs as the native model. Listing 3 shows this lightweight approach. ## 4 Results ### Flexibility and portability With only a few library calls, RoseNNa can be readily integrated into existing programs. It can interface with commonly used machine learning libraries and be linked to Fortran and C, the most popular languages in CFD. RoseNNa can dynamically reconstruct neural networks and avoids any manual intervention. RoseNNa can also represent attributes of deep learning models: Layers, activation functions, important constants, and more. RoseNNa caters to smaller neural networks (MLPs and LSTMs) and supports around 90% of the most popular architectures and activation functions used in CFD research. Its simple user interface and ability to interpret ONNX-format models enable the conversion of a massive pool of promising neural networks in CFD. ### Performance on example cases We ran tests for CFD's most commonly used architectures, LSTMs and MLPs, to compare inference performance differences between RoseNNa and PyTorch. We compare RoseNNa's performance to that of PyTorch because it is a representative and widely used deep learning library. We used a single core of an Intel Xeon Gold 6226 CPU to run the following tests. We ran 100 tests in PyTorch on a single thread for each data point using randomly initialized weights. The same models curated in PyTorch were converted to and tested in RoseNNa. Then, we took the ratio of the medians of the 100 RoseNNa and 100 PyTorch times. This process was repeated 25 times for each point in figs. 2 to 4. Results for MLPs are important due to their widespread usage in CFD solvers. Their straightforward architectures and computation also allow for unproblematic conversions. Most MLPs used in CFD are shallow to enable reasonable computation runtimes. Based on this and the results of our literature survey, MLPs used to solve large PDE systems like those of CFD fall within the axis limits of fig. 2. Figure 2 shows that tests fall under a RoseNNa-to-PyTorch time ratio of one, indicating RoseNNa's quicker inference speeds. The ratio stays near one even for large examples such as 50 neurons and a depth of 100, which is uncommon for CFD applications. We further tested RoseNNa's inference speeds against a different PyTorch backend for consistency and to ensure we compared against the fastest version of PyTorch. Therefore, fig. 2 (b) represents the same tests run on PyTorch with an OpenBLAS backend instead of MKL. RoseNNa is 10% faster (averaged over all 25 test cases) using this backend, but the results still fall below a one-time ratio for most CFD use cases. However, with OpenBLAS, larger architectures entail increasingly slower times. Small-scale LSTM-RNN architectures are also often used in CFD applications. Figure 3 shows tests conducted at different depths and hidden dimension sizes to demonstrate where RoseNNa falls compared to PyTorch inference speeds. Most CFD-based LSTMs' architectures are located below the one RoseNNa-to-PyTorch time ratio. Compared with an OpenBLAS implementation of PyTorch, RoseNNa seems to be 10% faster on average. Larger architectures lead to a slower inference time ratio as expected. Figure 2 and fig. 3 incorporate published examples of LSTMs and MLPs. All four test cases lie in the bottom left corner of the graph since they are shallow architectures. A simple conversion from PyTorch or TensorFlow to ONNX allowed us to pass the model through RoseNNa's pipeline. Despite their shallow architectures, these papers reported promising results across CFD modeling tasks broadly. For MLPs, Zhang et al. [17] proposed combining an artificial neural network with a flamelet-generated manifold to solve a memory issue. Zhou et al. [18] developed a new SGS model for large-eddy simulation (LES), showing significant improvements over the conventional models. For LSTMs, Srinivasan et al. [19] found this architecture outperformed MLPs in predicting turbulent statistics in temporally evolving turbulent flows. Lastly, Li et al. [20] uses LSTMs to develop a reduced-order modeling of a wind-bridge interaction system. ### Comparison to a lower-level implementation Another approach to reducing Python overhead is to use a library's C/C++ API if supported. For example, PyTorch has a (beta) fully-native C++ API called libtorch that provides access to most PyTorch functionality [10]. Figure 4 represents comparison tests run on the same architectures as fig. 2 but against libtorch. Most architecture sizes are inferred faster via RoseNNa, in particular the smaller ones relevant to CFD simulation. Larger neural networks, most of which are outside the CFD scope, are still slower but near RoseNNa's speed, even for sizes as large as 15 layers of 100 neurons. Libtorch makes up some of the RoseNNa-PyTorch speed difference for larger cases, but there are still potential issues with relying upon the Torch C++ API (and other exposed backend APIs). For example, libtorch support is liable to change, which is stated directly on the Torch website. It also only provides a C++ API, thus requiring more work, like a shim layer, for use in Fortran codebases than RoseNNa. Python-based overhead might explain part of the time discrepancy of fig. 2 and fig. 3, but the main contribution towards the speedup is RoseNNa's compile-time optimization and Fortran implementation. These results show RoseNNa's computationally viability for ML-enhanced CFD. For the larger architectures in figs. 2 to 4 that were slower in RoseNNa, one can implement large matrix-matrix multiplies and other expensive calls via optimized linear algebra libraries like BLAS/LAPACK. However, based on our literature survey, these larger neural networks fall outside the CFD (and PDE-solver) scope RoseNNa focuses on. With no external dependencies, the RoseNNa library is lightweight and can be readily incorporated into existing PDE solvers. ## 5 Conclusions This paper describes the design, application, and viability of RoseNNa, a neural network conversion tool for CFD codebases. It can encode a neural network's features using ONNX, a Python-based library we use to unify machine learning libraries. With a Python-powered pre-processor, fypp, RoseNNa decodes the model in Fortran. We present this tool as an alternative to manually defining neural networks in Fortran or re-implementing existing libraries' ML features. In three speed comparison benchmarks we conducted (RoseNNa/MKL, RoseNNa/OpenBLAS, RoseNNa/libtorch), RoseNNa's application in the CFD domain seemed to be promising and a more reliable alternative to low-level implementations of PyTorch, TensorFlow, or other Python-based machine learning libraries. RoseNNa supports many popular features and establishes a streamlined process for increasing its breadth. RoseNNa presents useful benefits for neural network conversion and inference. First, it supports the conversion from Python machine-learning libraries via ONNX. It is also simple to use. As shown in listing 3, a few API calls enable inference. Lastly, RoseNNa is a lightweight tool, enabling integration and minimal intrusiveness in existing and (potentially large) CFD codebases. The library is compiled for the neural network and linked to existing code. RoseNNa's future lies in improving performance, adding functionality to existing architectures, and expanding to new, popular features. With the pipeline of fig. 1, contributors can incorporate any Figure 2: Multilayer perceptron (MLP) time comparison (RoseNNa versus PyTorch). \(\delta\) represents a specific hidden size (neurons per layer), and the x-axis represents the depth (number of hidden layers). Random activation functions (ReLu, Tanh, Sigmoid) were chosen for each MLP and assigned to each hidden layer. needed feature. We have created an in-depth manuscript about our current methodology and how new contributions can be feasibly integrated (accessible at github.com/comp-physics/roseNNa). We provide steps describing which files to modify and examples, with documentation, of their functions and variables. Any new changes can be verified via the testing pipeline, allowing contributors to add new features efficiently. ## Acknowledgements This work used Bridges2 at the Pittsburgh Supercomputing Center through allocation TG-PHY210084 (PI Spencer Bryngelson) from the Advanced Cyberinfrastructure Coordination Ecosystem: Services & Support (ACCESS) program, which is supported by National Science Foundation grants #2138259, #2138286, #2138307, #2137603, and #2138296. SHB also acknowledges the resources of the Oak Ridge Leadership Computing Facility at the Oak Ridge National Laboratory, which Figure 4: Multilayer perceptron (MLP) model time comparison (RoseNNa/libtorch). \(\delta\) is the hidden size, and the horizontal axis is the number of layers. Libtorch is PyTorch’s C++ API. The same scheme for testing the RoseNNa to PyTorch speed ratio for MLPs was used for these tests. Figure 3: Long Short-Term Memory (LSTM) time comparison (RoseNNa/PyTorch). The horizontal axis is the number of time steps (depth), and \(\lambda\) is the hidden dimension size. All the typical operations and activation functions were incorporated into the timing of the LSTM cells. is supported by the Office of Science of the U.S. Department of Energy under Contract No. DE-AC05-00OR22725. SHB acknowledges support from the Office of the Naval Research under grant N00014-22-1-2519 (PM Dr. Julie Young). This research was supported in part through research cyberinfrastructure resources and services provided by the Partnership for an Advanced Computing Environment (PACE) at the Georgia Institute of Technology, Atlanta, Georgia, USA.
2306.03406
Deep neural networks architectures from the perspective of manifold learning
Despite significant advances in the field of deep learning in ap-plications to various areas, an explanation of the learning pro-cess of neural network models remains an important open ques-tion. The purpose of this paper is a comprehensive comparison and description of neural network architectures in terms of ge-ometry and topology. We focus on the internal representation of neural networks and on the dynamics of changes in the topology and geometry of a data manifold on different layers. In this paper, we use the concepts of topological data analysis (TDA) and persistent homological fractal dimension. We present a wide range of experiments with various datasets and configurations of convolutional neural network (CNNs) architectures and Transformers in CV and NLP tasks. Our work is a contribution to the development of the important field of explainable and interpretable AI within the framework of geometrical deep learning.
German Magai
2023-06-06T04:57:39Z
http://arxiv.org/abs/2306.03406v1
# Deep neural networks architectures from the perspective of manifold learning ###### Abstract Despite significant advances in the field of deep learning in applications to various areas, an explanation of the learning process of neural network models remains an important open question. The purpose of this paper is a comprehensive comparison and description of neural network architectures in terms of geometry and topology. We focus on the internal representation of neural networks and on the dynamics of changes in the topology and geometry of a data manifold on different layers. In this paper, we use the concepts of topological data analysis (TDA) and persistent homological fractal dimension. We present a wide range of experiments with various datasets and configurations of convolutional neural network (CNNs) architectures and Transformers in CV and NLP tasks. Our work is a contribution to the development of the important field of explainable and interpretable AI within the framework of geometrical deep learning. _Representation learning, Deep networks architectures, manifold learning, performance evaluation._ ## I Introduction Over the years, deep neural networks (DNNs) have shown success in applications in many areas: natural and social sciences, computer vision, text, audio processing and generation, and more. Despite the obvious empirical progress, some deep learning questions are still poorly understood theoretically: why some architectures are more successful than others at solving the same problem? What determines the generalizing ability of DNNs and how can it be assessed without using a test sample? A promising and important area of research is the interpretation of the learning process and the internal representation of DNNs in terms of topology and geometry. Recently, many efficient DNNs architectures have been developed. Transformer neural network architectures are increasingly used not only in the field of language processing, but also in other tasks that can be represented in terms of sequence processing. For example, Vision Transformers [56] in image processing tasks, where Convolutional Neural Network (CNN) have been used until recently. And there is still no clear answer which approach to neural networks' design is better. Analysis and comparison of different architectures from different aspects: internal representation, robustness, performance, scaling etc. can greatly improve understanding of why some architectures perform better than others. New results in this direction will help provide approaches to the design and development of efficient architectures in various tasks. In this paper, we analyze knowledge representation in neural networks of different architecture families. To interpret the internal representations of deep models, we use an approach based on manifold learning and topological data analysis (TDA). We touch upon the issue of the evolution of the embedding space throughout the depth of neural networks using the example of various architectures, activation functions and datasets. Furthermore, we propose a method for estimating the generalization ability based on the topological and geometric properties of the internal representation. We pioneered the use of fractal dimension to analyze the internal representation of DNNs. Experiments include CNNs, Vision Transformers and large language models. As a result of the empirical study, our contributions and conclusions are as follows: \(\bullet\) In the process of data propagation throughout the depth of the DNN, the properties of data representations change. In our work, we show a significant difference in the evolution of data in DNN belonging to different families of architectures: based on convolutions and attention mechanisms. \(\bullet\) During the training of the DNN, the geometric and topological properties of the embedding space evolve, the model tries to learn the highest quality representations.We propose a way to estimate the expected performance and generalization ability of models based on representation analysis without using the standard test-training split. ## II Related Work Approaches based on topology and geometry can give a new vision of the above problems related to understanding deep learning algorithms and finding their original, effective solution by formulating a descriptive model of learning processes and the structure of neural networks. Also relevant for our study are works that systematically study and compare the features of different architectures according to various criteria. The available results can be divided into 3 groups: topological and geometric aspects of learning and performance of DNNs, research on the internal representation of DNNs, and comparative analysis of neural networks. Some articles aim to clarify the processes that take place inside a DNN during training and inference, while others suggest improvements to existing DL solutions. Particular attention is paid to the analysis of the generalizability, capacity and expressiveness of deep learning models using topology and geometry methods. Gus in [2] raises the question of whether the learning and generalizability of a DNNs depends on the homological complexity of a particular dataset. On the other hand, authors of [3] and [4] investigate the performance of DNNs depending on the ID of the training dataset and notice that the generalization error does not depend on the extrinsic dimension of data. In [5] it is proved that a DNNs can successfully learn with help of SGD to solve a binary classification problem when a number of conditions on the width, length and sample complexity are met with certain geometric properties of the training dataset. There is also a series of works that consider the expressive power of DNNs through the analysis of the topology of the decision boundary [6-8]. In some works, a computational graph of a neural network is considered [9-10]. It was proved [77] that the Hausdorff dimension of the SGD trajectory can be related to generalization error. [78] consider the \(\mathrm{PH}_{\mathrm{dim}}\) of the learning trajectory in the parameter space, in the optimization SGD process, this is the first work that connects \(\mathrm{PH}_{\mathrm{dim}}\) and theoretical problems of deep learning. [11] analyzing the space of weights in convolution filters, the authors come to the conclusion that the topological features of this space change during the learning of CNN. To understand the learning process of DNNs, it is important to have an idea of the dynamics and changes in geometric properties within the space of embeddings on different layers. The paper [17] argues that the learning process of DNNs is associated with the untangling of object manifolds, on which the data lie, when passing through the layers of the DNN, and a quantitative assessment of the untangling is proposed. The authors of [18] analyze the change in the geometry of object manifolds (dimension, radius, capacity) during training and argue that as a result of the evolution of object manifolds in a well-trained DNN, by the end of the hierarchy of layers, manifolds become linearly separable. [19] focus on the problem of memorization and generalization when training DNN and come to the conclusion that memorization occurs on deeper layers due to a decrease in the radius and size of object manifolds. [20] also consider transformations of data in a DNN and attempts to formulate deep learning theory in terms of Riemannian geometry. In [67] the ability of DNN to learn an efficient low-dimensional representation is considered, and [68] deals with the DNN-based transformation of data into minimal representation. Paper [79] uses persistence landscapes to analyze the dynamics of topological complexity across all layers of the neural network, according to their results, topological descriptors are not always simplified in the learning process. In many ways, our work is a continuation and improvement of the ideas outlined in [21], where it is argued that when passing through the layers of a FC neural network, the data topology is simplified and the Betti numbers are reduced, and the ReLU activation function contributes to better performance. But the methodological problem of this work is that it is necessary to calculate the Betti numbers for a fixed scale parameter. Our work uses TDA and removes this need for epsilon search. In addition, we make use of the results of [22], where shows the dynamics of ID when passing data on different layers throughout the depth of the model and its relationship with performance and generalization gap using the example of several modern CNNs architectures, the authors conclude that neural networks transform data into low-dimensional representations. Paper [23] shown that clusters with different density peaks are formed on different layers, which reflects the semantic hierarchy of the ImageNet. In [12] mean-field-theory is used to analyze the geometric properties of data in the internal representation of the BERT language model.Work [13] compares different DNN architectures from decision boundary perspective.In [65] the problem of calibrating modern architectures into classification task is explored. Paper [14] also shows that CNNs and ViT \(\mathtt{\ast}\)see\(\mathtt{\ast}\) the data representation in different ways. But in our work, we come to the conclusion that models of different architectures transform the geometric and topological properties of data in different ways, which is confirmed experimentally. ## III Preliminaries We can consider various aspects of deep neural networks: decision boundaries, loss function landscape, functional graph, weight dynamics during optimization. But it is also very important to consider internal representations, analyze their dynamics at different epochs of learning and at depths. It is possible to analyze data properties from different points of view, including using methods of applied algebraic topology and geometry. In this section, we present a definition and a brief description of the topological data analysis and manifold learning concepts that we will use to explore data properties within a DNN. ### _Deep neural networks_ A deep neural network is a function DNN: \(\mathrm{R^{x}}\rightarrow\mathrm{R^{y}}\) defined by the composition DNN = softmax\(\mathrm{f_{a^{0}}}\)\(\mathrm{.}\)\(\mathrm{. ### _Persistent homology_ The main tool for topological data analysis is the concept of persistent homology. This construction summarizes the process of changing the Betti numbers during the filtration. Details and more deep theoretical introduction can be found in [11, 83, 24 - 26]. To be able to work with objects in vector space X, it is necessary to construct simplicial complexes K from them. We use the Vietoris-Rips complex K(X; r), {\({}_{\text{i0,...,i,s}}\)} is a simplex of K(X; r) if balls of radius r around \({\text{x}_{\text{i0,...,x}}}\) is intersect pairwisely. For a simplicial complex K, H(K) denotes the vector space of i-th simplicial homology of K (coefficient field F is less important for us, hence omitted). \(\beta\)(K) = dim H(K) denotes the i-th Betti number. For i = 0, 1, 2 this number counts the number of connected components, cycles, and cavities in K respectively. An increasing sequence of simplicial complexes is called a filtration: {K}\({}_{\text{i}}\)\({}_{\text{i}\in Z\geq 0}\)) = K\({}_{0}\)\(\subseteq\) K\({}_{1}\)\(\subseteq\) K\({}_{2}\)\(\subseteq\)\(\ldots\)\(\subseteq\) K\({}_{\text{s}}\). Persistent homology is an invariant of a filtration, which tracks the change in homology throughout the filtration. The persistent homology is encoded by the barcode: that is a finite collection of triples (\({\text{t}}_{\text{birth}}^{\text{n}}\), \({\text{t}}_{\text{death}}^{\text{n}}\), \({\text{deg}}^{\text{n}}\) ), where \({\text{t}}_{\text{birth}}^{\text{n}}\) is the birth time of n-th homological feature, \({\text{t}}_{\text{death}}^{\text{n}}\) its death time, and \({\text{deg}}^{\text{n}}\) its degree (Fig. 1). We restrict to degrees 0, 1 in our work due to the resource-intensive calculation of higher degree. In \({\text{t}}_{\text{birth}}^{\text{n}}\)\(-{\text{t}}_{\text{death}}^{\text{n}}\) the lifetime of the n-th homology feature, called lifespan, it is obvious that it cannot be negative. A long interval in barcode means that we have a sufficiently long-lived n-homology, which is a persistent topological feature, it helps to evaluate the topological properties of a space. An equivalent representation of the barcode is the persistent diagram. This is a plane with coordinates of the birth \({\text{t}}_{\text{birth}}\) and death \({\text{t}}_{\text{death}}\) times, each homology is indicated by a point with a color corresponding to the degree. The power-weighted sum of N lifespans for the i-th homology degrees is denoted as follows \[{\text{E}}_{\alpha}^{\text{i}}(\text{X})=\sum_{\text{n=1}}^{\text{N}}{\text{I} }_{\text{n}}^{\alpha} \tag{1}\] where \(\alpha\geq 0\), it is noted in [27] that \({\text{E}}_{\text{n}}^{0}(\text{X}_{\text{n}})\) it is equal to the length of Euclidean minimal spanning tree (MST) of set of n points in \({\text{R}}^{\text{d}}\). \({\text{E}}_{\alpha}^{\text{i}}(\text{X}_{\text{n}})\) can be understood as the cyclomatic capacity of the data, the larger this value, the more obvious the cycles. Finding a geometric interpretation of \({\text{E}}_{\alpha}^{\text{i}}(\text{X}_{\text{n}})\) could be a topic for future research. \({\text{E}}_{\alpha}^{\text{i}}(\text{X}_{\text{n}})\) we will call topological descriptors and use them to analyze the properties of data \(\text{X}_{\text{n}}\) in our work. Numerical experiments and calculations of persistent diagrams were carried out using Ripser library [28]. ### _Manifold learning and fractal dimension_ We are increasingly faced with very high-dimensional data in computer vision problems, sound signal processing, in the analysis of gene expression, and others. According to the manifold hypothesis [30], the data X lies on a low-dimensional submanifold: X \(\subseteq\) M\({}^{\text{n}}\)\(\subseteq\) R\({}^{\text{d}}\), where d - extrinsic dimension, n - ID. [31] Proved that given sufficient sample complexity, we can model a low-dimensional representation of the data with some error. It is possible to divide the methods for estimating the ID into two classes [32, 33]:1) Local methods estimate the dimension at each data point from its local neighborhood, and then calculate the average over the local estimates of the ID: NN algorithm [34], MLE [35], nonlinear manifold learning methods. 2) Global methods estimate the dimension using the entire dataset, assuming that the dataset has the same dimension throughout: PCA, MDS, k-NNG, GMST [36]. This group also includes fractal-based methods: Hausdorff dimension, correlation dimension and box-counting dimension. If we consider the persistent diagrams obtained from a set of points in R\({}^{\text{d}}\), it is often possible to notice an accumulation of homological features in the diagonal area and near zero, they are born and die quickly. These points are considered to be topological noise that does not carry useful information. However, the decay rate of <<noise>> depends on the size of the submanifold on which the set of points lies. [39] introduces the concept of Persistent homological fractal dimension PH\({}_{\text{dim}}\), generalizing [38] for any homology group dimensions and based on [76]. X - bounded subset of a metric space and \(\mu\) a measure defined on X, for each i \(\in\) N define the PH\({}_{\text{dim}}\) of \(\mu\): \[\text{PHdim}_{\alpha}^{\text{i}}(\mu)=\frac{\alpha}{1-\beta} \tag{2}\] where \[\beta=\lim_{n\rightarrow\infty}\text{sup}\frac{\log\left(\mathbb{E}\left({ \text{E}}_{\alpha}^{\text{i}}(\text{x}_{1},\ldots\text{x}_{\text{n}})\right) \right)}{\log(n)} \tag{3}\] and \(\text{x}_{1,\ldots,\text{x}_{\text{n}}}\) are sampled independently from \(\mu\). That is, \(\text{PHdim}_{\alpha}^{\text{i}}(\mu)=d\) if \({\text{E}}_{\alpha}^{\text{i}}(\text{x}_{1},\ldots\text{x}_{\text{n}})\) scales as \(\frac{d-\alpha}{n}\) and \(\alpha\geq 0\). Larger values of \(\alpha\) give relatively more weight to large intervals than to small ones. In other words, the persistent homological dimension can be estimated by analyzing the asymptotical behavior at n \(\rightarrow\infty\) of \({\text{E}}_{\alpha}^{\text{i}}(\text{x}_{1},\ldots\text{x}_{\text{n}})\) for any i. [39] proved that if \(\mu\) satisfies the hypothesis of Ahlfors regularity, then \(\text{PHdim}_{\alpha}^{0}(\mu)\) equals the Hausdorff dimension of the support of \(\mu\). In practice, the PH\({}_{\text{dim}}\)\(\alpha(\mu)\) = d can be calculated as follows: for real m\({}_{1}\), m\({}_{2}\),...,m\({}_{\text{k}}\) logarithmic values \(\log_{10}(\mu)\) = m\({}_{i}\), we randomly sample n points from X and calculate the \({\text{E}}_{\alpha}^{\text{i}}(\text{x}_{1},\ldots\text{x}_{\text{n}})\). We then use linear regression to fitting the power law for obtained values n and \({\text{E}}_{\alpha}^{\text{i}}(\text{x}_{1},\ldots\text{x}_{\text{n}})\). In all experiments in our work, the calculations were carried out for the case i = 0 and \(\alpha\) = 1, and the PHdim\({}_{1}^{0}(\mu)\) will be denoted PH\({}_{\text{dim}}\). We restrict ourselves to i = 0, because this will allow us to get all the comprehensive geometric information. Semantically, different PH\({}_{\text{dim}}\) is expressed in the diversity. The larger the ID, the more diverse the data (Fig 2). Fig. 1: An example of a barcode with discrete time t, green color denotes homology of dimension 0, blue – 1. Unfortunately, the problem of existing algorithmic methods for calculating the ID is that for a correct estimate, an exponentially large amount of data is needed, which leads to a systematic error and a significant underestimation of the obtained ID [33]. According to [4] we can control the upper bound ID of the dataset: generate synthetic data using a BigGAN, to set the necessary upper bound d for the ID, we fix 128 - d elements of the hidden vector equal to zero. We generate synthetic datasets with different ID for assessing the accuracy of the PH\({}_{\text{dim}}\) method and comparing with other approaches. The generated examples with didterent ID are shown in Fig. 2. In table 1 we compare the accuracy of PH\({}_{\text{dim}}\) with other ID estimation approaches: Correlation dimension (CorrDim) [74], TwoNN [34], Maximum likelihood estimation (MLE) [35]. As you can see, PH\({}_{\text{dim}}\) estimates the ID more accurately than others. The datasets from Table 1 are synthetic data generated with BigGAN by controlling ID. ## IV Evolution of topological descriptors and fractal dimension in deep models To develop new, high-performance deep networks architectures and solve open problems in the field of deep learning, it is necessary to understand the essence of the processes that occur during training, as well as what affects the expressive power and ability of deep learning models to generalization. DNN learns an internal low-dimensional representation of the data manifold on different layers and deep learning models training can be interpreted in terms of evolution of embedding manifold representations, changes in topology and geometry of data. An embedding manifold \(\text{X}_{n}\subseteq\text{R}^{d}\) is a low-dimensional representation of the object data manifold within a DNN, where d - the width of the layer. In the process of passing the data manifold from block to block along the all depth, the embedding manifold's characteristics change. Here we track the change in topological descriptors and PH\({}_{\text{dim}}\) at different depths of model and associate them with the success of training in image and text classification tasks. Based on our experiments, we test the hypothesis that, in terms of topology and internal representation geometry, deep neural networks of different architectures transform data in different ways. We are clarifying exactly how the architecture affects data dynamics. ### _Experimental setup_ The experiments include a systematic comparison of DNNs in terms of analyzing the dynamics of the embedding space in supervised classification regime. We consider several families of architectures: * Deep networks based on the convolution mechanism: ResNet [41], SE-ResNet [42], MobileNetV2 [43], VGG-18 [44]. * VisionTransformer based on the attention mechanism that work with images as with sequences of tokens. * ConvMixer [57] model is a hybrid of the architectural features of CNN and ViT, it combines the advantages of both approaches to architecture design. It abandons the classic pyramidal structure of CNN and uses image partitioning, as in ViT. * Large attention-based language model (LLM) BERT [58], have replaced the generation of RNN language models. BERT consists 12 blocks, each encoder layer uses bidirectional attention, which allows the model to consider context from both sides of the token. RoBERTa [81] is an improvement on BERT. Datasets in image classification task: CIFAR-10 [45], Street View House Numbers [46], ImageNet [47]. For the task in the NLP domain, we use different emotional coloring tweets dataset [80]. The tweets dataset includes 8 basic emotions: anger, anticipation, disgust, fear, joy, sadness, surprise, and trust. For correct comparison of models with each other, all CNN consist of 10 structural blocks, and 128 channels, in order to exclude the influence of the ambient space. ViT also consists of 10 blocks. GlobalAveragePooling operations are used to vectorize feature maps in CNN, and first sequence token for Transformers. Each model was trained with an accuracy of 95% or more on the training dataset using the Adam [53] optimizer with adaptive learning rate. Train/test split 0.8/0.2, hardware specifications: Nvidia GeForce GTX 3080Ti, Intel Core i7-10700K, 16 GB of RAM. ### _Experiments_ The design ideology of modern deep learning architectures is based on the principle of structural blocks (moduls). The architecture consists of specific blocks connected in series, which include a set of different operations, such as activation, 1D, 2D and depthwise convolution, attention, pooling, skip-connections, compression, batchnormalization, etc. Different configurations and combinations of these operations give different efficiency, accuracy, and computational complexity and at the same time affect differently the change in the geometry of the object manifold. We analyze the embedding representation at the output of each structural block in CNNs, ViT, ConvMixer and LLMs. One of the main results of this section is the demonstration of the behavior of the topological descriptors and PH\({}_{\text{dim}}\) of the data embedding manifold on different blocks during training on CIFAR-10 and text dataset at different epochs. In Fig. 3, 4, 5, each line indicates the dynamics of the topology and geometry of the data over the entire depth, line has its own color from bright yellow to blue, which indicates the accuracy on the test dataset at this stage of training. For experiments, we feed a randomly selected batches of 300 examples from train dataset of each class to the input of the DNNs several times, and then average the results across batches and over all 10 classes. Fig 2: Relationship between ID and diversity of the Castles image dataset, rows correspond to different ID According to the observation (Fig.3) of the evolution of the topology of a train dataset manifold when passing through a CNNs, in the process of training a DNN to learn more efficiently and faster to lower the values of topological descriptors at the all depth. On different architectures of CNN, the evolution of the data manifolds occurs in different ways, this may be a consequence of the unique arrangement of structural modules (blocks) that underlie a particular architecture. In the case of a ResNet, the dynamics of a decrease in topological descriptors shows a decrease from the very first blocks, and in the case of MobileNetV2 with linear bottleneck and SE-ResNet with squeeze-and-excitation block, the topology is simplified from the middle of the layer hierarchy. Experiments show that the dynamics of topological and geometric characteristics of models based on the mechanism of convolutions and attention is different. Fig. 4: Changing the topological descriptors and PH\({}_{\text{kin}}\) inside ViT and ConvMixer across all depth at different epochs. Dataset CIFAR-10 Fig. 5: Changing the topological descriptors and PH\({}_{\text{kin}}\) inside BERT and RoBERTa across all depth (12 encoder layers) at different epochs. Fig. 3: Change in topological descriptors and PH\({}_{\text{kin}}\)(y-axis) on different blocks of CNNs during training at different epochs, x-axis – relative depth from 0.1 (output of 1 block) to 1 (last output fully connected layer). Columns denote various CNN architectures, rows denote topological and geometric properties. Dataset – CIFAR-10 A decrease in topological descriptors \(\text{E}_{1}^{0}(\text{X}_{\text{n}})\) indicates that the classes in the dataset \(\text{X}_{\text{n}}\) are becoming more compact. \(\text{E}_{1}^{1}(\text{X}_{\text{n}})\) indicates that the number of noticeable cycles in the data is decreasing, which also indicates about compactification and structural simplification. While we observe a decrease in topological descriptors over the entire depth in CNN, in ViT the values of these descriptors almost do not change, however, depending on the epoch of their training, the indicators are smaller (Fig 4). In the case of \(\text{PH}_{\text{dim}}\), empirical observations also show a different picture, \(\text{PH}_{\text{dim}}\) increases at intermediate layers in ViT. It is important to note that a sharp decrease in \(\text{PH}_{\text{dim}}\) on last output fully connected layer is expected and is explained by the small dimension of the ambient space. But in CNN, we see the hump shape as the data evolves throughout the depth. The decrease in topological features in the CNN can be associated with the pyramidal hierarchical structure of the CNN, in which the information obtained at the first ones is generalized in deeper layers. In ViT there is no hierarchical structure and image resolution does not change with depth, all layers have access to the same knowledge representation. ConvMix is a hybrid of CNN and ViT, the dynamics of changing topological and geometric properties in the embedding space is more similar to CNN (Fig 4.b). In the embeddings space of large language models BERT (Fig. 5a) and RoBERTa (Fig. 5b), geometric and topological properties change throughout the depth, but in a different way. The topological descriptors of not well trained models do not decrease over the entire depth, but rather increase. The trajectory of the \(\text{PH}_{\text{dim}}\), unlike CNN and ViT, does not reproduce the shape of the hump so clearly. This observation suggests that in the internal representation, large language models \(\text{\soutrelbar}\) and transform data in a different way. In the process of training on different layers, the data form clear clusters that correspond to their classes. As shown in this section, the internal presentation of data is simplified across the layers, if one measures simplicity by natural topological descriptors. We can propose the following explanation for the phenomenon observed in Fig. 3,4,5: In an ideal well-trained DNN the internal representation at the last layer should represent a collection of untangled and separated clusters, ideally a finite set of points. A finite set of points has \(\text{PH}_{\text{dim}}=0\). So it is natural to expect that \(\text{PH}_{\text{dim}}\) gets reduced throughout the layers, which is consistent with observations in next chapter. For all datasets within the ResNet representation, there is the same tendency to simplify topological descriptors, but in different ways. On fig. 6a, 6b show the difference in data dynamics in the same architecture but with different datasets: CIFAR-10 [45], 10 classes 32x32x3 images, Street View House Numbers (SVHN) and 10 classes corresponding to "buildings" from ImageNet 64x64x3. The trend towards simplification is observed for all classes in datasets; in Fig. 6a, 6b, all classes are indicated by thin lines of different colors. As shown in Fig. 6a, b the topological properties for the SVHN dataset are simplified faster, indicating that this is an easier task for ResNet. We evaluate the change in topological descriptors and \(\text{PH}_{\text{dim}}\) on intermediate ResNet-101 layers' representation with different activation functions. As you can see in the Fig. 6c, 6d, different activation functions make different contribution to the topology and \(\text{PH}_{\text{dim}}\) change; with the Swish activation function (black line), model has better accuracy on the test dataset in our experiments, and according to [48] Swish improves CNN performance over ReLU (blue line) and Sigmoid (yellow line), helping to alleviate the vanishing gradient problem. The ReLU, ReLU-6 and ELU activation functions are more successful in practice than Tanh and Sigmoid, which is consistent with the dynamics of topological simplification of the train dataset manifold in our experiments. Success of DNN with ReLU is explained by they are not homeomorphic map [21]. Fig. 6: Changing the topological descriptors and \(\text{PH}_{\text{dim}}\) inside ResNet: a, b) Different datasets, thin lines indicate different classes. c) Influence of activation functions on changing topological descriptors. d): Influence of activation functions on changing \(\text{PH}_{\text{dim}}\). Fig. 7: The dynamics of \(\text{PH}_{\text{dim}}\) face anti-spoofing manifold. a) Binary classification. b) Arcface face recognition. We analyze how different datasets are transformed in the internal representation of neural networks in terms of PH\({}_{\text{dim}}\), Fig. 7 explains on the experiments in Fig. 6. Real face and spoofing examples face were chosen as datasets. Spoofing examples are a type of attack on face recognition systems where a physical photo or screen of a photo is shown instead of a person's real face [54]. We show here that the PH\({}_{\text{dim}}\) of the real and spoofing faces dataset [59] in the internal representation of the DNNs changes as it passing through all the layers (Fig 7). In the binary classification problem (spoof/real, 2000 examples per each class), the dynamics of the face data manifold repeats the shape, as in the Fig. 3. In the problem of 10 persons face recognition, the VGG [44] with fixed 32 width architecture is used with a loss function ArcFace [62], in the output space the objects lie on a 32-dimensional hypersphere, which simplifies the comparison of objects of the same class with each other. PH\({}_{\text{dim}}\) in this case does not correspond to the shape of the hump. Examples of spoofing attacks have a higher PHdim than real faces, due to the presence of effects related to glare, texture, lighting and other effects, the visual complexity of spoofing attacks is higher. An estimate of the PH\({}_{\text{dim}}\) can be useful to determine the quality and diversity of a spoofing examples dataset. Tests have shown that the CelebA-Spoof [60] dataset PH\({}_{\text{dim}}\) = 14, while the screen attack dataset from [59] PH\({}_{\text{dim}}\) = 10. This can be explained by that CelebA-Spoof presents a wider range of spoof attack types, not just screen attacks. ### _Discussion and comparison with other works_ Here we will discuss how the results in this chapter relate to existing research about comparing different architectures. The gradual increase in the PH\({}_{\text{dim}}\) in CNN up to the middle of the depth can be explained by the pyramidal structure of CNN models. Low-level features are extracted in the first layers, and high-level features are extracted in the intermediate layers closer to the middle. Semantically more complex feature maps with more information are formed, which explains the increase of PH\({}_{\text{dim}}\). This correlates with [64], where an analysis of "visual complexity" of feature maps on different layers is proposed and it is shown that visual complexity is higher in the middle layers than in the first and last layers. One can interpret the decrease in PH\({}_{\text{dim}}\) on the last layers as the model tends to learn a simpler and more efficient representation of the extracted features on the previous layers. The dynamics of feature maps on the surface and deep layers at different stages of learning does not differ significantly for CNN and ViT (Fig. 8a, 8c). We see that CNN models recognize visually and semantically more complex feature maps that carry more information, so we can observe an increase in ID on these layers. ViT do not have a hierarchical structure, but at the same time, they themselves extract more and more semantically complex features in the learning process. In BERT, at different learning epochs, PH\({}_{\text{dim}}\) decreases at all intermediate layers, not just at the last one (Fig. 8d). This indicates a fundamentally different logic of knowledge processing in the fields of image and text processing. The paper [14] presents a systematic comparison of CNN and ViT architectures in terms of centered kernel alignment (CKA) similarity. Many results of our work confirm the mentioned empirical study, while we use geometry and topology methods to analyze representations. We notice the following similarities: the representation structure of ViT and CNN from the CKA similarity point of view shows significant differences: ViT have very similar representations throughout the depth of the model, while ResNet models show much less similarity between the lower and deeper layers. This correlates with our observations. The higher the ID of the embeddings in the intermediate layers, the more "qualitatively" the deep model is trained, but the higher the ID in the output layer, the less the test accuracy of the model. In the case of ViT and CNN in deep and shallow layers, PH\({}_{\text{dim}}\) increases with each training epoch. This may indicate that intermediate layers in CNN and ViT are trying to learn more complex visual representations with more and more information with each epoch. The conclusion of the chapter is that we tested the hypothesis that the data transformation in the internal representation of different architectures is very different. The statement that the model gradually reduces topological properties is not true for all types of architectures; The statement is true for CNN and BERT. But this does not apply to ViT - at all depth levels, the topology almost does not change. Also, not very well trained LIM do not reduce topological properties while CNNs do, although not gradually. We proposed a geometric interpretation of the phenomenon of changing the semantic complexity of feature maps in CNN, in the learning process, the fractal dimension on intermediate layers, except for the last ones, increases, also for architectures based on the attention mechanism (ViT), we observe similar behavior. Fig. 8: PH\({}_{\text{dim}}\) on first, middle and last layers for all training epochs of ResNet, SE-ResNet, ViT and BERT models. ## V Influence of topology and geometry on the generalization ability of deep models Neural network generalizations are the ability to learn from the training set to work effectively with data that was not in the training dataset. The measure of generalization in classification problems is determined by the concept of a generalization gap - the difference in the accuracy metric between the indicators on the test and train datasets. In addition to classical measures of DNNs expressivity, such as VC-dimension [66] or Rademacher complexity [74], there are many approaches to estimating generalization error [49 - 52]. [9, 22, 72, 78] demonstrate methods for analyzing the performance and expressive power of DNN based on geometric and topological characteristics. In this section, we test the hypothesis that neural network training is associated with a gradual simplification of topological descriptors and a decrease of fractal dimension in the internal representation al last layer. We propose a way to evaluate the performance and generalizability of CNN and Transformer models in image and text classification problems. We use PH\({}_{\text{dim}}\) to analyze the dynamics of the geometric properties of the neural network output representation during training at different epochs. PH\({}_{\text{dim}}\) was chosen as a more accurate and mathematically sound way to estimate ID than others (Table 1). We also demonstrate the relationship of topological descriptors to the performance of DNNs trained with different hyperparameters. ### _Evolution of topological descriptors and PH\({}_{\text{dim}}\) in training process_ If we consider the last output layer after softmax activation as the final representation R\({}^{\text{k}}\) of the DNN in the k-classification problem, then we can see a statistically significant relationship between the PH\({}_{\text{dim}}\) of the train dataset batch in this representation and the test accuracy (Fig. 9). We can evaluate the performance of models at different epochs without using the standard split test/train, which is important in conditions of limited data. The fact that PH\({}_{\text{dim}}\) tends to 0 during the learning process can be related to the theory of Neural Collapse (NC) [40, 55], according to which, in the output feature space R\({}^{\text{k}}\), data clusters (classes) are concentrated around centroids lying at the vertices of the Simplex Equisangular Tight Frame [55]. And PH\({}_{\text{dim}}\) = 0 is the stage when the clusters corresponding to the classes collapse to a point and the DNN seems to be trying to reach this state during the learning process. This is consistent with Fig.8, where it is empirically shown that the DNN tends to learn the most efficient low-dimensional representation on the last layer, and the rate of PH\({}_{\text{dim}}\) decrease affects the learning accuracy. Fig. 10: Dependence between Ej(X), obtained from the internal representation X of the last layer and the accuracy on the test set in the learning process at different epochs. a) ResNet, r = -0.92. b) SE-ResNet, r = -0.965. Fig. 9: Dependence between PH\({}_{\text{dim}}\), obtained from the internal representation of the last layer output and the test accuracy at different epochs. Pearson’s correlation coefficient denoted by r. As shown in Section 4, the learning of CNN affects the dynamics of topological descriptors throughout the depth. We can see (Fig. 10) the relationship between topology of embedding space in last intermediate layer and the learning epoch. With each training step and increasing accuracy, the topological descriptors decrease, which confirms the hypothesis that the learning process of a neural network is associated with a gradual simplification of the topology. ### _Generalization gap estimation_ To estimate the generalization error, it is necessary to consider not one model at different learning epochs, but a family of trained models with different accuracy on the test data. If the learning process can be understood as a simplification of the topology of the data manifold across all depth, then the models with the simplest data on the last layer Xout have the best performance in test dataset. Topological descriptors as well as PHdim decrease throughout the depth of the DNN, and they are similarly generalizing ability predictors. Our hypothesis is supported and a statistically significant inverse correlation r = -0.9 (Pearson's correlation coefficient) can be observed between the topological description E\({}_{1}^{0}\)(Xout) and the test accuracy error (difference between train accuracy and test accuracy), and this can be a reliable predictor of DNN generalization in the classification problem (Fig 11, 12). To test a topological predictor, only the train dataset is required without the need for a test data, as in Section 5.A. For experimental verification, a dataset of trained 50 CNN-models of the family of architectures ResNet-32, ResNet-56, ResNet-110 (Fig 11) with different learning hyperparameters was formed: regularization, learning rate, weight decay, batch size, with or without augmentation. All models are trained on the CIFAR-10 dataset to 95-99% train accuracy. To test the approach for assessing the generalizing ability (Fig 12) in the case of other architectures, the Vision Transformer architecture was chosen with a depth of 10 transformer layers, embedding dimension 128, 4 attention heads, patch size 6. And 16 ViT models were trained with different hyperparameters, as well as CNN. In this section, we have demonstrated that the topological and geometric invariants of the internal representations at the last layer are closely related to the learning process. These invariants can be predictors of the performance and generalizability of deep models across different architectures. ## VI Conclusions and future work As a result of our empirical study, we have attempted to clarify some aspects of DNNs learning based on the topology and geometry of the internal representation. Several hypotheses were tested and it was shown that neural network architecture significantly influences knowledge representations and data transformation across the depth of the model. Because of the structural features and differences of CNN, ViT and large language models transform data in different ways. How deep neural networks "see" and understand, data can be interpreted geometrically. We conclude that the learning process of DNNs is related to changes in the topological descriptors and fractal dimensionality of the data manifold. It is shown that the performance and generalization ability of classifiers can be related to the topology and geometry of the data. Future research may be focused on the analysis of analogies between neuroscience, biological models of the nervous system and artificial neural network models of different architectures, on fundamental similarities and differences. The topic of understanding the decision boundarys of neural networks in terms of combinatorics and polyhedral topology is also very promising. A more theoretical understanding of the observations obtained in this paper may be a topic for future research. ## VII Acknowledgment The article was prepared within the framework of the HSE University Basic Research Program.
2302.04852
SparseProp: Efficient Sparse Backpropagation for Faster Training of Neural Networks
We provide a new efficient version of the backpropagation algorithm, specialized to the case where the weights of the neural network being trained are sparse. Our algorithm is general, as it applies to arbitrary (unstructured) sparsity and common layer types (e.g., convolutional or linear). We provide a fast vectorized implementation on commodity CPUs, and show that it can yield speedups in end-to-end runtime experiments, both in transfer learning using already-sparsified networks, and in training sparse networks from scratch. Thus, our results provide the first support for sparse training on commodity hardware.
Mahdi Nikdan, Tommaso Pegolotti, Eugenia Iofinova, Eldar Kurtic, Dan Alistarh
2023-02-09T18:54:05Z
http://arxiv.org/abs/2302.04852v1
# SparseProp: Efficient Sparse Backpropagation ###### Abstract We provide a new efficient version of the backpropagation algorithm, specialized to the case where the weights of the neural network being trained are _sparse_. Our algorithm is general, as it applies to arbitrary (unstructured) sparsity and common layer types (e.g., convolutional or linear). We provide a fast vectorized implementation on commodity CPUs, and show that it can yield speedups in end-to-end runtime experiments, both in transfer learning using already-sparsified networks, and in training sparse networks from scratch. Thus, our results provide the first support for sparse training on commodity hardware. Machine Learning, SparseProp, Efficient Sparse Backpropagation ## 1 Introduction The significant computational costs of deep learning have led to massive interest in approaches for leveraging _sparsity_ in neural networks, which have been investigated in great breadth and depth (Hoefler et al., 2021). On the inference side, there is already emerging algorithmic and system support for sparsity on both GPUs (Mishra et al., 2021; Gale et al., 2020) and CPUs (Elsen et al., 2020; NeuralMagic, 2022), as well as a wide range of methods for obtaining models which are both highly-sparse and highly-accurate. A new frontier in the area is _accurate and efficient sparse training_. On the algorithmic side, there are several interesting proposals for _sparse training_ algorithms (Dettmers and Zettlemoyer, 2019; Kusupati et al., 2020; Evci et al., 2020; Jayakumar et al., 2020; Schwarz et al., 2021), i.e. variants of stochastic gradient descent (SGD) which aim to keep as many weights as possible sparse during training. Another interesting related approach is _sparse transfer_(Zafrir et al., 2021; Chen et al., 2021; Iofinova et al., 2022; Kurtic et al., 2022), by which models sparsified on a large pretraining corpus are then used for _transfer learning_ on different tasks, while preserving the sparsity mask. Despite this progress on the optimization side, the vast majority of these approaches lack _system support for fast training_, in that they do not provide any practical speedups. This is because the weight sparsity introduced is _unstructured_, which is notoriously hard to leverage for computational gains. Specifically, there is no general implementation of backpropagation that can leverage unstructured weight sparsity for practical speedup on common hardware. At the same time, approaches leveraging _block sparsity_(Mishra et al., 2021; Gray et al., 2017) can only reach lower sparsity without significant accuracy drops, and require specialized training algorithms (Lagunas et al., 2021; Jiang et al., 2022). As such, unstructured weight sparsity is often dismissed as a practical way of accelerating model training. **Contribution.** We contradict this conventional wisdom by presenting a new vectorized implementation of backpropagation (Rumelhart et al., 1986), designed to be efficient in the case where the weights of the neural network are _sparse_, i.e. contain a significant fraction of zero values, and show its potential for practical speedups in common edge training scenarios, for both vision and language tasks. More precisely, our algorithm, called SparseProp, is general in the sense that 1) it applies to arbitrary sparsity patterns, 2) general layer types, and 3) can be efficiently vectorized using standard CPU-supported approaches. The asymptotic complexity of the algorithm is _linear_ in the _layer density_, i.e. the number of non-zero weights in the layer, providing proportional runtime improvements to the weight sparsity, for both linear and convolutional layers. To illustrate practical efficiency, we provide a fast vectorized implementation of SparseProp aimed at general-purpose Intel and AMD CPU architectures. Specifically, our implementation provides drop-in replacement implementations for standard layer types, and only relies on widely-supported AVX2 instructions. We show that SparseProp can lead to practical runtime improvements both on single sparse layers, validating our linear sparsity scaling claims, as well as on end-to-end training of sparse models. Specifically, we provide results for a preliminary integration with Pytorch (Paszke et al., 2019), which can run sparse backpropagation for linear and convolutional layers, covering most popular model families. As such, SparseProp can provide direct support for methods like Gradual Pruning (Zhu & Gupta, 2017), RigL (Evci et al., 2020) or AC/DC (Peste et al., 2021), which assume a fixed sparsity mask for any fixed forward and backward pass, and can be modified to support more complex methods (Jayakumar et al., 2020), which specify different sparsities for weights and gradients. We believe it is the first implementation to do so on commodity hardware. Our end-to-end experiments aim to make the case that sparsity can be a viable option for DNN training _at the edge_. That is, we explore settings where a device with moderate computational power (e.g., a CPU with a limited number of cores) performs either _sparse transfer_ or _from-scratch sparse training_ over a specialized task. We investigate sparsity-versus-accuracy trade-offs in two model/task combinations: 1) ResNets (He et al., 2016) applied to twelve popular vision tasks (Kornblith et al., 2019), and 2) a standard BERT-base model (Devlin et al., 2019) applied to GLUE language modelling tasks (Wang et al., 2018). In the _sparse transfer_ scenario, we are provided an already-sparse model pretrained on a large corpus, e.g. ImageNet (Russakovsky et al., 2015) respectively WikiText (Merity et al., 2016), and wish to finetune the corresponding sparse weights on a (usually smaller) target dataset. This application has gained significant popularity (Zafrir et al., 2021; Chen et al., 2021; Iofinova et al., 2022; Kurtic et al., 2022), and pretrained sparse models are available for several standard tasks and models (Wolf et al., 2019; SparseZoo, 2022). In this context, we show that, for both vision and language tasks, SparseProp can lead to end-to-end sparse transfer speedups of up to 1.85x, at similar accuracies, relative to CPU-based finetuning of _dense models_ in the same environment. Measured only over backward-pass operations--and thus omitting framework-level overheads-our algorithm provides speedups of 3.6x at 95% model sparsity. In the second scenario, we examine the ability of SparseProp to provide speedups for _sparse training from scratch_, on the same series of tasks, adapting variants of sparse training (Zhu & Gupta, 2017) to our setting. Experiments show that, in this scenario, SparseProp leads to end-to-end speedups of up to 1.4x, with moderate accuracy loss. In sum, our results show that SparseProp can efficiently provide system support for CPU-based unstructured sparse training, ensuring speedups for both from-scratch training and sparse transfer. We believe our approach could lead to additional practical impact for research on sparsity, especially given that our end-to-end runtime numbers can still be improved via additional optimizations, and by mitigating external, framework-specific overheads. ## 2 Related Work **Sparse Inference.** One of the key motivations behind sparsity in DNNs is reducing inference costs. For this, an impressive number of weight pruning techniques have been introduced, e.g. (LeCun et al., 1990; Hagiwara, 1994; Han et al., 2016; Singh & Alistarh, 2020; Sanh et al., 2020). Complementing this work, there have been a number of algorithmic proposals for efficient sparse inference algorithms over DNNs, e.g. (Park et al., 2016; Han et al., 2016; Gale et al., 2020; Elsen et al., 2020), although it is known that layer-wise gains can be difficult to translate into end-to-end speedups (Wang, 2020). Nevertheless, sparse inference support is now available on both CPUs, e.g. (NeuralMagic, 2022) and GPUs (Mishra et al., 2021). Hubara et al. (2021) proposed a theoretically-justified approach for identifying sparse transposable masks matching the NVIDIA 2:4 sparsity pattern, which could be leveraged for faster training on GPUs. However, they do not provide an implementation, and, currently, GPU-based 2:4 sparsity speedups tend to be minimal (NVIDIA, 2021). **Sparse SGD-Based Training.** As noted, there has been a significant amount of work on SGD-like algorithms for _sparse training_ of DNNs, balancing accuracy while trying to maximize sparsity in the models' internal representations (Mocanu et al., 2016; Bellec et al., 2018; Zhu & Gupta, 2017; Mostafa & Wang, 2019; Lis et al., 2019; Dettmers & Zettlemoyer, 2019; Zhang et al., 2020; Wiedemann et al., 2020; Kusupati et al., 2020; Evci et al., 2020; Jayakumar et al., 2020; Peste et al., 2021; Schwarz et al., 2021). Unfortunately, a precise comparison is quite difficult, since each makes different assumptions regarding the degree of sparsity in the network's internal representations, potentially even varying the amount of sparsity between weights and gradients, e.g. (Jayakumar et al., 2020). **Sparse Training for Speedup.** Leveraging sparsity for practical speedups has been a major goal in model compression (Hoefler et al., 2021). Yang et al. (2020) proposed a specialized hardware accelerator which is specialized to the DropBack pruning algorithm (Lis et al., 2019). SWAT (Raihan & Aamodt, 2020) proposed a sparsity-aware algorithm for the case where both weights and activations have high sparsity, and showed speedups in a simulated environment. Their approach works only for specific networks, and can lose significant accuracy. More recently, Jiang et al. (2022) proposed an algorithm-hardware co-design approach, for the case of GPU-based training. Specifically, their approach imposes _block sparsity_ in GPU-friendly patterns, and leverages it for speedup. By contrast to this work, our approach considers efficient support for backpropagation for _unstructured sparse weights_, implements this efficiently for commodity CPUs, and shows that this can be leveraged for _end-to-end speedup during training. Specifically, this provides support to the vast amount of existing work on unstructured sparse training algorithms, on commodity hardware. **System Support.** Pytorch (Paszke et al., 2019) introduced partial sparse tensor support recently, while the STen (Ivanov et al., 2022) provides a general interface for such representations. Our work is complementary to this direction, as our implementation can be interfaced with Pytorch or specifically STen to provide training speedups. ## 3 The Sparse Backpropagation Algorithm ### Background **SIMD Instructions.** Fast and efficient numerical code heavily relies on Single Instruction Multiple Data (SIMD) instructions to improve performance. These instructions operate on specialized machine registers (xmm, ymm, and zmm) that contain multiple values. Our implementations currently support x86 machines that provide the standard AVX2 instruction set, which uses \(256\) bit registers, or \(8\) single precision floating point values. Table 1 provides an overview of the instructions employed by our library. Our SIMD implementation structure follows the Load-Compute-Store paradigm, where data is explicitly transferred to registers via the **loadv** and **broadcastv** instructions. Computation is performed on the data in the registers using fused multiply-add instructions **vfmadd** (\(r=a\cdot b+c\)), and the results are subsequently moved back to memory with the **vstore** instruction. Following this structure, we significantly increase performance since the data loaded into the registers can be used for multiple operations before being stored back in memory. **Backpropagation.** Let \(f(\mathbf{X};\mathbf{W})\) represent a layer (fully-connected or convolution) in a neural network \(\mathcal{N}\); \(\mathbf{W}\) represents the parameters of this layer and \(\mathbf{X}\) represents a batch of inputs. Let \(B\) be the batch size. Additionally, denote the output of this layer by \(\mathbf{O}=f(\mathbf{X};\mathbf{W})\). Let \(L\) be the loss of the whole network \(\mathcal{N}\) for this batch of inputs. Backpropagating through this layer involves calculating the gradients \(\partial L/\partial\mathbf{W}\) and \(\partial L/\partial\mathbf{O}\), given \(\partial L/\partial\mathbf{O}\). Consider the situation where we have a highly sparsified matrix \(\mathbf{W}\) that is stored as a sparse matrix. During the backpropagation process, it is necessary to calculate the gradient of this matrix. However, in practice, the full gradient of the dense matrix is often calculated, even though the pruned elements are not updated and their gradients are discarded. This can be inefficient, as it consumes a significant amount of computation and time without providing any benefits. ### The Case of Fully-connected Layers We now focus on the case where \(f(.)\) is a fully-connected layer. Assume \(\mathbf{X}\) and \(\mathbf{W}\) are \(B\times M\) and \(M\times N\) matrices, respectively. Consequently, \(\mathbf{O}=f(\mathbf{X};\mathbf{W})=\mathbf{X}\mathbf{W}\) will be a \(B\times N\) matrix. The gradients of \(L\) with respect to \(\mathbf{X}\) and \(\mathbf{W}\) are calculated as follows: \[\frac{\partial L}{\partial\mathbf{X}}=\frac{\partial L}{\partial \mathbf{O}}\mathbf{W}^{T} \tag{1}\] \[\frac{\partial L}{\partial\mathbf{W}}=\mathbf{X}^{T}\frac{ \partial L}{\partial\mathbf{O}} \tag{2}\] If we examine equations (1) and (2), we can see that the former is a General Sparse Matrix-Matrix Multiplication (SpGEMM) operation, while the latter is a Sampled Dense Dense Matrix Multiplication (SDDMM) operation. **Sparse Representation.** The matrix \(\mathbf{W}\) is stored in a compressed sparse row (CSR) format, a standard representation for sparse matrices. The non-zero values of the matrix are stored in the arrays \(W_{\mathrm{vals}}\) and \(W_{\mathrm{cols}}\), which correspond to the values and column indices of the non-zero elements, respectively. The array \(W_{\mathrm{rows}}\) encodes each row's start and end indices. For example, the non-zero values and column indices of a row \(i\) of \(\mathbf{W}\) are contained between positions \(W_{\mathrm{rows}}[i]\) and \(W_{\mathrm{rows}}[i+1]\). **Algorithm.** In Algorithm 1, we present high-level pseudocode for backpropagation in our linear layer. The calculations for (1) and (2) are performed in a single pass by utilizing the sparsity pattern of \(\mathbf{W}\), which is identical to \(\partial L/\partial\mathbf{W}\). Specifically, the result of \((\partial L/\partial\mathbf{O})\mathbf{W}^{T}\) is computed as a sparse matrix-matrix multiplication. Whereas \(\mathbf{X}^{T}(\partial L/\partial\mathbf{O})\) is computed as an SDDMM, with \(\mathrm{nnz}\) dot-products, where \(\mathrm{nnz}\) is the number of non-zero elements of \(\mathbf{W}\). In more detail, the computation is divided into \(3\) loops. The innermost loop contains the core of the computation. It computes at each iteration \(16\) floating point operations using \(2\)**fmadd** instructions: the first **fmadd** computes \(8\) entries of \(\partial L/\partial\mathbf{X}\) and the second accumulate a dot-product in a register acc. **Implementation Details.** We operate on the transposed matrices in our linear layer implementation to improve cache utilization. Specifically, in both the forward and backward passes, we operate on the transposed version of the input matrix, \(\mathbf{X}^{T}\), which is a column-major representation of \(\mathbf{X}\). By doing so, we achieve a streaming access pattern over the rows of \(\mathbf{X}^{T}\), as we see from the innermost loop Algorithm 1. \begin{table} \begin{tabular}{l l} \hline \hline **vload**(address) & load from memory address \\ **vstore**(address, a) & store a at memory address \\ **vbroadcast**(a) & fill a register with a \\ **vfmadd**(a, b, c) & return \(a\cdot b+c\) \\ **vaddreduce**(a) & return sum elements of a \\ \hline \hline \end{tabular} \end{table} Table 1: List of vector instructions used in the implementation and their semantics. Additionally, we leverage that the transpose of a CSR matrix is none other than the same matrix in Compressed-Sparse-Column (CSC) format to avoid expensive sparse transpose operations. An example computation is given in Figure 1. ### Sparse Backpropagation for Convolutional Layers We now examine convolutional layers. Denote the number of input channels by \(IC\), and the number of output channels by \(OC\). The input width and height are represented by \(M\) and \(N\), respectively, and let the kernel size be \(K\times K\). The input tensor, \(\mathbf{X}\), and the weights tensor, \(\mathbf{W}\), have dimensions \(B\times IC\times M\times N\) and \(OC\times IC\times K\times K\), respectively. For simplicity, here we only consider the case where padding is \(0\) and stride is \(1\). For larger padding and stride, the generalization is not difficult. The output tensor, \(\mathbf{O}\), will be of size \(B\times OC\times OM\times ON\), where \(OM=M-K+1\) and \(ON=N-K+1\). For \(0\leq b<B,0\leq oc<OC,0\leq p<OM,0\leq q<ON\) we have: \[\mathbf{O}[b,oc,p,q]=\sum_{ic=0}^{IC-1}\sum_{i=0}^{K-1}\sum_{j=0}^ {K-1}\mathbf{W}[oc,ic,i,j] \tag{3}\] \[.\mathbf{X}[b,ic,p+i,q+j].\] Using the chain rule, it is easy to check that for \(0\leq b<B,0\leq ic<IC,0\leq m<M,0\leq n<N\): \[\frac{\partial L}{\partial\mathbf{X}}[b,ic,m,n]=\sum_{oc=0}^{OC-1} \sum_{p=p_{s}}^{m}\sum_{q=q_{s}}^{n}\frac{\partial L}{\partial\mathbf{O}}[b, oc,p,q] \tag{4}\] \[.\mathbf{W}[oc,ic,m-p,n-q],\] with \(p_{s}=m-K+1\), and \(q_{s}=n-K+1\). And for \(0\leq oc<OC,0\leq ic<IC,0\leq i<K,0\leq j<K\), we have: \[\frac{\partial L}{\partial\mathbf{W}}[oc,ic,i,j]=\sum_{b=0}^{B-1} \sum_{p=0}^{M-K}\sum_{q=0}^{N-K}\frac{\partial L}{\partial\mathbf{O}}[b,oc,p,q] \tag{5}\] \[.\mathbf{X}[b,ic,p+i,q+j].\] It is assumed that the weight matrix \(\mathbf{W}\) is sparse. In accordance with equation (4), when a weight \(\mathbf{W}[oc,ic,m-p,n-q]\) is pruned, the multiplication and corresponding addition operations can be skipped. Furthermore, when a weight \(\mathbf{W}[oc,ic,i,j]\) is pruned, the calculation of the gradient for this parameter is not necessary, as it will not be updated, and therefore the computation outlined in equation (5) can be skipped. ``` for\(i=0\) to \(N-1\)do for\(j=\mathbf{W}_{\mathrm{coh}}[i]\)do \(\prime\)\(\prime\) repeat one weight entry 8 times*/ \(v\leftarrow\textbf{broadcast}(\mathbf{W}_{\mathrm{vals}}[j]\) /* initialize \(acc\) to zero*/ \(acc\leftarrow\textbf{vbroadcast}(0)\) \(r\leftarrow\textbf{W}_{\mathrm{rows}}[j]\) for\(k=0\) to \(B-1\)with \(k\) += 8do /* load * values*/ \(dx\leftarrow\textbf{vload}((\partial L/\partial\mathbf{X})_{r,k})\) \(do\leftarrow\textbf{vload}((\partial L/\partial\mathbf{O})_{r,k})\) \(x\leftarrow\textbf{vload}(\mathbf{X}_{i,k})\) /* compute \(8\)\(dx\leftarrow\textbf{vfindact}(do,v,dx)\) /* compute \(8\)\(acc\gets do\cdot x+acc*/\) \(acc\leftarrow\textbf{vfindact}(do,x,acc)\) /* store updated \(dx\) back*/ \(\textbf{vstore}((\partial L/\partial\mathbf{X})_{r,k},dx)\) endfor /* sum the 8 values in \(acc*/\) \((\partial L/\partial\mathbf{W})_{\mathrm{vals}}[j]\leftarrow\textbf{vaddreduce }(acc)\) endfor endfor ``` **Algorithm 1** AVX2 Linear Backward Pass **Sparse Representation.** To efficiently represent a sparse tensor, we employ a representation akin to the compressed sparse row (CSR) format used for sparse matrices. Four arrays, \(W_{\mathrm{och}}\), \(W_{\mathrm{ich}}\), \(W_{\mathrm{x}}\), and \(W_{\mathrm{y}}\), are used to store the indices, and an array \(W_{\mathrm{vals}}\) is used to store the non-zero values. Specifically, \(W_{\mathrm{x}}\) and \(W_{\mathrm{y}}\) are arrays of size \(\mathrm{nnz}\), which contain the coordinates of the non-zero values of each filter. \(W_{\mathrm{och}}\) is an array of size \(OC+1\), which encodes the start of each output channel's entries in \(W_{\mathrm{ich}}\). Finally, \(W_{\mathrm{ich}}\) is an array of size \(OC\times(IC+1)\), which encodes the indices in \(W_{\mathrm{x}}\), \(W_{\mathrm{y}}\), and \(W_{\mathrm{vals}}\) of each input channel. For example, for an output channel \(oc\), the non-zero elements of the input channel \(ic\) are stored between indices \(W_{\mathrm{och}}[oc]+W_{\mathrm{ich}}[oc\cdot(IC+1)+ic]\) and \(W_{\mathrm{och}}[oc]+W_{\mathrm{ich}}[oc\cdot(IC+1)+ic+1]\). As example, consider the following sparse tensor of dimensions \((3,2,2,3)\) Figure 1: Visual representation of the core computation of Algorithm 1 using vector registers of size 4. We represent elementwise multiplication with \(\times\) and **vaddreduce** with \(\bigoplus\). \[\left\{\begin{bmatrix}\cdot&a&\cdot\end{bmatrix}\begin{bmatrix}\cdot&\cdot&\cdot \\ \cdot&\cdot&\cdot\end{bmatrix}\begin{bmatrix}\cdot&\cdot&\cdot\\ b&\cdot&c\end{bmatrix}\right\},\] \[\left\{\begin{bmatrix}\cdot&\cdot&\cdot\\ \cdot&\cdot\end{bmatrix}\begin{bmatrix}\cdot&d&\cdot\\ e&e\end{bmatrix}\begin{bmatrix}\cdot&\cdot&f\\ \cdot&\cdot&\cdot\end{bmatrix}\right\},\] where \(\cdot\) represents a zero value. Its sparse representation is given by \[W_{\mathrm{och}} =\begin{pmatrix}0&1&3&6\end{pmatrix},\] \[W_{\mathrm{ich}} =\begin{pmatrix}0&1&1&0&0&2&0&2&3\end{pmatrix},\] \[W_{\mathrm{x}} =\begin{pmatrix}0&0&1&1&1&0\end{pmatrix},\] \[W_{\mathrm{y}} =\begin{pmatrix}1&1&1&0&2&2\end{pmatrix},\] \[W_{\mathrm{vals}} =\begin{pmatrix}a&b&c&d&e&f\end{pmatrix}.\] Although the usage of a \(W_{\mathrm{och}}\) may seem superfluous, its inclusion allows us to reduce total memory usage. Indeed, assuming \(K<256\) and \(IC<8192\), we can store entries in \(W_{\mathrm{x}}\) and \(W_{\mathrm{y}}\) using uint8_t and \(W_{\mathrm{ich}}\) using int16_t. Therefore, using \(W_{\mathrm{och}}\) lowers memory usage from \(4B\times(IC+1)\times OC\) bytes to \(2B\times(IC+1)\times OC+4\times OC\) bytes. **Algorithm.** In Algorithm 2, we present an overview of our backpropagation algorithm for a convolutional layer. If we ignore at first the pointer arithmetic needed to traverse the structures, the main structure remains similar to that of Algorithm 1 as both innermost loops use the same instructions. **Implementation Details.** We developed two kernels for fast 2D convolutions based on the input dimensions. For larger \(M\) and \(N\), we found that no preprocessing was needed. Keeping the input dimensions as \(B\times IC\times M\times N\) offers both computing batches in parallel on multiple threads and high single-core parallelization using AVX2 instructions. On the other hand, for small \(M\) and \(N\), which often occur for the last layers of a network, we found it more efficient to permute the tensors to have the batch as the last index. In particular, \(\mathbf{X}\) and \(\partial L/\partial\mathbf{X}\) became of size \(IC\times M\times N\times B\), and \(\mathbf{O}\) and \(\partial L/\partial\mathbf{O}\) became of size \(OC\times OM\times ON\times B\). Indeed, setting \(B\) as the last dimension allows the usage of SIMD instructions even for small \(M\) and \(N\). ``` for\(ic=0\)to\(IC\)do for\(oc=0\)to\(OC\)do \(si_{i}=\mathbf{W}_{\mathrm{och}}[oc]+\mathbf{W}_{\mathrm{ich}}[ic]\) \(si_{e}=\mathbf{W}_{\mathrm{och}}[oc]+\mathbf{W}_{\mathrm{ich}}[ic+1]\) for\(si=si_{e}\)to /*repeat 8 times */ \(v\leftarrow\)vbroadcast(\(\mathbf{W}_{\mathrm{vals}}[j]\)) * initialize \(acc\) */ \(acc\leftarrow\)vbroadcast(\(0\)) \(p_{*}\leftarrow\max(0,pad-\mathbf{W}_{\mathrm{x}}[si])\) \(p_{e}\leftarrow\min(pad-\mathbf{W}_{\mathrm{x}}[si]+M,OM)\) \(q_{*}\leftarrow\max(0,pad-\mathbf{W}_{\mathrm{y}}[si])\) \(q_{e}\leftarrow\min(pad-\mathbf{W}_{\mathrm{y}}[si]+N,ON)\) for\(p=p_{*}\)do for\(q=q_{*}\)to\(q_{*}\)do for\(k=0\)to\(B-1\)with\(k==8\)do /* load 8 values*/ \(do\leftarrow\)vload(\((\partial L/\partial\mathbf{O})_{oc,p,q,k}\)) \(dx\leftarrow\)vload(\((\partial L/\partial\mathbf{X})_{ic,p,q,k}\)) \(x\leftarrow\)vload(\(\mathbf{X}_{ic,p,q,k}\)) /* compute 8 \(dx\) - \(do\cdot v+dx\)*/ \(dx\leftarrow\)vfmadd(\(do,v,dx\)) /* compute 8 \(acc=do\cdot x+acc\)*/ \(acc\leftarrow\)vfmadd(\(do,acc\)) /* store the updated \(dx\)*/ \(\mathbf{vstore}((\partial L/\partial\mathbf{X})_{ic,p,q,k},dx)\) endfor endfor endfor endfor endfor endfor endfor /* sum the 8 values in \(acc\)*/ \((\partial L/\partial\mathbf{W})_{\mathrm{vals}}(j)\leftarrow\)vaddreduce(\(acc\)) endfor endfor ``` **Algorithm 2** AVX2 Convolutional Backward Pass ## 4 Experiments **Setup and Goals.** We now experimentally validate our approach. First, we perform an in-depth exploration of our algorithm's runtime relative to weight sparsity in a synthetic scenario, i.e. for standard layer and input shapes. Then, we examine performance for two _end-to-end training_ scenarios, as part of a Pytorch integration. Specifically, we examine performance for _sparse transfer_, i.e. fine-tuning of already-sparsified accurate models on a different "transfer" dataset, and _from-scratch sparse training_ on some specialized tasks. **Pytorch Modules.** We provide two Pytorch modules, one for linear and one for convolution layers, facilitating the integration of our algorithm to different applications. To this end, we employ the pybind11 library (Jakob et al., 2016) for fast communication between Pytorch and the C** backend. ### Synthetic Performance Evaluation This section analyzes the runtime scaling for our linear and convolutional layers implementations of Algorithms 1 and 2. To validate our linear-scaling claims, we specifically examine the runtime dependence of our implementations relative to sparsity. These implementations are compared to their dense counterparts available in Pytorch. Additionally, for the linear layer implementation, we compare it against the sparse implementation offered by Pytorch. We present the improvement in our implementations' performance as a function of a layer's sparsity ranging from \(80\%\) to \(99\%\). In particular, we give the runtime for our multithreaded implementations run on \(8\)-threads in Figures 4 and 3, and the runtime for the single-core implementations in Figure 2. To highlight the speedup between implementations, we give all our measurements in _log-lin_ plots. **Linear layers.** We evaluate the performance of our linear layer by measuring the runtime of forward and backward pass through a large layer of dimensions \((M,N)=(768,3072)\) and an input of size \((B,M)=(902,768)\). We report the single-core results for the backward pass in Figure 2(a), and we compare them to a Pytorch-based sparse implementation, which is currently only single-core on CPUs. Our sequential performance increases linearly with the sparsity of \(\mathbf{W}\), we match a dense implementation around \(90\%\) sparsity, and we obtain a \(5\times\) speedup at \(99\%\). In Figure 4, we plot the results for the multithreaded forward and backward passes. For our multithreaded forward pass, we observe similar behavior to the single-core variant beating the dense implementation after \(95\%\) sparsity. It should be noted that the performance of our multithreaded implementation of the backward pass is currently limited by synchronization overheads, which can be removed with additional optimizations. As of now, it matches the dense implementation only at very high levels of sparsity. **Convolutional layers.** In the case of the convolutional layers, we present the runtime performance for two distinct scenarios: small input tensor and large input tensor. The dimensions of the layer are set to \((OC,IC,K,K)=(256,128,3,3)\), and the input tensor's dimensions are set to \((B,IC,M,N)=(8,128,7,7)\) and \((B,IC,M,N)=(32,256,244,244)\). These scenarios highlight the difference between the two sparse convolution kernels we developed: SparseConv and SparseConvOverON. The former is presented in Algorithm 2, and the latter is its permuted variant that vectorizes over the \(ON\) dimension of the tensor. We show that by permuting the input, we substantially improve the performance of our algorithm. The single-core runtime performance over a small input is presented in Figure 2(b), where we observe a significant speedup compared to a dense implementation, with \(19\)x speedup at \(99\%\) sparsity. The parallel runtime for forward and backward passes are in Figure 4. Timings for small input sizes are given in Figures 4(a) and 4(b), and for large inputs in Figures 4(c) and 4(d). We see how permuting impacts our performance for small \(ON\) values achieving a speedup over the dense implementation of up to \(5\)x for the forward and backward pass at \(99\%\) sparsity. On the other hand, for larger \(M\) and \(N\), our results indicate that vectorizing over \(ON\) yields the best performance, resulting in a speedup of \(3.35\)x for the forward pass and \(9\)x for the backward. ### End-to-End Training Experiments We now evaluate SparseProp on _sparse transfer learning_, and _sparse training from scratch_. In each case we examine Figure 4: Runtime measurement of our parallel sparse convolutional layers (base and vectorized over the \(ON\) dimension) on \(8\) threads compared against a dense implementation. The layer has dimension \((OC,IC,K,K)=(256,128,3,3)\), and the input’s dimensions are set to \((B,IC,M,N)=(8,128,7,7)\) in (a) and (b) and to \((B,IC,M,N)=(32,256,244,244)\) in (c) and (d). Figure 3: Runtime measurement of our parallel sparse linear layer compared against a dense implementation. The layer has dimension \((M,N)=(768,3072)\) the input is of size \((B,M)=(902,768)\). Figure 2: Runtime of our single-core backward propagation of sparse linear and convolutional layers. The former has dimension \((M,N)=(768,3072)\) and the input is of size \((B,M)=(902,768)\), while the latter is of size \((OC,IC,K,K)=(256,128,3,3)\), and the input is \((B,IC,M,N)=(8,128,7,7)\). sparsity settings which, while maintaining reasonable accuracy, can achieve non-trivial speedups. Since we executed over more than 15 different tasks, on multiple models, the full experiments used to determine accuracy are executed on GPU. At the same time, we computed CPU speedups using proportionally-shortened versions of the training schedules on CPU, and validated correctness in a few end-to-end runs on different tasks. In all the experiments, dense modules (linear or convolution) are executed dense as long as they are less than \(80\%\) sparse. Once a module reaches at least \(80\%\) sparsity (which may happen during training for gradual pruning scenarios), we measure the time to run one batch through both dense and sparse versions, and choose the fastest version based on forward+backward time (in the case of convolution, both sparse implementations are considered). Notice that in all experiments, the sparsity patterns change only a few times during the whole run, meaning the overhead of these few extra batches is negligible. (An alternative approach would be to generate a static database of the best implementation choices for each layer type and size, and greedily adopt the implementation for each layer in turn.) #### 4.2.1 Application 1: Sparse Transfer **Image Classification.** We first consider a standard transfer learning setup for image classification using CNNs, in which a model pretrained on ImageNet-1K has its last (FC) layer resized and re-initialized, and then is further finetuned on a smaller target dataset. As targets, we focus on twelve datasets that are conventionally used as benchmarks for transfer learning, e.g. in (Kornblith et al., 2019; Salman et al., 2020; Iofinova et al., 2022). See Table 5 for a summary of the tasks. Importantly, input images are scaled to standard ImageNet size, i.e. \(224\times 224\times 3\), resulting in proportional computational costs. We consider dense and sparse ResNet50 models pre-trained (and sparsified) on the ImageNet-1K dataset. Models are pruned using the AC/DC method (Peste et al., 2021), which shows high accuracy on ImageNet-1K, and produces transferable sparse features (Iofinova et al., 2022). (We adopt their publicly-available models.) To explore the accuracy-vs-speedup trade-off, we consider both a _Uniform pruning_ scenario, in which all convolutional layers except for the input are pruned to a uniform sparsity (90% and 97%), and a _Global pruning_ scenario, in which all convolutional layers are pruned jointly, to a target average sparsity (95%), using the global magnitude pruning criterion. The former two models have been trained for 200 epochs each, and have 76.01% and 74.12% Top-1 accuracy, whereas the latter is trained for 100 epochs and has 73.1% Top-1 accuracy. The dense model has 76.8% Top-1 accuracy. For transfer learning, we maintain the sparsity pattern of the models, reinitialize the final fully-connected layer, and train for 150 epochs on each of the 12 "downstream" tasks. In Figure 5, we aggregated results across all tasks, in terms of mean and variance of the _accuracy drop relative to transferring the dense model_ (the full per-task accuracy results are presented in Table 6, and speedups are presented in Table 2). As expected, the aggregated sparse test accuracy drops relative to the dense baseline, proportionally to the ImageNet Top-1 accuracy. The Uniform-90 model shows the smallest drops (1% on average), but also the lowest end-to-end speedup (25%), while the Uniform-97 and Global-95 models have slightly worse average drops (around 2%). Remarkably, due to higher initial accuracy, the Uniform-97 model has similar accuracy to Global-95, but much higher end-to-end speedup of 1.75x. **Case Study: 95% Uniformly-Pruned ResNet18.** We now analyze in detail both the accuracy drops and the per-layer and global speedups for a 95% uniformly-pruned ResNet18 model. On ImageNet, the AC/DC pruned model ResNet18 model has 68.9% Top-1 accuracy, a relative 1% drop from the Torchvision baseline. Figure 7 depicts the transfer performance of the respective models on twelve target datasets, using exactly the same transfer recipe for both sparse and dense models. The accuracy loss is moderate (2.85% average, with a maximum gap of 4.5% Top-1, across all tasks). Figure 5: Accuracy vs. speedup for _transfer learning_ experiments on the ResNet50 architecture. The boxplots represent aggregated performance across all twelve target tasks. Figure 6: Accuracy vs. estimated speedup for _from-scratch learning_ experiments on the ResNet18 architecture. The boxplots represent aggregated performance across all twelve target tasks. Figure 8 depicts layer-wise backward speedups with respect to Pytorch's dense implementation. The results show that the overall end-to-end speedup is 1.58x, with a 1.26x speedup end-to-end for forward computations and a 2.11x speedup end-to-end for backward computations. A closer examination reveals that if we only measure the time spent in convolution and linear modules' forward and backward functions we get a 2.53x speedup, suggesting the presence of significant overheads outside of the convolution and linear computations (such as batch normalization layers and ReLU) for the Pytorch CPU implementation. More precisely, our implementations provide speedups of 1.57x and 3.60x, for the forward and backward multiplications, respectively. This highlights the efficiency of our backward algorithms, but also the overheads of Pytorch's current CPU training implementation. (Specifically, in our sparse implementation, the batch normalization and ReLU computations, executed via Pytorch, take approximately 25% of the total training time.) **Language Modelling.** Next, we replicate the setup of Kurtic et al. (2022), where a BERT-base (Devlin et al., 2019) model is pruned in the pre-training stage on BookCorpus and English Wikipedia (Lhoest et al., 2021) with the state-of-the-art unstructured pruner oBERT (Kurtic et al., 2022). After that, the remaining weights are fine-tuned on several downstream tasks with fixed sparsity masks. We consider a model with 97% global sparsity, and maintain its masks throughout finetuning on the MNLI and QQP tasks from the GLUE benchmark (Wang et al., 2018). Both accuracy and speedup results are shown in Table 3, and show 37% speedup on a single core for inference on this model, at the price of \(\sim\) 1-3.5% accuracy drop. #### 4.2.2 Application 2: Sparse Training **Image Classification.** Finally, we evaluate SparseProp in the from-scratch sparse training scenario. We first consider the same 12 specialized datasets as in Section 4.2.1, and train a ResNet18 architecture _from scratch_. We apply 90% and 95% sparsity using Gradual Magnitude Pruning (Zhu and Gupta, 2017), in two scenarios--Uniform sparsity, in which all convolutional layers, except the first, are pruned to the same target, and the Global scenario, in which the magnitudes of the weights are aggregated across all layers, and the smallest-magnitude weights are pruned to reach the target sparsity. (For the latter scenario, we consider only 95% sparse models.) Note that in the Uniform scenario, we do not prune the initial convolution, nor the final FC layer, while in the Global scenario, we do. In both cases, we train the model dense for ten epochs before pruning the lowest 5% of the weights (either uniformly or globally) and then prune gradually every 10 epochs until epoch 80, at which point we fine-tune for a further 20 epochs. The results are given in Figure 6. In terms of accuracy, Global-GMP outperforms Uniform-GMP at the same target sparsity, with Global-95% showing similar accuracy to Uniform-90%, though in all cases performance is inferior to when ImageNet weights are used for pre-training. The highest speedup is of 1.31x, for 95% Uniform sparsity. Additionally, we evaluate SparseProp on the CelebA dataset (Liu et al., 2015), which consists of a training set \begin{table} \begin{tabular}{l|l l l|l l l} \hline \hline Backtrack & Forward & Backward & End-to-End & Normal & Backward & End-to-End \\ \hline Dense & \(18.0\pm 0.14\) & \(18.6\pm 0.16\) & \(28.18\pm 0.20\) & \(1.14\pm 0.00\) & \(3.04\pm 0.00\) & \(3.00\pm 0.00\) \\ Uniform 90\% & 1.11\% & 1.31\% & 1.10\% & 1.00\% & 1.36\% & 1.16\% \\ Global 95\% & 1.26\% & 1.28\% & 1.27\% & 1.12\% & 1.26\% & 1.15\% \\ Uniform 95\% & 1.30\% & 1.86\% & 1.76\% & 1.40\% & 1.36\% & 1.80\% \\ Global 95\% & 1.00\% & 1.71\% & 1.86\% & 1.92\% & 1.63\% & 1.46\% \\ \hline \hline \end{tabular} \end{table} Table 2: Single-core (left) and parallel (right) relative speedup for transfer learning on sparse ResNet50 models pretrained on ImageNet1k over a dense implementation. Figure 8: Layer-wise back-propagation time comparison between Dense and 95% uniformly-pruned Resnet18. Note that first and last layers are always dense and are hence removed from the comparison. \begin{table} \begin{tabular}{l|l l|l l l} \hline \hline BERT-base & Forward & Backward & End-to-End & MNLI & QQP \\ \hline Dense & \(0.72\pm 0.01s\) & \(1.38\pm 0.00s\) & \(\mathbf{2.67s\pm 0.01s}\) & \(84.54\%\) & \(91.06\%\) \\ Global 97\% & \(1.27\times\) & \(1.40\times\) & \(\mathbf{1.27\times}\) & \(80.91\%\) & \(90.33\%\) \\ \hline \hline \end{tabular} \end{table} Table 3: Accuracies and single-core relative speedup for transfer learning sparse BERT-base models. Figure 7: Top-1 validation transfer accuracy of dense and 95% sparse ResNet18 models pre-trained on ImageNet-1K. of 162'770 images, and a validation set of 19'962 images from 10 000 well-known individuals, each annotated with forty binary attributes, such as "Smiling", "Male", "Wearing Necklace", etc. We consider the task of jointly predicting all forty attributes, in a similar setup as above, and show the resulting AUC in Table 4. We observe that AUC stays fairly constant even at high sparsities, even as the speed of training increases. **Language Modelling.** For sparse fine-tuning from scratch on language models, we start from the pre-trained BERTbase (Devlin et al., 2019) model, which we fine-tune for 3 epochs on the target downstream task, and then prune in _one-shot_ with the state-of-the-art unstructured pruner oBERT (Kurtic et al., 2022), uniformly to 90%, 95% or 97% per-layer sparsity. After one-shot pruning, we fine-tune the remaining weights for 5 epochs and examine accuracy and speedup versus the dense variant. The results are presented in Table 4 (right), and show end-to-end speedups of up to 30%, at an accuracy loss between 1 and 3.5%. ## 5 Discussion We have provided an efficient vectorized algorithm for sparse backpropagation, with linear runtime dependency in the density of the layer weights. We have also provided an efficient CPU-based implementation of this algorithm, and integrated it with the popular Pytorch framework. Experimental evidence validates the runtime scaling of our algorithm on various layer shapes and types. We complemented this algorithmic contribution with an extensive study of the feasibility of sparse transfer learning and from-scratch training in edge scenarios. We observed consistent speedups across scenarios, at the cost of moderate accuracy loss. Our results should serve as motivation for further research into accurate sparse training in this setting, in particular for leveraging sparsity on highly-specialized tasks, which is an under-studied area.
2307.12150
Does color modalities affect handwriting recognition? An empirical study on Persian handwritings using convolutional neural networks
Most of the methods on handwritten recognition in the literature are focused and evaluated on Black and White (BW) image databases. In this paper we try to answer a fundamental question in document recognition. Using Convolutional Neural Networks (CNNs), as eye simulator, we investigate to see whether color modalities of handwritten digits and words affect their recognition accuracy or speed? To the best of our knowledge, so far this question has not been answered due to the lack of handwritten databases that have all three color modalities of handwritings. To answer this question, we selected 13,330 isolated digits and 62,500 words from a novel Persian handwritten database, which have three different color modalities and are unique in term of size and variety. Our selected datasets are divided into training, validation, and testing sets. Afterwards, similar conventional CNN models are trained with the training samples. While the experimental results on the testing set show that CNN on the BW digit and word images has a higher performance compared to the other two color modalities, in general there are no significant differences for network accuracy in different color modalities. Also, comparisons of training times in three color modalities show that recognition of handwritten digits and words in BW images using CNN is much more efficient.
Abbas Zohrevand, Zahra Imani, Javad Sadri, Ching Y. Suen
2023-07-22T19:47:52Z
http://arxiv.org/abs/2307.12150v1
# Does color modalities affect handwriting recognition? ###### Abstract Most of the methods on handwritten recognition in the literature are focused and evaluated on Black and White (BW) image databases. In this paper we try to answer a fundamental question in document recognition. Using Convolutional Neural Networks (CNNs), as eye simulator, we investigate to see whether color modalities of handwritten digits and words affect their recognition accuracy or speed? To the best of our knowledge, so far this question has not been answered due to the lack of handwritten databases that have all three color modalities of handwritings. To answer this question, we selected 13,330 isolated digits and 62,500 words from a novel Persian handwritten database, which have three different color modalities and are unique in term of size and variety. Our selected datasets are divided into training, validation, and testing sets. Afterwards, similar conventional CNN models are trained with the training samples. While the experimental results on the testing set show that CNN on the BW digit and word images has a higher performance compared to the other two color modalities, in general there are no significant differences for network accuracy in different color modalities. Also, comparisons of training times in three color modalities show that recognition of handwritten digits and words in BW images using CNN is much more efficient. Keywords-- Handwritten word recognition, Handwritten Digit Recognition, Handwritten Databases, Image modalities, Convolutional Neural Networks (CNN), Deep Learning. ## 1 Introduction Unlike the retina of some animals like cats and dogs which possess solely blue and green cones, humans have color vision due to the existence of red, blue and green cones in retina [1]. Color information plays an important role in human vision for recognition of elements such as shape, texture, and object recognition in daily life [2]. Similarly color as a rich feature and important descriptor is the vital part in many computer vision applications such as image super resolution [3], image segmentation [4], medical image analysis [5], remote sensing [6], image retrieval [7], and etc. Handwriting recognition is a very challenging task due to the existence of many difficulties such as the high variability of the handwritten styles and shapes, uncertainty of human-writings, skew or slant, segmentation of the words into isolated characters, and etc. [8]. Handwritten digit and word recognition has many applications such as processing of bank cheques [9], postal mail sorting[10], reading data from forms[11], notes recognition [12] and production of digital libraries of historical documents [13]. While the effects of color as a feature has been studied in many computer vision applications, to the best of our knowledge so far no one has investigated the effects of color feature in handwritten recognition. This paper for first time tries to answer fundamental question in automatic document recognition to see whether color modalities of handwritten texts affect their recognition accuracy or speed? Handwriting recognition is the process of converting handwritten images into their corresponding editable files [8, 14]. The handwritten recognition methods are divided into two main groups: online and off-line approaches. While on-line recognition depends on the trajectory of the pen and the coordinates of the pen's movement on the paper, off-line recognition is accomplished by analyzing the input image of the text [8]. Due to the important applications of handwriting in daily life, in the last twenty years many works have been proposed on handwritten digit and word recognition in different scripts such as Latin, Chinese, Indian, Arabic, and Persian. For example, see [15, 16, 17, 18] for some recent works in isolated digit recognition. Similarly, Table 1 summarized some important works on the recognition of handwritten Persian/Arabic words. Although these works are impressive, most of them focus on BW images due to lack of handwritten digit and word images having all three color modalities. Fortunately, recently a new comprehensive Persian handwritten database which has all three color modalities (True Color (TC), Gray Level (GL), and Black and White (BW)) has been introduced in [19]. This paper consider samples of Persian isolated digits and word from this database and investigate to see whether color modalities of handwritten digits and words affect their recognition accuracy or speed? Due to the complexity and variety of handwriting styles in different scripts, extracting the appropriate features from handwriting in any language is difficult and still open problem. In recent years, CNN models have been achieved considerable attention in the most computer vision applications (please see [4, 30, 31]). For the first time, CNN models proposed by LeCun et al [32, 33]. These types of artificial neural networks combine feature extraction and classification tasks together, and the main purpose of their designs is to recognize image due to scale, shift and distortions [33]. Generally, CNNs consist of input and output layer as well as several convolutional layers sequentially connected to each other and followed by fully connected layer(s). In each convolutional layer inputs from the previous layer is convolved with trainable filters. Relu [34] usually acts as an activation function in CNN layers. For decreasing the size of the data and reducing the over-fitting phenomena [35], the pooling operation is applied to the output of the \begin{table} \begin{tabular}{l l l l l} \hline Ref. & Method & Dataset & Year & Color \\ & & & & Modalities \\ \hline [20] & Heuristic & IRANSHAHR & 2014 & BW \\ [21] & Image gradient, classifier fusion & IRANSHAHR & 2020 & BW \\ [22] & Fuzzy vector quantization, discrete HMM & IRANSHAHR & 2001 & BW \\ [23] & Structural based feature, discrete HMM, re-ranking & IFN/ENIT & 2011 & BW \\ [24] & M-band wavelet transform & Private & 2008 & BW \\ [25] & Statistical and structural features, discrete HMM & IFN/ENIT & 2018 & BW \\ [26] & Right to Left, Left to Right HMM & IRANSHAHR & 2018 & BW \\ [14] & Image gradient, discrete HMM & IRANSHAHR & 2014 & BW \\ [27] & Chain code, discrete HMM & IRANSHAHR & 2001 & BW \\ [28] & Statistical features, Support Vector Machine & IRANSHAHR & 2018 & BW \\ [29] & Connectionist Temporal Classification (CTC), CNN & Ref[19] & 2020 & BW \\ \hline \end{tabular} \end{table} Table 1: Some important works on the handwritten recognition in Persian/Arabic (BW: Black and White images) current layer. While CNNs as feature extractor or classifier have many applications in computer vision, so far they rarely have been used in Persian handwriting recognition. In this paper we try to use this architecture for recognizing Persian isolated digit and words in three color modalities. To the best of our knowledge, so far, the effects of color modalities on handwriting recognition have not been studied. The main contribution of this paper is to answer this fundamental question. Using CNN, as an eye simulator, we investigated to see whether color modalities of handwritten isolated digits and words affect their recognition accuracy or speed. For our experiment, we adopted images of isolated digits and words from Persian database in [19] which have all three color modalities. In the first set of experiments, for isolated digit recognition, three similar CNN architectures are designed, trained, and tested. In the second set of experiments, a popular CNN architecture so called AlexNet [30] is fine-tuned for recognizing of handwritten words. In both set of experiments on digit and word recognition, results showed that Black and White (BW) color modality outperforms than other two color modalities (Gray Level (GL) and True Color (TC) level) in terms of recognition accuracy and training time of CNNs. The rest of this paper organized as follow: in the Section 2 the database used for experiment are explained. In Section 3 the architecture of CNNs for all color modulates in isolated digits and words are explained. The details of experimental results on isolated digits and word in three color modalities are explained in Section 4, and finally in Section 5 conclusion and future works are described. ## 2 Database In the recent years besides developing many interesting and novel handwriting recognition methods, several handwritten databases in different scripts have been provided to evaluate and compare those recognition methods. For example for isolated digit, \(\text{CENPARMI}^{\dagger}\) digit dataset [36] which, comprises of 6000 digits prepared from the envelop USPS\({}^{\ddagger}\) images. In this database 4000 samples, 400 images per digit, are determined for training and 2000 images for test. The CEDAR8 digit dataset is another database, which comprises of 18468 and 2711 digits as the training and test sets, respectively [15]. The MNIST dataset [37] was another database which extracted from the NIST\({}^{\texttt{\tiny{\tiny{\tiny{\tiny{\tiny{\tiny{\tiny{\tiny{\tiny{\tiny{\tiny{\tiny{\tiny{\tiny{\tiny{ \tiny{\tiny{\tiny{\tiny{\tiny{{\left}}}}}}}}}}}}}}}}}}\) dataset. In MNIST, images are normalized into 20 * 20 gray scale images, and then the normalized samples are placed in 28 * 28 frames [11]. Another popular database is USPS digit dataset which has 7291 training and 2007 test samples. Similar databases also exist for other languages such as Chinese, Arabic and Indian [38,39]. In Persian, HODA [11] is popular database which, their image samples were extracted from 12,000 registration forms. This dataset contains 102,352 digits and partitioned into train, test and evaluation groups. Similarly, Because of the existence of many challenges like the lack of certainty in human-writing, slant and skew in writing, styles and shapes with high variability, there are some valuable handwritten word databases in each script which summarized in Table 2. Although these datasets are impressive works, to the best of our knowledge most of them do not provide all color (TC, GL, and BW) modalities. Providing all color modalities of the same images of handwritten digits and words can provide a lot of new opportunities for investigation in handwriting recognition. Recently, a newly Persian database [19] has been developed which consist of a huge number of numeral strings, touching digits, digits, numeral dates and worded, common financial words, Persian alphabetical letters, symbols, punctuation marks and an unconstrained text. This database was collected from 500 Persian male and female writers equally. Each of the 500 participants wrote 125 different words. For each stored image detailed ground truth files also were created. All sample images were recorded in three modalities: TC, GL, and BW. One example of three image color modalities in digits and words is shown in Table 3 and Table 4 respectively. In this paper, we use the samples of Persian isolated digits and words from this database in three color modalities for our experiments. 3. Proposed methodology Using CNN models, the present study investigate the effects of color modalities on handwritten digit and word recognition. In the following subsections CNN architectures for isolated digit and word recognition are explained. ### Architecture for isolated handwritten digit recognition The proposed CNN architecture for isolated digit recognition shown in Figure 1. This CNN network contains: one input layer, two convolutional, two sub-sampling layers for extracting features automatically, two fully connected layers as multi-layer perceptron for classification, and one output layer. Details of the proposed architecture shown in Table 5. Existence many trainable parameters are one of the challenging point in CNN [53]. As shown in Table 5, there are many parameters (in total 2,117,962) that should be optimized in CNN, and for training these huge numbers of parameters there must be enough image samples. In conventional CNNs, the first layers capture primary features of an input such as lines and edges. While the latter layers extract more complex parts of an input like tail of dog in an image [29]. As a result, the early layers converged after few epochs. Nevertheless, deeper layers need considerable epochs to converge. So, the neural networks are robust against most of the geometrical transformation [54]. As a consequence, when the network needs more data for training, it is easily possible augment new data by applying some simple geometrical transformations on the input data [30]. In this paper, a subset including of 13,330 samples of isolated digits have been selected from database [19], then 80% of them have been selected for training and validating CNN models, and 20% remaining images for testing of trained CNN models. For creating enough images, we have used efficient simple geometrical transformation like shifting (in four main directions) and rotation (with constant probability). As shown in Figure 2, each input image firstly shifted in four main directions and then each shifted and original images are rotated around -15 to 15 degrees with constant probability. Totally after augmentation, there are 100,000 images, which 80% (0.8*100,000 = 80,000) of data provided for training and validation of CNN model and remaining 20%(0.2*100,000 = 20,000) are used for testing CNN model. We use the same architecture for recognition of isolated digit in TC, GL and BW color modalities, and then we compare these networks in terms of their recognition accuracies and their training times. \begin{table} \begin{tabular}{l l l l l l} \hline \hline Layer & Layer Operation & Feature & Feature Map & Window Size & Parameter \\ & & Map No. & Size & & \\ \hline C1 & Convolution & 32 & 68x68 & 3x3 & 896 \\ S1 & Max-pooling & 32 & 34x34 & 2x2 & 0 \\ C2 & Convolution & 64 & 32x32 & 3x3 & 18496 \\ S2 & Max-pooling & 64 & 16x16 & 2x2 & 0 \\ FC & Flatten layer & N/A & N/A & N/A & 0 \\ FC & Fully connected & N/A & N/A & N/A & 2097280 \\ FC & Output & N/A & N/A & N/A & 1290 \\ \hline & & & & **Total =** & **2,117,962** \\ \hline \hline \end{tabular} \end{table} Table 5: Details of each layer of proposed CNN[52] (shown in Figure 1). Figure 2: Structure of augmenting for each input image[52]. As shown in the figure, input images and all their shifted are saved as new images, and then each shifted and original images are rotated randomly with a fix probability (= 0.9). ### Architecture for handwritten word recognition Automatic Persian handwritten word recognition is a very complex task due to the existence of many challenges like lack of certainty in human writing, styles and shapes with high variability in handwritten and etc. Segmentation-based [55] and holistic [56] are two main approaches in Persian word recognition. This paper focuses on holistic approach. Hinton et al in 2012 proposed new architecture similar to LeNet [37] but more complex and deeper so called "AlexNet" [30] (please see Fig 3). As shown in this figure, it contains five convolutional layers and three fully connected layers. Relu [34] is applied after every convolutional and fully connected layer. In this paper, we use this architecture as a backbone network, and then we fine-tune it by modified the three last layers for handwritten word recognition. Training CNN from scratch without reducing the generalizability is not easy and requires plentiful training data. In conventional CNNs, the first layers capture global features of input image, while the last layers extract more local features from input images [30, 54]. In this paper for fine-tuning a backbone network, only the three last fully connected layers (L\({}_{6}\), L\({}_{7}\), and L\({}_{8}\)) are trained on handwritten word images. The general setup for fine-tuning procedure has shown in Table 6. As shown in this table, each fully connected layer has input features (in) and output features (out). The backbone network is trained with different numbers of hidden neurons in each of its three last layers (L\({}_{6}\), L\({}_{7}\) and L\({}_{8}\)) and the network with best performance on BW word images are chosen. The detail of the best fine-tuned network is shown in Table 7. As shown in this table, the total number of parameter in the best fine-tuned network is equal to 12,195,529 which compared to AlexNet (57,515, 965) shown in Fig 3 is much lower, while keeping same performance. We use the best fine-tuned network to investigate the effects of color modalities on handwritten word recognition in the experimental results. Database in [19] have word images with different sizes, however AlexNet [30] need 227*227 image as input size in first layer. There are many approach for resizing images [19]. The simplest method is resizing all images to 227*227, but applying this method on all images with different sizes deal to deform structure of handwritten images. In this paper, motivated by [57], the efficient image scaling (resizing) applied on all images in the preprocessing step (please see Figure 4). As shown in this figure, all images in database divided into two groups; firstly, images with dimensions smaller than standard size. These images only are padded with background pixel. Secondly, images with one or both dimension greater than 227 sizes. In these images, the ratio of the standard size to the bigger dimension is calculated and height and width of the input image is resized base on this ratio. With this strategy structure of input images doesn't change. \begin{table} \begin{tabular}{l l l l l l l l} \hline \hline \multicolumn{2}{c}{No. of trainable Layer} & \multicolumn{1}{l}{Batch} & No. of & Learning & Accuracy (\%) \\ \hline L\({}_{6}\)(in, out) & L\({}_{7}\)(in, out) & L\({}_{8}\)(in, out) & Size & Epochs & Rate (n) & (BW) \\ \hline (9216,4096) & (4096,9096) & (1024,125) & 128 & 100 & 0.001 & 77.0 \\ (9216,4096) & (4096,4096) & (4096,125) & 128 & 100 & 0.01 & 69.0 \\ (9216,4096) & (4096,4096) & (4096,125) & 200 & 100 & 0.001 & 76.0 \\ (9216,4096) & (4096,250) & (250,125) & 128 & 100 & 0.001 & 89.6 \\ (9216,4096) & (4096,500) & (500,125) & 128 & 100 & 0.001 & 89.8 \\ (9216,4096) & (4096,700) & (700,125) & 128 & 100 & 0.001 & 85.0 \\ (9216,1024) & (1024,250) & (250,125) & 128 & 100 & 0.001 & 94.9 \\ (9216,1024) & (1024,500) & (500,125) & 128 & 100 & 0.001 & 95.0 \\ (9216,1024) & (1024,250) & (250,125) & 128 & 100 & 0.002 & 95.2 \\ (9216,**1024**) & **(1024,250)** & **(250,125)** & 128 & 100 & 0.004 & 95.4 \\ \hline \hline \end{tabular} \end{table} Table 6: The setup for fine–tuning AlexNet, in each row one or more than one fully connected layer are trained with special batch size, epochs and learning rate on BW images. Then the network with respect to the best setup is chosen. \begin{table} \begin{tabular}{l l l l l l l l l} \hline \hline Layer & Layer type & No. of & Kernel & Stride & Padding & Input & Output & No. of \\ name & & filter & size & & & features & features & parameters \\ \hline \multirow{8}{*}{L\({}_{1}\)} & Convolution & 64 & (11,11) & (4,4) & (2,2) & (d,224,224) & (64,55,55) & 23,296 \\ & Relu & — & — & — & — & (64,55,55) & (64,55,55) & 0 \\ & Max-pooling & — & (5,5) & (2,2) & — & (64,55,55) & (64,27,27) & 0 \\ & Convolution & 192 & (5,5) & (2,2) & (2,2) & (64,27,27) & (192,27,27) & 307,392 \\ & Relu & — & — & — & — & (192,27,27) & (192,27,27) & 0 \\ L\({}_{2}\) & Max-pooling & — & (3,3) & (2,2) & — & (192,27,27) & (192,13,13) & 0 \\ & Convolution & 384 & (3,3) & (1,1) & (1,1) & (192,13,13) & (384,13,13) & 663,936 \\ L\({}_{3}\) & Relu & — & — & — & — & (384,13,13) & (384,13,13) & 0 \\ & Convolution & 256 & (3,3) & (1,1) & (1,1) & (384,13,13) & (256,13,13) & 884,992 \\ L\({}_{4}\) & Relu & — & — & — & — & (256,13,13) & (256,13,13) & 0 \\ & Convolution & 256 & (3,3) & (1,1) & (1,1) & (256,13,13) & (256,13,13) & 590,080 \\ L\({}_{5}\) & Relu & — & — & — & — & (256,13,13) & (256,13,13) & 0 \\ & Max-pooling & — & (3,3) & (2,2) & — & (256,6,6) & (256,6,6) & 0 \\ & Fully connected & — & — & — & — & 9216 & 1024 & 9,438,208 \\ L\({}_{6}\) & Relu & — & — & — & — & — & — & 0 \\ & Fully connected & — & — & — & — & 1024 & 250 & 256,250 \\ L\({}_{7}\) & Relu & — & — & — & — & — & 0 \\ & Fully connected & — & — & — & — & 250 & 125 & 31,375 \\ L\({}_{8}\) & Relu & — & — & — & — & — & 0 \\ \hline \hline \end{tabular} \end{table} Table 7: Details of the best fine-tuned network from Table 6. ## 4 Experimental results The main goal of this present study is trying to answer fundamental question in document recognition. Using CNNs, we try to see whether color modalities of handwritten digits and words affect their recognition accuracy or speed. It should be emphasized that providing novel techniques for improving accuracy of handwritten word and digit recognition are not the objectives of these experiments. Two sets experiments are conducted: isolated digit recognition and handwritten word recognition. All our experiments run on a machine with Intel(r) core i3-6300 CPU @3.70GHz, 16GB RAM, and NVidia(r) 1060Ti 6GB GPU. We implement our experiments using PyTorch(r) framework installed on Microsoft(r) windows10. ### Results for isolated handwritten digit recognition In this part, we apply similar architecture (see Fig 1) for recognizing Persian handwritten digit database. In three image modalities, proposed CNN trained by Stochastic Gradient Descent (SGD) algorithm using empirical optimized parameters. The confusion matrixes for TC, GL, and BW images are shown in Tables 8, 9, and 10 respectively. Figure 4: Column on the left: original image, Column in the middle: Resized image by normal scaling, and Column on the right: Resized image by [57]. In addition, for better comparison among three image modalities, recognition accuracy for each isolated digit in TC, GL, and BW modalities are shown in Figure 5. As shown in this figure recognition accuracy for BW images are higher than two other image modalities, but these differences are not significant. Validation accuracy and loss values in three color modalities with respect to different epochs are shown in Figure 6. As shown these figures network, converges in BW images are faster than two other image modalities. Finally the training time for three color modalities are shown in Table 11. As shown in this table, in the training phase recognizing handwritten digits in BW modality is more efficient than the two other modalities. \begin{table} \begin{tabular}{c c c c c c c c c c c} \hline \hline **0** & **1** & **2** & **3** & **4** & **5** & **6** & **7** & **8** & **9** \\ \hline **0** & **1989** & 2 & 2 & 0 & 3 & 4 & 0 & 0 & 0 & 0 \\ **1** & 0 & **1987** & 2 & 0 & 0 & 0 & 4 & 7 & 0 & 0 \\ **2** & 0 & 2 & **1937** & 36 & 17 & 0 & 1 & 5 & 2 & 0 \\ **3** & 0 & 0 & 56 & **1925** & 10 & 5 & 1 & 3 & 0 & 0 \\ **4** & 0 & 2 & 10 & 13 & **1950** & 3 & 0 & 13 & 3 & 6 \\ **5** & 0 & 5 & 0 & 1 & 7 & **1974** & 3 & 5 & 2 & 3 \\ **6** & 0 & 1 & 3 & 0 & 1 & 3 & **1562** & 424 & 0 & 6 \\ **7** & 0 & 10 & 7 & 8 & 6 & 29 & 56 & **1865** & 12 & 16 \\ **8** & 0 & 7 & 0 & 0 & 1 & 8 & 2 & 1 & **1972** & 9 \\ **9** & 0 & 13 & 0 & 0 & 4 & 40 & 3 & 8 & 0 & **1932** \\ \hline \hline \end{tabular} \end{table} Table 10: The confusion matrix on BW images[52]. \begin{table} \begin{tabular}{c c c c c c c c c c c} \hline \hline **0** & **1** & **2** & **3** & **4** & **5** & **6** & **7** & **8** & **9** \\ \hline **0** & **1993** & 0 & 5 & 1 & 0 & 2 & 2 & 3 & 1 & 3 \\ **1** & 0 & **1972** & 1 & 0 & 1 & 0 & 12 & 10 & 0 & 4 \\ **2** & 0 & 2 & **1864** & 78 & 39 & 1 & 10 & 5 & 1 & 0 \\ **3** & 0 & 0 & 60 & **1883** & 47 & 7 & 1 & 2 & 0 & 0 \\ **4** & 0 & 22 & 32 & 87 & **1822** & 8 & 5 & 15 & 4 & 5 \\ **5** & 4 & 8 & 1 & 7 & 14 & **1912** & 8 & 25 & 10 & 11 \\ **6** & 0 & 5 & 13 & 1 & 8 & 23 & **1412** & 507 & 14 & 17 \\ **7** & 0 & 14 & 56 & 13 & 120 & 109 & 288 & **1384** & 4 & 12 \\ **8** & 4 & 5 & 3 & 0 & 0 & 48 & 10 & 6 & **1904** & 20 \\ **9** & 1 & 10 & 1 & 0 & 5 & 57 & 16 & 25 & 7 & **1878** \\ \hline \hline \end{tabular} \end{table} Table 8: The confusion matrix on TC images[52]. ### Results for handwritten word recognition As the second set of the experiments, samples of database [19] which consist of 62,500 words are selected, and then divided into 70% (0.7*62,500 = 43,750) for training, 15% (0.15*70,000 = 9,375) for validation and 15% (0.15*70,000 = 9,375) for testing. Figure 7 show validation accuracy and loss values in different epochs in three color modalities. As shown in this figure, similar to isolated \begin{table} \begin{tabular}{l c} \hline Color modalities & Training times \\ & (in seconds) \\ \hline True Color(TC) & 68016.6 \\ Gray Level(GL) & 58705.5 \\ Black and White(BW) & 52261.0 \\ \hline \end{tabular} \end{table} Table 11: Running times for training CNN (in seconds)[52]. Figure 5: Overall recognition accuracy for each class (isolated digit) in three image modalities[52]. Figure 6: Performance of the proposed model with respect to different epochs during training in three different color modalities, (left) validation accuracy versus number of epochs, (right) loss values versus number of epochs for validation set[52]. digit (previous subsection) recognition accuracy and network convergence in BW images is outperformance than two other modalities but this difference isn't meaningful. In Table 12, the performance of the fine-tuned network is compared to AlexNet with respect to training time and recognition accuracy in three color modalities. As shown in this table, compared to a backbone network (AlexNet), the training time was significantly reduced, while the network accuracy didn't decreased significantly in all three color modalities. Although the purpose of this paper is not to improve the accuracy of the existence Persian word recognition system, however compared to the most of previous works, the proposed method provides much higher results (see Table 13). \begin{table} \begin{tabular}{l l l l l l l} \hline Ref. & Method & Dataset & No. of & \multicolumn{2}{c}{Accuracy (\%)} \\ & & classes & TC & GL & BW \\ \hline [20] & Heuristic & IRANSHAHR & 100 & \multicolumn{2}{c}{----} & \multicolumn{2}{c}{----} & 78.8 \\ [21] & Image gradient, classifier fusion & IRANSHAHR & 200 & \multicolumn{2}{c}{----} & \multicolumn{2}{c}{----} & 89.0 \\ [22] & Fuzzy vector quantization, HMM & IRANSHAHR & 198 & \multicolumn{2}{c}{----} & 67.7 \\ [23] & Structural based feature, discrete HMM, re-ranking & IFN/ENIT & 411 & \multicolumn{2}{c}{----} & 89.2 \\ [25] & Statistical and structural features, discrete HMM & IFN/ENIT & 411 & \multicolumn{2}{c}{----} & 87.9 \\ [26] & Right to Left, Left to Right HMM & IRANSHAHR & 200 & \multicolumn{2}{c}{----} & 84.4 \\ [14] & Image gradient, discrete HMM & IRANSHAHR & 198 & \multicolumn{2}{c}{----} & 68.8 \\ [27] & Chain code, HMM & IRANSHAHR & 198 & \multicolumn{2}{c}{----} & 69.0 \\ [28] & Statistical features, Support Vector Machine & IRANSHAHR & 198 & \multicolumn{2}{c}{----} & 80.7 \\ [29] & Connectionist Temporal Classification, bi-LSTM, CNN & Ref[19] & 125 & \multicolumn{2}{c}{----} & 98.1 \\ **—** & **Modified AlexNet(Proposed network)** & **IRANSHAHR** & **503** & \multicolumn{2}{c}{----} & **89.4** \\ **—** & **Modified AlexNet(Proposed network)** & **Ref[19]** & **125** & **91.2** & **94.4** & **95.4** \\ \hline \end{tabular} \end{table} Table 13: Compare the performance of the proposed method with existing holistic methods in Persian/Arabic database \begin{table} \begin{tabular}{l c c c c c c c} \hline \multirow{2}{*}{Network} & \multicolumn{2}{c}{Total} & \multicolumn{2}{c}{Training times} & \multicolumn{3}{c}{Accuracy (\%)} \\ & parameters & \multicolumn{3}{c}{(minutes)} & & & \\ \cline{3-8} & & BW & GL & TC & BW & GL & TC \\ \hline Alexnet & 57,515, 965 & 406 & 464 & 758 & 95.7 & 95.6 & 93.2 \\ Fine-tune Alexnet & 12,195,529 & 203 & 218 & 317 & 95.4 & 94.4 & 91.2 \\ \hline \end{tabular} \end{table} Table 12: Comparison of the performance of the best fine-tuned AlexNet and AlexNet (shown in Fig 3) Figure 7: Performance of the proposed model with respect to different epochs during training in three different color modalities, (left) validation accuracy versus number of epochs, (right) loss values versus number of epochs for validation set. Unlike the retina of some animals like cats and dogs which possess solely blue and green cones, humans have color vision due to the existence of red, blue and green cones in the retina[1]. Color information plays an important role in human vision for recognition of elements such as shape, texture, and object recognition in daily life [2]. Similarly color as a rich feature or important descriptor is the most important part in many computer vision applications such as image super resolution[3], image segmentation[4], medical image analysis [5], remote sensing [6], image retrieval[7] and etc. In this paper we conducted a case study on Persian handwritten recognition in three different color vision modalities. Using CNNs, as eye simulators, we investigated to see whether color modalities of handwritten digits and words would affect their recognition accuracy or speed. To the best of our knowledge, so far this question has not been answered, quantitatively, due to the lack of handwritten digit and words databases that have all three-color modalities of the handwritten digits. To answer this question, samples of Persian isolated digits and words provided by a new comprehensive handwritten Persian database[19] in three different color modalities are selected and they are divided into training, validation, and testing sets. In general, experimental showed there are no significant difference for recognition accuracy in different color models in both isolated digits and words. Also, comparisons of training times in three color modalities show that recognition of handwritten digits and words in BW modality using CNN is much more efficient than two other color modalities. In the future study, we would like to investigate the effects of the color modalities on handwritten recognition of other script such as: Latin, Arabic, Chinese, and etc.
2306.16755
Processing Energy Modeling for Neural Network Based Image Compression
Nowadays, the compression performance of neural-networkbased image compression algorithms outperforms state-of-the-art compression approaches such as JPEG or HEIC-based image compression. Unfortunately, most neural-network based compression methods are executed on GPUs and consume a high amount of energy during execution. Therefore, this paper performs an in-depth analysis on the energy consumption of state-of-the-art neural-network based compression methods on a GPU and show that the energy consumption of compression networks can be estimated using the image size with mean estimation errors of less than 7%. Finally, using a correlation analysis, we find that the number of operations per pixel is the main driving force for energy consumption and deduce that the network layers up to the second downsampling step are consuming most energy.
Christian Herglotz, Fabian Brand, Andy Regensky, Felix Rievel, André Kaup
2023-06-29T07:53:33Z
http://arxiv.org/abs/2306.16755v1
# Processing Energy Modeling ###### Abstract Nowadays, the compression performance of neural-network-based image compression algorithms outperforms state-of-the-art compression approaches such as JPEG or HEIC-based image compression. Unfortunately, most neural-network based compression methods are executed on GPUs and consume a high amount of energy during execution. Therefore, this paper performs an in-depth analysis on the energy consumption of state-of-the-art neural-network based compression methods on a GPU and show that the energy consumption of compression networks can be estimated using the image size with mean estimation errors of less than \(7\%\). Finally, using a correlation analysis, we find that the number of operations per pixel is the main driving force for energy consumption and deduce that the network layers up to the second downsampling step are consuming most energy. Christian Herglotz, Fabian Brand, Andy Regensky, Felix Rievel, Andre Kaup Multimedia Communications and Signal Processing Friedrich-Alexander-Universitat Erlangen-Nurnberg (FAU) Erlangen, Germany video, compression, autoencoder, energy ## 1 Introduction In the recent years, image compression using neural networks (NNs) has improved significantly. State-of-the-art compression networks outperform classical methods such as JPEG compression and often show a superior performance to high-end codecs such as HEIC or VVC intra [1, 2]. Unfortunately, NNs are very complex due to a large number of parameters and a complex architecture. As a consequence, they are usually executed on highly parallelized GPUs which leads to extremely high processing energies to compress and decompress a picture. As in a recent study it was shown that online video communications contribute significantly to global greenhouse gas emissions [3], it is clear that this high energy consumption must be mitigated before practical application. To this end, we perform a first analysis on the energy consumption of current NN-based image compression solutions, which we call compression networks in the following, on GPUs. Then, we construct an energy model that shows that the energy consumption can be estimated with high accuracy using the resolution of the image. Finally, we compare the compression energy in terms of operations per pixel with various network parameters and find that the complexity in terms of multiply-accumulate (MAC) operations has the highest correlation with the energy consumption. The contributions of this paper are as follows: * In-depth analysis of the power consumption of image compression networks, * Highly accurate energy modeling approach, * Recommendations for designing energy-efficient networks. First, Section 2 introduces the compression networks considered for energy analysis. Section 3 explains our energy measurement setup and Section 4 shows that the energy consumption can accurately be modeled using a linear model exploiting the number of pixels. Then, Section 5 analyzes the resulting energy modeling with respect to typical network parameters. Finally, Section 6 concludes this paper. ## 2 Neural-Network-Based Image Compression Most current neural network based compression techniques are building on the works by Balle et al. [4]. The authors proposed to use an autoencoder [5] with an entropy bottleneck. Autoencoders were primarily used for feature extraction, similar to principle component analysis. An autoencoder consists of an analysis transform and a synthesis transform. The former is used to transform the input image to a (typically lower dimensional) latent representation while the latter transforms this representation back to the original image. Since the intermediate latent space is low dimensional, the network is forced to focus this representation on the most important features in order to reconstruct the image as accurately as possible. Both analysis and synthesis transform are typically implemented with multiple strided convolutions. Balle et al. additionally included an entropy constraint to this latent space. Therefore, a probability distribution for the latent elements is estimated which is then used to estimate the rate required to transmit the latent representation using an asymptotically optimal coder (such as, e.g., an arithmetic coder). The network is then trained to jointly minimize the distortion and the required rate. It is easily seen that the quality of the probability model is crucial for the performance of the compression network. Therefore, subsequent work concerned not only with improving the backbone autoencoder and thereby the feature generation, but also the probability modeling for the latent space. In [6], Balle et. al proposed a refined probability model, which relies on the so-called hyperprior network, which is a second autoencoder transmitting scale information about the features on a side channel. Thereby, regions with low dynamic information can be compressed more efficiently as the low variance can be taken into account by the probability model. This work was further refined by Minnen et al. [7], who proposed an autoregressive context model, such that the probability model can take spatial correlation into consideration. The context model consists of causal masked convolutional layers, which together with the hyperprior network estimates mean and variance of a multivariate Gaussian distribution. The previously mentioned approaches use four strided convolution layers with similar dimensions. In contrast, Cheng et al. [8] proposed an autoencoder structure which is much larger and consists of multiple residual blocks and attention layers. Furthermore, the network uses Gaussian mixture models with three Gaussians instead of simple Gaussian models. Thereby, the number of parameters for probability modeling, which need to be estimated, increases. Table 1 summarizes all compression networks evaluated in this work and their main properties. We show proposed quality levels, the number of parameters, and the required operations in kMAC per pixel. The huge number of parameters hints at the immense complexity of NN-based image compression. NNs are thus commonly executed on GPUs leveraging their extreme parallelization capabilities. This is possible as GPUs provide thousands of compute cores that perform the same instruction on a large number of inputs simultaneously, an operation that is typical for NNs [9]. Since Krizhevsky et al. first successfully employed GPUs for the training and inference of large-scale neural networks [10], GPUs have become the de-facto standard for deep learning research and manufacturers have even extended their hardware to provide dedicated tensor cores for these tasks [11, 12]. ## 3 Measurement Setup For our measurements, we use desktop PCs (Linux OS) equipped with Nvidia Quadro RTX 4000 GPUs run by Intel Core i5-10505 CPUs. As power meters, we use the internal power meters of the GPU that can be read-out using the NVIDIA SMI interface [13] at a sampling rate of \(f_{\mathrm{s}}=10\) Hz. An example for the power consumption of the GPU during the execution of a compression network (model is already loaded to the GPU) is illustrated in Fig. 1. The plot shows the power consumption of the GPU as returned by NVIDIA SMI before, during, and after the execution of the compression network. Execution starts at \(t=5\) s and ends at \(t=6.2\) s, as indicated by the red vertical lines. The higher power value after the execution (\(t>6.2\) s) corresponds to a higher performance state of the GPU [14]. As the visible delay in state changes is an inherent property of the power control cycle of the GPU but not part of the compression procedure, it is not taken into account in our measurements. In our automated measurement script, we perform the following procedure to obtain mean processing energies: First, we perform a reference measurement in which the GPU is in idle mode. For this, we read all power consumption samples over \(120\) seconds and calculate the mean power \(P_{\mathrm{idle}}\). Then, we load the network models on the GPU and pre-heat the GPU to \(80^{\circ}\) C by running the current compression network repeatedly until the temperature is reached. Preheating is performed because during the measurement, we execute the compression network multiple times in a row. Preheating ensures that the temperature of the GPU is constant across all executions, such that static power losses are constant, too. Afterwards, we start a measurement loop in which the energy consumption \(E_{\mathrm{comp}}\) of compression network execution is measured. For this, we perform \(K\) measurements of the same compression modality (compression network, image, and quality level) to ensure statistical validity of the measurement. In each iteration of the \(K\) measurements, the modality is executed \(M\) times in a row, because the duration of a single execution is often close to the sampling time of the power meter. Consequently, the mean energy is obtained by \[\overline{E_{\mathrm{comp}}}=\frac{1}{K}\sum_{k=1}^{K}\frac{\left(\sum_{i=1}^{ N}t_{\mathrm{s}}\cdot P_{i,k}\right)-E_{\mathrm{idle}}}{M}, \tag{1}\] where \(N\) is the number of power samples from the power measurement interval, \(i\) the corresponding sample index, \(t_{\mathrm{s}}=\frac{1}{f_{s}}\) the sampling time of the power meter, \(P_{i,k}\) the power read-out at sample index \(i\) from measurement iteration \(k\), and \(E_{\mathrm{idle}}\) the corresponding energy consumed in idle mode. \(E_{\mathrm{idle}}\) is calculated by \(E_{\mathrm{idle}}=N\cdot t_{\mathrm{s}}\cdot P_{\mathrm{idle}}\). It is subtracted because we are interested in the dynamic, and not the static energy consumption. As measurement interval, we choose the beginning and the ending of the \(M\) executions (samples in-between the red vertical lines in Fig. 1). \(M\) is chosen such that the total duration of all \(M\) executions exceeds \(5\) s. Figure 1: GPU power over time (blue) during the execution of the compression network (between the red dashed lines). The network model is loaded to the GPU beforehand. The value of \(K\) is determined at measurement runtime to ensure statistical validity of the measurement using confidence interval tests as proposed in [15]. The resulting mean energy \(\overline{E_{\mathrm{comp}}}\) is then used for further analysis and modeling. Note that the measurements are performed with the following conditions: First, we test with the GPU in deterministic execution mode to ensure reproducibility [16] which is required in practice. Second, we do not perform entropy encoding and decoding of the latent space, because this is often performed on the CPU. Third, we measure the complete encoder-decoder chain. We measure the energy for all compression networks listed in Table 1, where we use the implementations from [17]. For each model, we test all available quality levels on \(60\) images from the CLIC image database [18] (test images). Note that the network architectures are provided in two variants with a differing number of parameters: a low level and a high level variant, where the former is used for low quality and the latter for high quality compression. The resolutions of the images span from \(751\times 500\) to \(2048\times 1366\). All images are padded according to the restrictions of the compression networks, which means that the height and the width are padded either to multiples of \(16\) or \(128\). To ensure the validity of energy measurements using the internal power meter (NVIDIA SMI), we performed additional experiments using an external power meter, a ZES Zimmer LMG661. We measured the energy consumption of the full desktop PC including the GPU through the main power supply of the PC. In total, we measured the execution of \(440\) compression network instances including different networks, images, and deterministic as well as non-deterministic execution. On the power meter, we used the same measurement procedure to derive energies as used for NVIDIA SMI, but we directly read integrated energy values from the power meter as explained in [15]. As a result from this benchmark, we find that apart from a constant offset energy, which is related to the PC's peripheral components such as CPU, memory, motherboard etc., NVIDIA SMI's energy measurements are correlated to the power meter's energy measurements with a correlation factor of \(0.9986\). We conclude that in the measurement conditions used in this analysis, NVIDIA SMI returns accurate energy measurements. ## 4 Energy Modeling Using the measured data for the six different networks, we attempt to model the energy consumption using high-level properties of the image. To this end, Fig. 2 shows the measured energies (NVIDIA SMI) over the number of pixels per image for the Bhyp compression network. We can see that if we consider a fixed network architecture including a fixed number of network parameters, e.g., the low quality levels of the Bhyp compression network (blue markers), the measured energy values closely follow a linear relationship with the number of pixels. The same holds true for the high quality levels. The linear correlation yields \(0.93\) and \(0.92\) for the low and the high quality levels, respectively, with similar results for other compression networks. Consequently, we propose to model the energy consumption of neural network processing using a linear equation given by \[\hat{E}=\alpha\cdot S+\beta, \tag{2}\] where \(\hat{E}\) is the estimated energy consumption, \(S\) the number of pixels in the image, i.e. the image width multiplied with the image height, \(\alpha\) the slope of the linear function, and \(\beta\) the offset. Illustratively, \(\alpha\) can be interpreted as the mean energy consumption per pixel and \(\beta\) as an energy offset per execution. To prove the accuracy of the linear estimator from Eq. (2), we also calculate the mean relative estimation error of the model [15]. It is given by \[\bar{\varepsilon}=\frac{1}{|\mathcal{I}|\cdot|\mathcal{Q}|}\sum_{i\in \mathcal{I}}\sum_{q\in\mathcal{Q}}\frac{|\hat{E}_{q,i}-E_{q,i}|}{E_{q,i}}, \tag{3}\] \begin{table} \begin{tabular}{l|l|c|c|c|c|c||c|c||c} \hline Network name & Abbr. & Source & low l. & high l. & low param. & high param. & padd & kMAC & kMAC (\(2^{\mathrm{nd}}\)) \\ \hline \hline bmshj2018\_factorized & Bfac & [4] & 1-5 & 6-8 & 2.998,147 & 7,030,531 & \(16\) & \(73.6/163.2\) & \(56/122.4\) \\ \hline bmshj2018\_hyperprior & Bhyp & [6] & 1-5 & 6-8 & 5,075,843 & 11,816,323 & \(128\) & \(76.3/169.7\) & \(56/122.4\) \\ \hline mbt2018\_mean & Mmean & [7] & 1-4 & 5-8 & 7,028,003 & 17,561,699 & \(128\) & \(80.3/181.4\) & \(56/122.4\) \\ \hline mbt2018 & Mcont & [7] & 1-4 & 5-8 & 14,130,467 & 25,504,596 & \(128\) & \(166.2/201.8\) & \(122.4/122.4\) \\ \hline cheng2020\_anchor & Canch & [8] & 1-3 & 4-6 & 11,833,149 & 26,598,956 & \(128\) & \(373.4/834.8\) & \(345.2/771.2\) \\ \hline cheng2020\_attn & Cattn & [8] & 1-3 & 4-6 & 13,183,293 & 29,631,788 & \(128\) & \(415.9/930.3\) & \(385.1/861.1\) \\ \hline \end{tabular} \end{table} Table 1: Compression networks and main properties. ‘low l.’ and ‘high l.’ represent parameter levels, ‘padd’ is short for ‘image padding’. The two rightmost columns show the kMAC per pixel (low/high) of the entire and up to the \(2^{\mathrm{nd}}\) layer, respectively. Figure 2: GPU energy over number of image pixels for the Bhyp compression network. The red markers correspond to high quality levels (HQ), the blue markers to low quality levels (LQ). The lines are linear least-squares fits to the points. where \(i\) is the image index from the complete set of images \(\mathcal{I}\) and \(q\) the quality level index from the set of quality indices \(\mathcal{Q}\), where this set either contains the high qualities or the low qualities. \(E_{q,i}\) and \(\hat{E}_{q,i}\) correspond to the measured and the estimated processing energies from Eq. (1) and Eq. (2), respectively, of the \(i\)-th picture and the \(q\)-th quality level. Training and validation is performed using \(10\)-fold cross-validation. The slope \(\alpha\), the offset \(\beta\), and the mean estimation errors \(\bar{\varepsilon}\) are summarized for all tested compression networks, separated by high and low quality levels, in Table 2. Considering the estimation error, we can see that the proposed linear model leads to mean estimation errors below \(7\%\). For the Canch and Cattn model, the error is significantly lower (below \(4\%\)). This behavior is probably related to the utilized capacity of the GPU, which is significantly higher for the Canch and Cattn network, as indicated by NVIDIA SMI. This conjecture is an interesting aspect for future research. The values of the offset parameter \(\beta\) show that there is a significant offset energy needed to execute the compression networks. However, considering image sizes of at least \(1120\times 760\) pixels (only a single image from the set has a lower resolution), the offset energy never exceeds a ratio of \(20\%\) of the total measured energy. The slope parameters \(\alpha\) reflect the observation that compression networks for high visual qualities consume more energy than those for low visual quality, because the high-quality values are greater. We can also observe that the highest value is almost five times higher than the lowest value (\(4.97\) vs. \(1.05\)). ## 5 Model Analysis In the next step, we compare the energy consumption (in energy per pixel) with network parameters to identify correlations, which could be helpful in network design decisions. Therefore, we analyze the per-pixel-complexity of the networks in the unit multiply-accumulate (MAC) operations per pixel. We calculate the MAC for all networks by counting the operations in each convolutional layer and weighting them according to the current downsampling at this layer. We report the values in Table 1. To show that the MAC is an important parameter in the energy consumption, we plot the MAC values and the \(\alpha\) values for all networks in Fig. 3. We can see that all parameters closely follow a linear relationship with the complexity of the network in terms of MAC. Next to a linear term, we can also find an offset, which indicates that a minimum energy per pixel is required (e.g., due to memory read and write of the raw image). We further study the kMAC per network layer to find reasons for the high power consumption of an image compression network. In particular, we focus on the part of the network that is most important for processing complexity. Here, we find that the layers up to and including the second downsampling step are very important (see the corresponding kMAC values in the last column of Table 1). Since the deeper layers are performed on rapidly decreasing resolution, the impact on the kMAC per pixel is small. Performing a similar fit to these \(2^{\rm nd}\)-layer MAC values as to the entire MAC values, we find that the linear correlation is almost as high (MRE of \(7.64\%\) for the entire MAC vs. \(11.16\%\) for the \(2^{\rm nd}\)-layer MAC). We conclude that these layers are the major reason for a high energy consumption of neural-network based image coders, such that they should be the main target when developing energy efficient NN-based compression schemes. ## 6 Conclusions In this paper, we investigated the energy consumption of state-of-the-art neural-network based image compression networks on a GPU.We showed that the energy consumption linearly depends on the number of pixels and that the network layers up to the second downsampling step contribute most to the overall energy consumption. In future work, we plan to analyze further networks, to separately analyze the encoding and the decoding process, and to additionally consider entropy encoding and decoding. Finally, we will test other GPUs and optimized hardware to generate a fair comparison with legacy image compression methods. \begin{table} \begin{tabular}{r|c|c|c|c|c|c} \hline Network & Bfac & Bhyp & Mmean & Mcont & Canch & Cattn \\ \hline \(\alpha_{\rm low}(\cdot 10^{-5})\) & \(1.05\) & \(1.15\) & \(1.17\) & \(1.75\) & \(1.99\) & \(2.34\) \\ \(\alpha_{\rm high}(\cdot 10^{-5})\) & \(1.50\) & \(1.73\) & \(1.76\) & \(1.82\) & \(4.20\) & \(4.97\) \\ \hline \(\beta_{\rm low}\) & \(1.95\) & \(1.61\) & \(1.58\) & \(3.01\) & \(0.37\) & \(0.42\) \\ \(\beta_{\rm high}\) & \(3.68\) & \(2.93\) & \(3.17\) & \(3.52\) & \(2.32\) & \(2.12\) \\ \hline \(\bar{\varepsilon}_{\rm low}\left[\%\right]\) & \(6.09\) & \(6.08\) & \(6.04\) & \(6.30\) & \(3.55\) & \(3.31\) \\ \(\bar{\varepsilon}_{\rm high}\left[\%\right]\) & \(6.11\) & \(6.24\) & \(6.28\) & \(6.46\) & \(3.88\) & \(3.54\) \\ \hline \end{tabular} \end{table} Table 2: Modeling parameters and estimation errors for all considered compression networks. Figure 3: Slopes \(\alpha\) over the MAC for all compression networks (color) and their quality levels (x’es for low qualities, o’s for high qualities). The dashed line is a linear fit for all points.
2305.12063
Efficient Multimodal Neural Networks for Trigger-less Voice Assistants
The adoption of multimodal interactions by Voice Assistants (VAs) is growing rapidly to enhance human-computer interactions. Smartwatches have now incorporated trigger-less methods of invoking VAs, such as Raise To Speak (RTS), where the user raises their watch and speaks to VAs without an explicit trigger. Current state-of-the-art RTS systems rely on heuristics and engineered Finite State Machines to fuse gesture and audio data for multimodal decision-making. However, these methods have limitations, including limited adaptability, scalability, and induced human biases. In this work, we propose a neural network based audio-gesture multimodal fusion system that (1) Better understands temporal correlation between audio and gesture data, leading to precise invocations (2) Generalizes to a wide range of environments and scenarios (3) Is lightweight and deployable on low-power devices, such as smartwatches, with quick launch times (4) Improves productivity in asset development processes.
Sai Srujana Buddi, Utkarsh Oggy Sarawgi, Tashweena Heeramun, Karan Sawnhey, Ed Yanosik, Saravana Rathinam, Saurabh Adya
2023-05-20T02:52:02Z
http://arxiv.org/abs/2305.12063v1
# Efficient Multimodal Neural Networks for Trigger-less Voice Assistants ###### Abstract The adoption of multimodal interactions by Voice Assistants (VAs) is growing rapidly to enhance human-computer interactions. Smartwatches have now incorporated trigger-less methods of invoking VAs, such as Raise To Speak (RTS), where the user raises their watch and speaks to VAs without an explicit trigger. Current state-of-the-art RTS systems rely on heuristics and engineered Finite State Machines to fuse gesture and audio data for multimodal decision-making. However, these methods have limitations, including limited adaptability, scalability, and induced human biases. In this work, we propose a neural network based audio-gesture multimodal fusion system that (1) Better understands temporal correlation between audio and gesture data, leading to precise invocations (2) Generalizes to a wide range of environments and scenarios (3) Is lightweight and deployable on low-power devices, such as smartwatches, with quick launch times (4) Improves productivity in asset development processes. Sai Srujana Buddi\({}^{1}\), Utkarsh Oggy Sarawgi\({}^{1}\), Tashweena Heeramun\({}^{1}\), Karan Sawnhey\({}^{1}\), Ed Yanosik\({}^{1}\), Saravana Rathinam\({}^{2*}\), Saurabh Adya\({}^{1}\)\({}^{1}\) Apple, USA \({}^{2}\) elbo.ai, USA {sbuddi,usarawgi,t_heeramun,ksawhney}@apple.com **Index Terms**: speech detection, gesture detection, multimodal fusion, temporal networks, neural networks, voice assistants, wearable smart devices, natural human-computer interactions ## 1 Introduction Multimodality is a fundamental aspect of human interactions [1, 2], as speech is frequently combined with other modalities, such as gesture, and gaze [3]. Human Computer Interfaces (HCIs) have embraced this concept to enhance natural modes of communication [4]. However, despite this trend, physical button press (BP) and voice trigger (VT) using keyword detection remain the dominant ways of invoking and interacting with Voice Assistants (VAs) on personal devices [5]. These methods can be cumbersome, particularly in multi-turn conversations [6]. Raise to Speak (RTS), developed by Zhao et al. [7], address these issues, and provides a more natural and convenient way of interacting with VAs on smartwatches using gesture and speech. The user can simply raise their watch to their mouth and speak, without the need for any explicit trigger phrases. The RTS task presents a complex challenge that requires the integration of multiple modalities: * Recognizing and identifying the combined parallel and sequential pattern of gesture (raise) and speech (audio). * Having the ability to adapt to a wide range of user scenarios, physical movements, demographics, and languages. * Running efficiently on low-power devices such as smartwatches, with limited resources. * Achieving a balance between fast response time and high precision. RTS system described in [7] employs human-designed Finite State Machines (FSMs) for audio-gesture integration, but FSMs have limitations in capturing intricate human behavior accurately, lack adaptability, and are susceptible to human biases. The difficulty in designing FSMs increases as the system complexity grows [8]. In this work, we present a refined method for solving the RTS problem by incorporating neural networks to seamlessly merge the audio and gesture modalities for improved VA invocation accuracy on smartwatches. We have devised _Neural Policy_, a lightweight, and low latency Gated Recurrent Unit (GRU) [9] that integrates speech and gesture signals and makes a binary RTS trigger/no-trigger decision. Due to the loose coupling between the speech and gesture modalities [10, 11, 12] and resource constraints of a low-power device like a smartwatch, we adopt a late fusion approach [13, 14]. Our proposed Neural Policy delivers significant accuracy improvements, with a \(90\%\) relative reduction in False Reject Rate (FRR) and False Accept Rate (FAR) while also eliminating the complexity in system design process. Figure 1: _Raise to Speak (RTS) model and process overview._ ## 2 Related work Multimodal learning has a long-standing history that predates and continues through the deep learning era [15]. The advancements in deep learning have been instrumental in the considerable growth of multimodal learning [16], leading to surge of interest in multimodal interfaces, with focus on improving the flexibility, transparency, and expressiveness of HCIs [3, 17, 18]. Gesture signals have been used in various multimodal applications, such as speech disambiguation [19] and object manipulation in augmented reality [20]. Recently, there has been an increasing trend of using gestures to enhance HCIs [21, 22, 23, 24]. Zhao et al. introduced an innovative way of using gesture and speech to make the VA invocation process quick, intuitive, and natural [7]. However, most of the multimodal systems defined in HCI works [7, 23, 24, 25, 26] use rule-based or linear systems for multimodal fusion, which fail to adapt to a diverse and sizable population. [21, 27] explored using deep learning for gesture and speech fusion but these systems are not computationally efficient for low-power devices. ## 3 Methods and Materials ### RTS Detection: System and Components The goal of the RTS detection systems is to detect RTS triggers by understanding the correlation and underlying patterns of accelerometer and audio signals as shown in Figure 0(b). To account for the asynchronous nature of input signals and device limitations, we chose a late fusion approach for this system. This approach involves processing each modality separately and then fusing the processed modalities to arrive at a multimodal decision. Figure 0(a) shows an overview of RTS detection system, with its components: * Audio featurizer, extracts \(40\) dimensional mel filter banks, \(\hat{x}_{audio}\in\mathbb{R}^{40}\), from input audio \(X_{audio}\in\mathbb{R}\). * Gesture featurizer, extracts \(31\) dimensional statistical features [7], \(\hat{x}_{accel}\in\mathbb{R}^{31}\), from \(3-\)axis accelerometer data \(X_{accel}\). * _speech_, _no speech_. It takes in the audio features \(\hat{x}_{audio}\) and outputs \(\hat{h}_{audio}\in\mathbb{R}^{2}\). * _raising_, _raised_, _dropping_, _dropped_. It takes in gesture features \(\hat{x}_{accel}\) and outputs \(\hat{h}_{accel}\in\mathbb{R}^{4}\). * _Not Intended for VA_ and _Intended for VA_, \(\hat{g}_{RTS}\in\mathbb{R}^{2}\). ### Training setup We adopt a sequential training process for development of the RTS system and components discussed in Section 3.1. Initially, we train the unimodal speech and gesture detectors separately, and the resulting scores from the unimodal detectors are then combined to train the multimodal fusion. This sequential training setup has several benefits, including reducing the complexity of the model and infrastructure, and enabling the utilization of all available data, even when paired modalities or labels are missing. Designing this system under real-world constraints, especially when dealing with a significant amount of missing data and labels in the gesture modality, presented a significant challenge. Nonetheless, the sequential training setup facilitated maximizing the utilization of the available data. ### Dataset In order to gather data that is representative and high in quality, we collected data from smartwatches, specifically, audio recordings through the single-channel \(16\) kHz microphone built into the smartwatch, as well as \(3-\)axis accelerometer data through the smartwatch's accelerometer sensor. To create a meaningful, and diverse dataset, we developed a detailed user study program. Through this program, we collected a total of \(8000\) hours of data from \(1500\) hired subjects with consent, with each subject recording \(100-150\) sessions. We ensured chosen subjects are from a variety of demographics, including gender, ethnicity, and location, as well as physical characteristics like height, age, and preferred wrist for wearing the watch. We chose an orchestrated approach to collect data, in which a moderator guides subjects through a wide range of scenarios defined by a data collection protocol. The objective of the protocol is to guarantee that the gathered data encompasses the diverse range of dynamic environments and activities that a smartwatch could potentially encounter in real-world settings. During the data collection process, subjects perform activities such as sitting, standing, walking, running, cycling, driving, kayaking, stretching, gesturing, and lying down, in environments including meeting rooms, gyms, parks, crowded areas, and quiet rooms. Half the scenarios involve the user interacting with the VA using RTS. Each subject receives \(75\) instructions, each with different activity and environment combinations, and records one or two sessions per instruction. Additionally, we collected video from the moderator's point of view to aid annotation. The data is split into train, validation, and test sets- with ratios of \(70\%\), \(15\%\), and \(15\%\), respectively. To maintain reliability in the model development process, we ensure that each subject's recordings belong to only one split. The data are annotated with audio, gesture, and intent to interact with VA labels. Audio from the watch is used for audio labeling and video from the recordings are used for gesture and intent labeling. ### Evaluation Metrics Owing to the user experience of the interaction, we perform evaluation of the detection system on the following metrics: * False Reject/Miss Rate (FRR): ratio of triggers that are missed by the detector to the total number of true triggers. A low FRR is desirable. * False Accept/Wake Rate (FAR): measures the frequency with which the detector is falsely triggered. A low FAR is desirable. * Equal Error Rate (EER): point on Detection Error Tradeoff (DET) curve [28] where FAR meets FRR. A low EER is preferred. In addition to accuracy metrics, we evaluate on-device performance metrics such as _runtime latency, physical memory, and power consumption_. ## 4 Multimodal Temporal Neural Fusion We propose _Neural Policy_, that uses lightweight, temporal neural networks to fuse audio and gesture signals for improved responsiveness, and enhanced RTS performance. Such a neural fusion technique, is able to use vast amounts of diverse training data to learn patterns, and correlations between the underlying modalities. Our approach involves constructing streaming tem poral networks that integrate the outputs from the RTS gesture and speech detectors on a per-frame basis and generate a probability of occurrence of RTS invocation in a streaming fashion. Firstly, the unimodal Gesture and Speech detectors as detailed in Section 3.1 are trained as \(10Hz\) streaming classifiers with a \(4\)-way and \(2\)-way classification setup, respectively. Both detectors are trained using Adam optimizer [29] to minimize the frame-wise discriminative categorical cross-entropy loss in accordance with their corresponding frame-wise labels as defined in Equation (1) below. \[l_{CE}=-\sum_{i=1}^{n}\sum_{j=1}^{m}\sum_{k=1}^{K}y_{k}^{(i,j)}log(\hat{s}_{k}^{( i,j)}) \tag{1}\] \[\text{where softmax scores, }\hat{s}_{k}^{(i,j)}=\frac{e^{\hat{l}_{k}^{(i,j)}}}{ \sum_{j=1}^{K}e^{\hat{l}_{k}^{(i,j)}}} \tag{2}\] \(\hat{l}\) represents output of the detector's final layer (logits), \(n\) represents sample count, \(m\) represents number of frames per session, and \(K\) represents number of classes where \(K=2\) for the speech detector, and \(K=4\) for the gesture detector. The outputs from the trained speech and gesture detectors at the frequency of \(10Hz\) are aligned, padded, and merged and are used as inputs to develop the neural policy. As part of the neural policy development, we propose two variations of the multimodal neural fusion technique, _softmax neural fusion_ and _logit neural fusion_, as also illustrated in Figure 2. ### Softmax neural fusion In softmax neural fusion approach, the frame-wise \(4\) dimensional, and \(2\) dimensional output probability score sequences from the gesture, and speech detectors respectively are used as input to the neural policy as shown in Figure 1(a). These output probability scores are computed by applying softmax function to the unimodal detectors final output as defined by Equation (2). The aligned audio and gesture scores are merged and used to train the neural fusion model using the Adam optimizer [29] to minimize the frame-wise discriminative categorical cross-entropy loss in accordance with their frame-wise binary _intended/unintended_ labels defined by Equation (1). ### Logit neural fusion Softmax non-linearity pushes the scores towards the extremes of 0 and 1, causing perturbations in the fusion latent space by reducing its dynamic range, thus making raw outputs of models like embeddings and logits more suitable for downstream tasks and further computations [30]. Considering this, we propose _logit neural fusion_, which incorporates the \(4\) and \(2\) dimensional gesture and speech logits directly in the fusion process of neural policy. The final layer output of the unimodal detectors, without applying the softmax function, serve as inputs to the neural policy, as depicted in Figure 1(b). With device limitations in mind, logits are preferred over embeddings. The training procedure of logit neural fusion is similar to that of softmax neural fusion, as discussed in Section 4.1. The merged \(2\) and \(4\) dimensional audio and gesture logits are used to train the fusion model using the Adam optimizer [29] to minimize the frame-wise discriminative categorical cross-entropy loss in accordance with their frame-wise binary _intended/unintended_ labels. ### Model architecture Due to their lightweightness and effectiveness in speech detection and gesture recognition tasks, we chose a \(1-\)dimensional convolutional neural network (1DCNN) architecture [7, 31, 32], for the speech and gesture detectors. Each 1DCNN detector consists of convolutional layers that operate along the temporal dimension, followed by a flatten, and two dense layers with dimensions \(128\) and \(32\). Due to the sequential nature and temporal ordering of the data, we opted Gated Recurrent Units (GRU) for the architecture of _neural policy_. Our chosen GRU architecture consists of a \(6\) dimensional input layer, followed by a single hidden layer with \(h_{dim}\) dimensions, followed by a fully connected layer, that results in \(2\) dimensional output. Softmax function performed on the output results in probability scores for RTS invocation occurrence. Although we have explored Long Short-Term Memory networks (LSTMs) as well for this task, we found that GRUs are more efficient as they require fewer parameters and computational resources to achieve high accuracy. ## 5 Experiments and Results We experimented with the hyperparameters of the models described in Section 4.3, and produced \(36\) distinct RTS detectors, by varying the size of the GRU neural policy's hidden layer, \(h_{dim}\in\{32,64\}\), the number of convolutional layers in unimodal 1DCNN detectors, \(n\in\{1,3,5\}\), and the type of neural fusion, \(f\in\{\text{softmax, logit}\}\). All the models involved are trained over \(200\) epochs with a learning rate of \(1e^{-3}\). In order to ensure an unbiased comparison, we also implemented an FSM policy as outlined by Zhao et al. [7] using \(15\) hyperparameters, and included this in our experimentation, resulting in a total of \(54\) distinct variations of the RTS detector. All the 54 variations are trained, tuned and evaluated end-to-end. We have selected a subset of models for further analysis based on their accuracy and on-device performance. Out of the \(54\) variations of the RTS detector, \(6\) candidates we have hand-picked for further evaluation are: * (a) : \(n_{s}=1\), \(n_{g}=1\), \(f=FSM\) (baseline) * (b) : \(n_{s}=1\), \(n_{g}=1\), \(f=Softmax\), \(h_{dim}=32\) Figure 2: Types of Neural Fusion * (c) : \(n_{s}=1\), \(n_{g}=1\), \(f=Softmax\), \(h_{dim}=64\) * (d) : \(n_{s}=1\), \(n_{g}=1\), \(f=Logit\), \(h_{dim}=64\) * (e) : \(n_{s}=3\), \(n_{g}=1\), \(f=Logit\), \(h_{dim}=64\) * (f) : \(n_{s}=5\), \(n_{g}=1\), \(f=Logit\), \(h_{dim}=64\) \(n_{s},n_{g}\) represents number of 1DCNN layers in speech and gesture detectors respectively, \(f\) represents neural fusion type, and \(h_{dim}\) represents size of GRU neural policy's hidden layer. Table 1 compares accuracy and model parameters of the selected RTS detectors, and several key observations can be drawn, (1) Replacing FSM with a neural policy using softmax neural fusion results in an \(80\%\) relative decrease in EER, indicating that the neural policy approach is highly effective, and the neural networks are more capable of learning from a large population than FSM. It is also observed that increase in the size of the neural policy leads to further accuracy improvements. (2) The accuracy of neural fusion is further enhanced by using logit neural fusion, which addresses the limitations of softmax nonlinearity, as discussed in Section 4.2. (3) Increasing the depth of the speech detector and adding more 1DCNN layers enhances the audio representation, leading to neural policy accuracy improvements. Figure 3 illustrates that RTS detectors with deeper speech detectors have higher accuracy in challenging negative scenarios, where RTS gestures are paired with unintended human speech. However, increasing the depth of the gesture detector did not lead to any performance improvements, likely due to the relatively smaller dataset available for gesture. The RTS detector that employs a 5-layered speech detector, a 1-layered gesture detector, and a logit neural policy with hidden size 64 (highlighted in Table 1) demonstrates the most significant accuracy gains and achieves a relative reduction in EER of \(90\%\). Table 2 compares the on-device performance metrics for the selected RTS detectors. The results are competitive, demonstrating that the chosen Neural Policy, despite using neural networks, is lightweight and suitable for on-device implementation. In this analysis, the models precision is set to FP32, but we observed that quantizing them to FP16 yields even better competitive outcomes with no accuracy reductions. The neural policy not only improves accuracy but also significantly simplifies the asset development process. The FSM policy development which involves no training, but finetuning in a \(15\) dimensional hyperparameter space to find a single operating point, takes \(3-5\) days and \(1000\) compute nodes even with the efficiency of Bayesian search and parallelism. In contrast, training and tuning the neural policy using distributed data parallel on a single \(4\) GPU node takes \(2-3\) hours reducing development time and compute resources significantly. ## 6 Conclusion and Future Work In conclusion, this work introduces two versions of a GRU-based multimodal temporal neural fusion approach, one using softmax and the other using logit, for accurate identification of VA trigger-less invocations using audio and gesture signals. The approach demonstrates its ability to learn the temporal correlations between the input audio and gesture signals and achieve high precision. It is lightweight and suitable for deployment on low-power devices, such as smartwatches, while maintaining low launch time and latency. Compared to the traditional FSM-based multimodal fusion, this approach results in a significant improvement in the Raise To Speak experience, with a relative decrease of nearly \(90\%\) in false rejects and false accepts. Additionally, this approach offers a more streamlined development process when compared to the traditional FSM-based multimodal fusion. Future research efforts can be focused on experimenting with techniques such as modality dropout [33] to make the fusion more robust. Attention-based fusion models like multimodal transformers [34] and attention bottlenecks [13] can be explored, albeit it is crucial to ensure that performance metrics such as memory, latency, and power are kept within acceptable limits for on-device applications. \begin{table} \begin{tabular}{l r r r r} \hline \hline & **(a)** & **(b)** & **(c)** & **(d)** & **(e)** & **(f)** \\ \hline **Memory(MB)** & 1.04 & 1.06 & 1.06 & 1.06 & 0.77 & 0.85 \\ **Power(mW)** & 100.4 & 122.2 & 122.4 & 122.4 & 124.1 & 128.9 \\ **Runtime(ms)** & 0.30 & 0.54 & 0.57 & 0.57 & 0.76 & 1.4 \\ \hline \hline \end{tabular} \end{table} Table 2: On-device performance metrics of RTS detectors. The values are recorded by running detectors on 32 bit ARM Cortex-A7 MPCore processor in low power mode, averaged over 30 iterations. Memory is physical memory consumed in megabytes. Power measures static and dynamic power drawn per inference along with static power of device when idle in milliWatts. Runtime is time taken per inference measured in milliseconds. \begin{table} \begin{tabular}{l r r r r} \hline \hline & **\#Speech** & **\#Gesture** & **\#NP** & **EER(\%)** \\ \hline (a) & 133466 & 133356 & 15 & 40.0 \\ (b) & 133466 & 133356 & 3906 & 8.1 \\ (c) & 133466 & 133356 & 13954 & 7.0 \\ (d) & 133466 & 133356 & 13954 & 5.5 \\ (e) & 58546 & 133356 & 13954 & 4.9 \\ **(f)** & **77482** & **133356** & **13954** & **4.4** \\ \hline \hline \end{tabular} \end{table} Table 1: EER comparison of RTS detectors. #Speech, #Gesture, and #NP are number of parameters in Speech, Gesture and Neural Policy detectors respectively. Figure 3: False Positives of challenging scenarios at fixed 20% FRR and variable FAR. (a) Check time on watch while talking (b) Check watch and read what’s on it (c) Raise watch near mouth and cough (d) Hold phone in same hand as watch and attend a call (e) Perform a right turn while on steering wheel and speak loudly.
2305.08013
Information Bottleneck Analysis of Deep Neural Networks via Lossy Compression
The Information Bottleneck (IB) principle offers an information-theoretic framework for analyzing the training process of deep neural networks (DNNs). Its essence lies in tracking the dynamics of two mutual information (MI) values: between the hidden layer output and the DNN input/target. According to the hypothesis put forth by Shwartz-Ziv & Tishby (2017), the training process consists of two distinct phases: fitting and compression. The latter phase is believed to account for the good generalization performance exhibited by DNNs. Due to the challenging nature of estimating MI between high-dimensional random vectors, this hypothesis was only partially verified for NNs of tiny sizes or specific types, such as quantized NNs. In this paper, we introduce a framework for conducting IB analysis of general NNs. Our approach leverages the stochastic NN method proposed by Goldfeld et al. (2019) and incorporates a compression step to overcome the obstacles associated with high dimensionality. In other words, we estimate the MI between the compressed representations of high-dimensional random vectors. The proposed method is supported by both theoretical and practical justifications. Notably, we demonstrate the accuracy of our estimator through synthetic experiments featuring predefined MI values and comparison with MINE (Belghazi et al., 2018). Finally, we perform IB analysis on a close-to-real-scale convolutional DNN, which reveals new features of the MI dynamics.
Ivan Butakov, Alexander Tolmachev, Sofia Malanchuk, Anna Neopryatnaya, Alexey Frolov, Kirill Andreev
2023-05-13T21:44:32Z
http://arxiv.org/abs/2305.08013v2
# Information Bottleneck Analysis of Deep Neural Networks via Lossy Compression ###### Abstract The Information Bottleneck (IB) principle offers an information-theoretic framework for analyzing the training process of deep neural networks (DNNs). Its essence lies in tracking the dynamics of two mutual information (MI) values: one between the hidden layer and the class label, and the other between the hidden layer and the DNN input. According to the hypothesis put forth by Shwartz-Ziv and Tishby (2017), the training process consists of two distinct phases: fitting and compression. The latter phase is believed to account for the good generalization performance exhibited by DNNs. Due to the challenging nature of estimating MI between high-dimensional random vectors, this hypothesis has only been verified for toy NNs or specific types of NNs, such as quantized NNs and dropout NNs. In this paper, we introduce a comprehensive framework for conducting IB analysis of general NNs. Our approach leverages the stochastic NN method proposed by Goldfeld et al. (2019) and incorporates a compression step to overcome the obstacles associated with high dimensionality. In other words, we estimate the MI between the compressed representations of high-dimensional random vectors. The proposed method is supported by both theoretical and practical justifications. Notably, we demonstrate the accuracy of our estimator through synthetic experiments featuring predefined MI values. Finally, we perform IB analysis on a close-to-real-scale convolutional DNN, which reveals new features of the MI dynamics. ## 1 Introduction The information-theoretic analysis of deep neural networks (DNNs) is a developing branch of the deep learning theory, which may provide a robust and interpretable way to measure the performance of deep models during training and inference. This type of analysis might complement current non-transparent meta-optimization algorithms for architecture search, like ENAS, DARTS, evolutionary algorithms, and others [1; 2; 3; 4; 5; 6]. For the same reasons, this method may also be preferable (see [7]) to current approaches to explainable AI that rely either on a local analysis of a model [8], or some complex perturbation of data [9]. We also note that information-theoretic quantities can be considered as training objectives [10]. The information-theoretic analysis of DNNs relies on the _Information Bottleneck_ (IB) principle, which was proposed in [11]. This concept was later developed in [10] and applied to DNNs in [12]. The major idea of the IB approach is to track the dynamics of two _mutual information_ (MI) values: \(I(X;L)\) between the hidden layer (\(L\)) and the DNN input (\(X\)) and \(I(Y;L)\) between the hidden layer and the target of the model (\(Y\)). As a result of the IB analysis, the authors of [12] put forth the so-called _fitting-compression_ hypothesis, which states that the training process consists of two phases: a feature-extraction "fitting" phase (both MI values grow) and a representation compression phase (\(I(Y;L)\) grows while \(I(X;L)\) decreases). The authors of [12] conjectured the compression phase to account for the good generalization performance exhibited by DNNs. However, it is still debated whether empirical confirmations of the compression phase are related to improper mutual information estimators, activation function choice, or other implementation details. For an overview, we refer the reader to [13]. The seminal paper [12] proposed to utilize a quantization (or binning) approach to calculate the MI. The first problem of such an approach lies in the fact that the MI estimate is very sensitive to the bin size. The second problem is even more fundamental, indeed let us consider \(I(X;L)\) at some fixed training epoch. When the training weights are fixed \(L\) is a deterministic function of \(X\) and thus the MI is not a function of the NN parameters (it is infinite for practically all regimes of interest if we speak about continuous case and reasonable activation functions, see e.g. [14]). The subsequent papers addressed the aforementioned problems. To tackle the infinite MI problem it was proposed to consider (a) stochastic NNs [15, 16], (b) quantized NNs [17] or (c) dropout NNs [18]. Simple and inconsistent binning entropy estimators have been replaced with estimators more appropriate for continuous random variables [15, 18, 19, 20]. However, due to the challenging nature of estimating MI between high-dimensional random vectors, the fitting-compression hypothesis has only been verified for toy NNs or special classes of models with trackable information-theoretic quantities [17, 18, 19]. We also mention papers that suggest using lower bounds or other surrogate objectives [21, 22, 23, 24, 25, 26, 27] or even using other definitions of entropy [28, 29]. Unlike all the mentioned approaches, we suggest overcoming the curse of dimensionality problem by compressing the data. As most of the datasets are internally structured (see the _manifold hypothesis_[30]), it may be assumed that it is usually sufficient to estimate information-theoretic quantities of compressed/latent representations of data. This allows conventional and well-developed information-theoretic approaches to be applied to real-scale machine-learning problems. This paper extends the ideas of [31], where we used the compression step to estimate the entropy. Our contribution is as follows. We introduce a comprehensive framework for conducting IB analysis of general NNs. Our approach leverages the stochastic NN method proposed [15] and incorporates a compression step to overcome the obstacles associated with high dimensionality. In other words, we estimate the MI between the compressed representations of high-dimensional random vectors. We provide a theoretical justification of MI estimation under lossless and lossy compression. The accuracy of our estimator is demonstrated through synthetic experiments featuring predefined MI values. Finally, the experiment with convolutional DNN classifier of the MNIST handwritten digits is performed. The experiment shows that there may be several compression/fitting phases during the training process. It may be concluded that phases revealed by information plane plots are connected to different regimes of learning (i.e. accelerated, stationary, or decelerated drop of loss function). We note that stochastic DNNs are just a proxy to analyze real DNNs as (a) small noise practically does not affect the accuracy and generalization ability, (b) introduced randomness makes information-theoretic quantities reasonable (MI values do depend on DNN parameters). The paper is organized as follows. In Section 2, we provide basic concepts and objects, used in this paper. In Section 3, we describe the proposed approach and provide the required theoretical justification, including bounds for mutual information estimate under compression. In Section 4, a general framework to test mutual information estimators on synthetic datasets is developed. This framework is then used in Section 5 to test four selected conventional mutual information estimators, complemented with the proposed compression step. The method performed the best is then used in Section 6 to conduct information plane analysis of a convolutional classifier of MNIST handwritten digits dataset [32]. The results are discussed in Section 7. ## 2 Preliminaries Consider an absolutely continuous random vectors \(X\colon\Omega\to\mathbb{R}^{n}\) and \(Y\colon\Omega\to\mathbb{R}^{m}\), here and in what follows by \(\Omega\) we denote the sample space. Let us assume that these random vectors have absolutely continuous probability density functions (PDF) \(\rho(x)\), \(\rho(y)\), and \(\rho(x,y)\), where the last term means a joint PDF. The differential entropy of \(X\) is defined as follows \[h(X)=-\operatorname{\mathbb{E}}\log\rho(x)=-\int\limits_{\operatorname{supp}X }\rho(x)\log\rho(x)\,dx,\] where \(\operatorname{supp}X\subseteq\mathbb{R}^{n}\) is the _support_ of \(X\), and \(\log(\cdot)\) means a natural logarithm. Similarly, let us define the joint differential entropy \(h(X,Y)=-\operatorname{\mathbb{E}}\log\rho(x,y)\) and conditional differential entropy \(h(X\mid Y)=-\operatorname{\mathbb{E}}\log\rho\left(X\mid Y\right)=- \operatorname{\mathbb{E}}_{Y}\left(\operatorname{\mathbb{E}}_{X\mid Y=y}\log \rho(X\mid Y=y)\right)\). Finally, mutual information (MI) is given by \(I(X;Y)=h(X)-h(X\mid Y)\), and the following equivalences hold \[I(X;Y)=h(X)-h(X\mid Y)=h(Y)-h(Y\mid X), \tag{1}\] \[I(X;Y)=h(X)+h(Y)-h(X,Y). \tag{2}\] In some cases, \(\operatorname{supp}X\) or \(\operatorname{supp}Y\) can be of measure zero (the distribution is singular). Then, if the supports are manifolds, density functions can be treated as induced probability densities, and \(dx\), \(dy\) -- as area elements of corresponding manifolds; thus all the previous definitions remain valid. There is an alternative definition of the MI given by the Kullback-Leibler divergence \(D_{KL}(\,\cdot\,)\). \[I(X;Y)=\int\rho(x,y)\log\frac{\rho(x,y)}{\rho(x)\rho(y)}dxdy=D_{KL}(\rho(x,y)|| \rho(x)\rho(y)).\] In what follows, we use the quite important property of MI -- invariance under nonsingular mappings between smooth manifolds. We aim to show that one can measure the MI between compressed representations of random vectors. The following statement holds. **Statement 1**.: _Let \(\xi\colon\Omega\to\mathbb{R}^{n^{\prime}}\) be absolutely continuous random vector, \(f\colon\mathbb{R}^{n^{\prime}}\to\mathbb{R}^{n}\) be injective piecewise-smooth mapping with Jacobian \(J_{f}\) such that \(n\geq n^{\prime}\) and \(\det\left(J_{f}^{T}J_{f}\right)\neq 0\) almost everywhere. Let either \(\eta\) be a discrete random variable, or \((\xi,\eta)\) be an absolutely continuous random vector. Then_ \[I(\xi;\eta)=I\left(f(\xi);\eta\right) \tag{3}\] **Remark 1**.: _In what follows by \(\xi\colon\Omega\to\mathbb{R}^{n^{\prime}}\) we denote the compressed representation of \(X\), \(n^{\prime}\leq n\)._ Recall that we utilize the stochastic NN approach to deal with the problem of infinite MI \(I(X;f(X))\) for a deterministic mapping \(f\). As it has been shown in [15], adding stochasticity enables proper MI estimation between layers of the network. The stochastic modification of a network is used as a proxy to determine the information-theoretic properties of the original model. The conventional feedforward NN can be defined as an acyclic computational graph, which can be topologically sorted: \[L_{0}\triangleq X,\quad L_{1}:=f_{1}(L_{0}),\quad L_{2}:=f_{2}(L_{0},L_{1}), \quad\ldots,\quad\hat{Y}\triangleq L_{n}:=f_{n}(L_{0},\ldots,L_{n-1}),\] where \(L_{0},\ldots,L_{n}\) are the outputs of the network's layers. The stochastic modification is defined similarly, but using the Markov chain stochastic model: **Definition 1**.: _The sequence of random vectors \(L_{0},\ldots,L_{n}\) is said to form a stochastic neural network with input \(X\) and output \(\hat{Y}\), if \(L_{0}\triangleq X\), \(\hat{Y}\triangleq L_{n}\), and_ \[L_{0}\ \longrightarrow\ (L_{0},L_{1})\ \longrightarrow\ \ldots\ \longrightarrow\ (L_{0},\ldots,L_{n})\] _is a Markov chain; \(L_{k}\) represents outputs of the \(k\)-th layer of the network._ Our main goal is to track \(I(L_{i};L_{j})\) during the training process. Due to \(L_{k}\) being of high dimension, it is difficult to acquire the desired estimates [15]. In the following sections, we propose the MI estimation method for high-dimensional random vectors, which utilizes the compression step. Our method works for the datasets for which the manifold hypothesis holds. In what follows we perform all our experiments with raster pictures. As any \(L_{k}\) is an image of \(X\) under some continuous mapping, the manifold hypothesis is likely to be assumed for \(L_{k}\), thus justifying the usage of the proposed method. ## 3 Mutual information estimation via lossy compression In this section, we discuss the application of lossy compression to MI estimation for high-dimensional random vectors. The task is to estimate \(I(X;Y)\) using \(\{(x_{k},y_{k})\}_{k=1}^{N}\), where \((x_{k},y_{k})\sim(X,Y)\). Conventional estimation approaches rely to some extent on PDF reconstruction in order to acquire the MI or entropy estimate. However, these methods fail to yield a correct estimation for high-dimensional cases. In the following subsections, we analyze the conventional MI estimators, propose and theoretically justify a complementary lossy compression step to tackle the problems of high dimensionality and derive theoretical bounds on mutual information estimate under lossy compression. ### Mutual information estimation The most straightforward way to estimate mutual information is to estimate all the components in (2) or (1). There are several methods of entropy estimation that require only a set of samples from multivariate distribution: plug-in estimators [33; 34], kernel density-based approaches [33; 35], weighted and non-weighted Kozachenko-Leonenko estimators [36; 37] and other. However, all the mentioned approaches fail to correctly estimate the entropy of high-dimensional random vectors. We assume the manifold hypothesis (i.e., that data lie along (or close to) some manifold in multidimensional space). This is believed to be true for a large variety of structured data; some datasets are known to satisfy this assumption exactly. In our work we use the following simplified definition of the manifold hypothesis: **Definition 2**.: _A random vector \(X\colon\Omega\to\mathbb{R}^{n}\) is said to strictly satisfy the manifold hypothesis iff there exist \(\xi\colon\Omega\to\mathbb{R}^{n^{\prime}}\) and \(f\colon\mathbb{R}^{n^{\prime}}\to\mathbb{R}^{n}\) satisfying the conditions of Statement 1, such that \(X=f(\xi)\). A random vector \(X^{\prime}\colon\Omega\to\mathbb{R}^{n}\) is said to loosely satisfy the manifold hypothesis iff \(X^{\prime}=X+Z\), where \(X\) strictly satisfies the manifold hypothesis, and \(Z\) is insignificant in terms of some metric._ To avoid support of measure zero, the probability measure induced on the manifold is considered. As we will show, considering induced PDFs can also solve the problem of high dimensionality, as the small intrinsic dimension of the manifold allows conventional entropy estimators to be applied. Let \(\{(x_{k},y_{k})\}_{k=1}^{N}\) be a sequence of samples from the joint distribution of random vectors \(X\) and \(Y\). Our goal is to estimate the mutual information between \(X\) and \(Y\), i.e. \(I(X;Y)\), from these samples. To overcome the curse of dimensionality, we suggest learning the manifold with autoencoders [38; 39] and apply conventional estimators to the compressed representations. First, let us suppose that random vectors \(X\) and \(Y\) are absolutely continuous, and corresponding autoencoders are provided: \(A_{X}=D_{X}\circ E_{X}\), \(A_{Y}=D_{Y}\circ E_{Y}\). **Corollary 1**.: _Let \(E_{X}^{-1}\colon\mathbb{R}^{n^{\prime}}\supseteq E_{X}(\operatorname{supp}X) \to\mathbb{R}^{n}\), \(E_{Y}^{-1}\colon\mathbb{R}^{m^{\prime}}\supseteq E_{Y}(\operatorname{supp}Y) \to\mathbb{R}^{m}\), \(E_{X}(X)\colon\Omega\to\mathbb{R}^{n^{\prime}}\) and \(E_{Y}(Y)\colon\Omega\to\mathbb{R}^{m^{\prime}}\) exist and satisfy conditions of the Statement 1. Then_ \[I(X;Y)=I(E_{X}(X);E_{Y}(Y)),\] _so the mutual information estimate can be computed as follows:_ \[\hat{I}(X;Y)=\hat{I}(E_{X}(X);E_{Y}(Y))=\hat{h}(E_{X}(X))+\hat{h}(E_{Y}(Y))- \hat{h}(E_{X}(X),E_{Y}(Y)) \tag{4}\] Now, the case of absolutely continuous \(X\) and discrete \(Y\) should be considered. In this case, it is impractical to use (2), as the (induced) joined probability distribution is neither absolutely continuous nor discrete. However, (1) is still valid: \[h(X\mid Y)=\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\! \!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\! \!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\! \!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\! \!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\! \!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\! \!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\! \!\! Probabilities \(p_{Y}\) can be estimated using empirical frequencies: \(\hat{p}_{Y}(y)=\frac{1}{N}\cdot|\{k\mid y_{k}=y\}|\). Conditional entropy \(h(X\mid Y=y)\) can be estimated using corresponding subsets of \(\{x_{k}\}_{k=1}^{N}\): \(\hat{h}(X\mid Y=y)=\hat{h}(\{x_{k}\mid y_{k}=y\})\). **Corollary 2**.: _Let \(E_{X}^{-1}\colon\mathbb{R}^{n^{\prime}}\supseteq E_{X}(\text{supp}\,X)\to \mathbb{R}^{n}\), \(E_{X}(X)\colon\Omega\to\mathbb{R}^{n^{\prime}}\) and \(Y\colon\Omega\to\text{supp}\,Y\) satisfy conditions of the Statement 1. Then_ \[I(X;Y)=I(E_{X}(X);Y),\] _so the mutual information estimate can be computed as follows:_ \[\hat{I}(X;Y)=\hat{I}(E_{X}(X);Y)=\hat{h}(E_{X}(X))-\sum_{y\in\text{supp}\,Y} \hat{p}_{Y}(y)\cdot\hat{h}(E_{X}(X)\mid Y=y) \tag{5}\] According to the strong law of large numbers, \(\hat{p}\xrightarrow{\text{a.s.}}p\). That is why the convergence of the proposed MI estimation methods solely relies on the convergence of the entropy estimator used in (4) and (5). ### Bounds for mutual information estimate It can be shown that it is not possible to derive non-trivial bounds for \(I(E_{X}(X);E_{Y}(Y))\) and \(I(E_{X}(X);Y)\) in general case if Corollaries 1, 2 do not hold. Let us consider a simple linear autoencoder, optimal in terms of mean squared error (i.e. principal component analysis-based). The following statement shows that there are cases when the proposed method of mutual information estimation via lossy compression fails to estimate the MI. **Statement 2**.: _For any given \(\varkappa\geq 0\) there exist random variables \(X\colon\Omega\to\mathbb{R}^{n}\), \(Y\colon\Omega\to\mathbb{R}^{m}\) and non-trivial linear autoencoder \(A=D\circ E\) with latent space dimension \(n^{\prime}<n\), optimal in terms of minimizing mean squared error \(\mathbb{E}\,\|X-A(X)\|^{2}\), such that \(I(X;Y)=\varkappa\) and \(I(E(X);Y)=0\)._ Proof.: Let us consider the following three-dimensional Gaussian vector \((X_{1},X_{2},Y)\triangleq(X,Y)\): \[X\sim\mathcal{N}\left(0,\begin{bmatrix}1&0\\ 0&\sigma\end{bmatrix}\right),\qquad Y\sim\mathcal{N}(0,1)\qquad(X_{1},X_{2},Y) \sim\mathcal{N}\left(0,\begin{bmatrix}1&0&0\\ 0&\sigma&a\\ 0&a&1\end{bmatrix}\right),\] where \(\text{cov}(X_{2},Y)=a\triangleq\sqrt{1-e^{-2\varkappa}}\), \(\text{cov}(X_{1},Y)=0\) (so \(X_{1}\) and \(Y\) are independent). Let the intrinsic dimension be \(n^{\prime}=1\), and \(\sigma<1\). According to the principal component analysis, the optimal linear encoder is defined up to a scalar factor by the equality \(E(X)=X_{1}\). However, \(I(X;Y)=-\frac{1}{2}\ln\left(1-a^{2}\right)=\varkappa\) (see the Statement 4), but \(I(E(X);Y)=0\), as \(A(X)\) and \(Y\) are independent. This statement shows that an arbitrary amount of information can be lost due to the compression. It follows from the fact that "less significant" in terms of metric spaces does not comply with "less significant" in terms of information theory. However, with some additional assumptions, a more useful theoretical result can be achieved. **Statement 3**.: _Let \(X\), \(Y\) and \(Z\) be random variables such that \(I(X;Y)\) and \(I\left((X,Z);Y\right)\) are defined. Let \(f\) be a function of two arguments such that \(I(f(X,Z);Y)\) is defined. If there exists a function \(g\) such that \(X=g(f(X,Z))\), then the following inequalities hold:_ \[I(X;Y)\leq I\left(f(X,Z);Y\right)\leq I((X,Z);Y)\] Here \(f(X,Z)\) can be interpreted as (compressed) noisy data, \(X\) -- as denoised data, and \(g\) -- as a perfect denoising autoencoder. This statement justifies the proposed lossy compression method in some cases (namely, when data lost by compression can be considered as an independent random noise). **Corollary 3**.: _Let \(X\), \(Y\), \(Z\), \(f\) and \(g\) satisfy the conditions of the Statement 3. Let also random variables \((X,Y)\) and \(Z\) be independent. Then \(I(X;Y)=I\left(f(X,Z);Y\right)\)._ These bounds are optimal due to the optimality of the data processing inequality, but additional knowledge about the connection between \(X\), \(Y\), and \(Z\) is required to properly utilize them. Other bounds can also be derived [21; 23; 40], but they do not utilize the fact of compression. ## 4 Synthetic dataset generation In order to test the proposed mutual information estimator we develop an universal method for synthetic dataset generation with defined information-theoretic properties. This method yields two random vectors \(X\) and \(Y\) which have predefined value of mutual information \(I(X;Y)\). The method requires \(X\) and \(Y\) to be images of normally distributed vectors under some known nonsingular smooth mappings. The generation consists of two steps: first, a normal vector \((\xi,\eta)\sim\mathcal{N}(0,M)\) is considered, where \(\xi\sim\mathcal{N}(0,I_{n^{\prime}})\), \(\eta\sim\mathcal{N}(0,I_{m^{\prime}})\) and \(n^{\prime}\), \(m^{\prime}\) are dimensions of \(\xi\) and \(\eta\) respectively. The covariance matrix \(M\) is chosen to satisfy \(I(\xi;\eta)=\varkappa\), where \(\varkappa\) is an arbitrary non-negative constant. **Statement 4**.: _Let \((\xi,\eta)\sim\mathcal{N}(0,M)\) be a Gaussian pair of (scalar) random variables with unit variance such that \(I(\xi;\eta)=\varkappa\). Then_ \[M=\begin{bmatrix}1&a\\ a&1\end{bmatrix},\qquad a=\sqrt{1-e^{-2\varkappa}} \tag{6}\] **Corollary 4**.: _For every \(\varkappa\geq 0\) and every \(n^{\prime},m^{\prime}\in\mathbb{N}\) exists a matrix \(M\in\mathbb{R}^{(n^{\prime}+m^{\prime})\times(n^{\prime}+m^{\prime})}\) such that \((\xi,\eta)\sim\mathcal{N}(0,M)\), \(\xi\sim\mathcal{N}(0,I_{n^{\prime}})\), \(\eta\sim\mathcal{N}(0,I_{m^{\prime}})\) and \(I(\xi;\eta)=\varkappa\)._ The second step of the method is the application of smooth nonsingular mappings to vectors \(\xi\) and \(\eta\): \(X=f(\xi)\), \(Y=g(\eta)\). Due to the Statement 1, \(I(\xi;\eta)=I(X;Y)\). ## 5 Comparison of the entropy estimators The MI estimate is acquired according to Subsection 3.1. To estimate the entropy terms in (2) or (1) we leverage conventional entropy estimators, such as kernel density-based and Kozachenko-Leonenko estimators (original and weighted versions), see Table 1. To test the accuracy of these approaches, we use datasets sampled from synthetic random vectors with known MI. We generate these datasets in accordance to Section 4. To examine the impact of the compression step proposed in Subsection 3.1 we utilize a special type of synthetic datasets. Synthetic data lies on a manifold of small dimension. This is achieved by generating a low-dimensional dataset and then embedding it into a high-dimensional space by a smooth mapping (so the Statement 1 can be applied). Then the acquired datasets are compressed via autoencoders. Finally, the obtained results are fed into a mutual information estimator. The Algorithm 1 and Figure 2 describe the proposed mutual information estimation quality measurement. We run several experiments with \(f\) and \(g\) mapping normal distributions to rasterised images of geometric shapes (e.g. rectangles) or 2D-plots of smooth functions (e.g. Gaussian functions). The results are presented in the Figures 3 and 4. Blue and green curves correspond to the estimates of MIs marked by the corresponding colors in Figure 2. Thus, we see that the compression step do not lead to bad estimation accuracy especially for KL and WKL estimators, which demonstrate the best performance. In what follows we use WKL estimator. ## 6 Information flow in deep neural networks This section is dedicated to the information flow estimation in DNNs via the proposed method. We estimate information flow in a convolutional classifier of the MNIST handwritten digits dataset [32]. This neural network is simple enough to be quickly trained and tested, but, at the same time, is complex enough to suffer from the curse of dimensionality. The MNIST dataset consists of images of size \(28\times 28=784\) pixels. It was shown in [44] that these images have relatively low latent space Figure 3: Maximum-likelihood and Least Squares Error KDE, Non-weighted and Weighted Kozachenko-Leonenko for \(16\times 16\) (first row) and \(32\times 32\) (second row) images of gaussians (\(n^{\prime}=m^{\prime}=3\)), \(5\cdot 10^{3}\) samples. Along \(x\) axes is \(I(X;Y)\), along \(y\) axes is \(\hat{I}(X;Y)\). Figure 2: Conceptual scheme of Algorithm 1. In order to observe and quantify the loss of information caused by the compression step, we split \(f\colon\mathbb{R}^{n^{\prime}}\to\mathbb{R}^{n}\) into two functions: \(f_{1}\colon\mathbb{R}^{n^{\prime}}\to\mathbb{R}^{n^{\prime}}\) maps \(\xi\) to a structured latent representation of \(X\) (e.g. to parameters of geometric shapes), and \(f_{2}\colon\mathbb{R}^{n^{\prime}}\to\mathbb{R}^{n}\) maps latent representations to corresponding high-dimensional vectors (e.g. rasterised images of geometric shapes). The same goes for \(g=g_{2}\circ g_{1}\). Colors correspond to the Figures 3 and 4. dimension -- about \(12\)-\(13\). If the preservation of only main features is desired, the latent space can even be narrowed down to \(3\)-\(10\). It can be concluded from the previous section that the weighted Kozachenko-Leonenko estimator is superior to the other methods tested in this paper. That is why this estimator is used in experiments with the MNIST classifier described in the current section. The analyzed network is designed to return the output of every layer. To avoid the problem of a deterministic relationship between input and output, a small additive Gaussian noise is injected on each layer (we use constant signal-to-noise ratio). Lossy compression of input images \(X\) is performed via convolutional autoencoder with latent dimension \(d_{X}^{\text{latent}}\). Lossy compression of layer outputs \(L_{i}\) is performed via principal component analysis with \(d_{L_{i}}^{\text{latent}}\) as the number of principal components. The general algorithm is described in 2. ``` 1:Compress the input dataset \(\{x_{k}\}_{k=1}^{N}\) via the encoder \(E_{X}\): \(c_{k}^{X}=E_{X}(x_{k})\). 2:for epoch : \(1,\dots,\text{number of epochs}\)do 3:for\(L_{i}\) : layers do 4: Collect outputs of the layer \(L_{i}\): \(y_{k}^{L_{i}}=L_{i}(x_{k})\). Each layer must be noisy/stochastic. 5: Compress the outputs via encoder \(E_{L_{i}}\): \(c_{k}^{L_{i}}=E_{L_{i}}(y_{k}^{L_{i}})\). 6: Estimate \(I(E_{X}(X);E_{L_{i}}(L_{i}))\) and \(I(E_{L_{i}}(L_{i});Y(X))\), where \(Y\) maps inputs to their true targets. 7:endfor 8: Perform one-epoch training step of the network. 9:endfor ``` **Algorithm 2** Estimate information flow in the neural network during training We use the architecture of the classification network provided in Table 2. We train our network with a learning rate equaling \(10^{-5}\) using Nvidia Titan RTX. For other hyperparameters we refer to the source code [43]. The acquired information plane plots are provided by Figure 5. As the direction of the plots with respect to the epoch can be deduced implicitly (the lower left corner of the plot corresponds to the first epochs), we color the lines in accordance with loss function dynamics per epoch. We do this to stress out one of the key observations: the first transition from fitting to compression phase coincides with the acceleration of loss function decrease. It is also evident that there is no clear large-scale compression phase. Moreover, it seems that the number of fitting and compression phases can vary from layer to layer. \begin{table} \begin{tabular}{l l} \(L_{1}\): & Conv2d(1, 8, ks=3), LeakyReLU(0.01) \\ \(L_{2}\): & Conv2d(8, 16, ks=3), LeakyReLU(0.01) \\ \(L_{3}\): & Conv2d(16, 32, ks=3), LeakyReLU(0.01) \\ \(L_{4}\): & Dense(32, 32), LeakyReLU(0.01) \\ \(L_{5}\): & Dense(32, 10), LogSoftMax \\ \end{tabular} \end{table} Table 2: The architecture of the MNIST convolution-DNN classifier used in this paper. Figure 4: Maximum-likelihood and Least Squares Error KDE, Non-weighted and Weighted Kozachenko-Leonenko for \(16\times 16\) (first row) and \(32\times 32\) (second row) images of rectangles (\(n^{\prime}=m^{\prime}=4\)), \(5\cdot 10^{3}\) samples. Along \(x\) axes is \(I(X;Y)\), along \(y\) axes is \(\hat{I}(X;Y)\). ## 7 Discussion An information-theoretic approach to explainable artificial intelligence and deep neural networks analysis seems promising, as it is interpretable, robust, and relies on the well-developed information theory. However, the direct application of information-theoretic analysis still constitutes some problems. The main contribution of our work is overcoming challenges caused by the curse of dimensionality in the information theory of machine learning. We have shown that it is possible to apply information analysis to compressed representations of datasets or models' outputs. In order to justify our approach, we have acquired several theoretic results regarding mutual information estimation under lossless and lossy compression. These results suggest that this approach is applicable to real data cases. Although it has been shown that an arbitrary amount of information can be lost due to compression, the information required for optimal decompression is still preserved. We have also developed a framework to test conventional mutual information estimators complemented with the proposed lossy compression step. This framework allows generating of pairs of high-dimensional datasets with small internal (latent) dimensions and a predefined quantity of mutual information. Conducted numerical experiments have shown that the proposed method performs well, especially if entropy estimation is done via a weighted Kozachenko-Leonenko estimator; other methods tend to underestimate or overestimate mutual information. Finally, an information plane experiment with the MNIST dataset classifier has been carried out. This experiment has shown that dynamics of information-theoretic quantities during the training of deep neural networks are, indeed, non-trivial. However, it is not clear whether the original fitting-compression hypothesis holds, as there is no clear large-scale compression phase after the fitting. We suggest that there may be several compression/fitting phases during the training of real-scale neural networks. An interesting observation has also been obtained: the first compression phase coincides with the rapid decrease of loss function (i.e. with the highest absolute value of loss function delta per epoch). It may be concluded that phases revealed by information plane plots are connected Figure 5: Information plane plots for the MNIST classifier. The lower left parts of the plots correspond to the first epochs of training. to different regimes of learning (i.e. accelerated, stationary or decelerated drop of loss function). However, further investigation of this phenomenon has to be carried out in order to supply this seeming connection with more evidence and theoretical basis. As a further research we consider using normalizing flows to improve our approach [45]. Normalizing flows are invertible smooth mappings, providing means of lossless and information-preserving compression. Normalizing flows can also be used to transform the joint distribution to a Gaussian, thus facilitating mutual information estimation.
2305.03152
Communication-Efficient Graph Neural Networks with Probabilistic Neighborhood Expansion Analysis and Caching
Training and inference with graph neural networks (GNNs) on massive graphs has been actively studied since the inception of GNNs, owing to the widespread use and success of GNNs in applications such as recommendation systems and financial forensics. This paper is concerned with minibatch training and inference with GNNs that employ node-wise sampling in distributed settings, where the necessary partitioning of vertex features across distributed storage causes feature communication to become a major bottleneck that hampers scalability. To significantly reduce the communication volume without compromising prediction accuracy, we propose a policy for caching data associated with frequently accessed vertices in remote partitions. The proposed policy is based on an analysis of vertex-wise inclusion probabilities (VIP) during multi-hop neighborhood sampling, which may expand the neighborhood far beyond the partition boundaries of the graph. VIP analysis not only enables the elimination of the communication bottleneck, but it also offers a means to organize in-memory data by prioritizing GPU storage for the most frequently accessed vertex features. We present SALIENT++, which extends the prior state-of-the-art SALIENT system to work with partitioned feature data and leverages the VIP-driven caching policy. SALIENT++ retains the local training efficiency and scalability of SALIENT by using a deep pipeline and drastically reducing communication volume while consuming only a fraction of the storage required by SALIENT. We provide experimental results with the Open Graph Benchmark data sets and demonstrate that training a 3-layer GraphSAGE model with SALIENT++ on 8 single-GPU machines is 7.1 faster than with SALIENT on 1 single-GPU machine, and 12.7 faster than with DistDGL on 8 single-GPU machines.
Tim Kaler, Alexandros-Stavros Iliopoulos, Philip Murzynowski, Tao B. Schardl, Charles E. Leiserson, Jie Chen
2023-05-04T21:04:01Z
http://arxiv.org/abs/2305.03152v1
Communication-Efficient Graph Neural Networks with Probabilistic Neighborhood Expansion Analysis and Caching ###### Abstract Training and inference with graph neural networks (GNNs) on massive graphs has been actively studied since the inception of GNNs, owing to the widespread use and success of GNNs in applications such as recommendation systems and financial forensics. This paper is concerned with minibatch training and inference with GNNs that employ node-wise sampling in distributed settings, where the necessary partitioning of vertex features across distributed storage causes feature communication to become a major bottleneck that hampers scalability. To significantly reduce the communication volume without compromising prediction accuracy, we propose a policy for caching data associated with frequently accessed vertices in remote partitions. The proposed policy is based on an analysis of vertex-wise inclusion probabilities (VIP) during multi-hop neighborhood sampling, which may expand the neighborhood far beyond the partition boundaries of the graph. VIP analysis not only enables the elimination of the communication bottleneck, but it also offers a means to organize in-memory data by prioritizing GPU storage for the most frequently accessed vertex features. We present SALIENT++, which extends the prior state-of-the-art SALIENT system to work with partitioned feature data and leverages the VIP-driven caching policy. SALIENT++ retains the local training efficiency and scalability of SALIENT by using a deep pipeline and drastically reducing communication volume while consuming only a fraction of the storage required by SALIENT. We provide experimental results with the Open Graph Benchmark data sets and demonstrate that training a 3-layer GraphSAGE model with SALIENT++ on 8 single-GPU machines is \(7.1\times\) faster than with SALIENT on 1 single-GPU machine, and \(12.7\times\) faster than with DistDGL on 8 single-GPU machines. ## 1 Introduction Graph neural networks (GNNs) are an important class of machine learning models that incorporate relational inductive bias for effective representation learning on graph structured data (Li et al., 2016; Kipf and Welling, 2017; Hamilton et al., 2017; Velickovic et al., 2018; Xu et al., 2019). These neural networks have been successfully applied in a number of use cases, including product recommendation, traffic forecasting, and financial forensics (Ying et al., 2018; Li et al., 2018; Weber et al., 2019). In many applications, data are continuously collected and the resulting graph grows rapidly, calling for efficient GNN training and inference systems that can scale with the explosive increase of graph data. This work considers minibatch training and inference with neighborhood sampling in the distributed setting, where vertex data (features) are partitioned across machines. As opposed to full-batch optimization, minibatch optimization is typical for training neural networks, but it poses a unique challenge for GNNs because of the exponential increase of neighborhood size across network layers (Chen et al., 2018). Neighborhood sampling is a popular and effective approach to mitigating this issue (Hamilton et al., 2017; Chen et al., 2018; Ying et al., 2018; Zou et al., 2019; Zeng et al., 2020; Ramezani et al., 2020; Dong et al., 2021). In distributed GNN training, each machine computes the training loss for a minibatch of vertices that are local to the machine's partition. At every step of the training optimization, a set of partition-wise minibatches forms a "distributed minibatch" which is used to update the GNN model parameters. Distributed GNN inference is organized similarly. Even with neighborhood sampling, minibatch neighborhood expansion creates a communication bottleneck as each machine needs to access remote data for sampled vertices. The communication pattern is stochastic because of the random nature of minibatch and neighborhood sampling. Communication time often dominates the time for training computations. An example of this bottleneck effect is shown in Table 1, which we will walk through shortly. To overcome the communication bottleneck, we propose an analysis of neighborhood access patterns via vertex inclusion probabilities, as well as a caching policy based on the analysis. We refer to this analysis as "VIP analysis." In contrast to commonly used heuristics for estimating vertex access probabilities -- e.g., based on vertex degree and expanded boundary frontiers (Lin et al., 2020), random walks (Dong et al., 2021; Min et al., 2021), or simulated GNN computations (Yang et al., 2022) -- VIP analysis estimates access probabilities for all graph vertices based on an analytical model of the actual stochastic neighborhood expansion process. We derive the specific VIP model for the important class of node-wise sampling schemes (Hamilton et al., 2017; Ying et al., 2018; Velickovic et al., 2018; Xu et al., 2019; Liu et al., 2020) and find that the resulting caching policy drastically reduces the communication volume in distributed GNNs that employ node-wise sampling with only a modest memory overhead. Moreover, VIP analysis offers a means to organize in-memory data by prioritizing GPU storage for the most frequently accessed vertex features, reducing host-to-device data transfers. Our system, SALIENT++, is developed over SALIENT (Kaler et al., 2022), an efficient GNN system that achieves state-of-the-art performance through performance-engineered neighborhood sampling, shared-memory parallel batch preparation, and data-transfer pipelining. SALIENT achieves per-epoch time that is nearly equal to the GPU time for model computation alone (effectively hiding the cost of minibatch construction, data transfer, and gradient communication), and it scales well with additional machines. But SALIENT has the drawback of replicating the entire data set on each machine, imposing a hard limit on the data set size. Extending SALIENT to distribute vertex feature data requires addressing the feature communication bottleneck. SALIENT++ uses the VIP-analysis-driven caching policy and a deep pipeline to achieve scalability and efficiency. It nearly matches the performance of SALIENT with only a fraction of SALIENT's memory requirements. To highlight the efficacy of SALIENT++, Table 1 lists the resulting performance of progressive modifications on top of SALIENT. This example uses the ogbn-papers100M data set (Hu et al., 2020) and partitions the graph using METIS (Karypis & Kumar, 1997) with an edge-cut minimization objective and balancing constraints for the number of training, validation, and overall vertices, as well as the total number of edges, in each partition. Accompanying Table 1, Figure 1 illustrates the key differences between SALIENT and the successive optimizations in SALIENT++ using simplified computation profiles and storage requirement depictions. We first explore the distributed performance of SALIENT with a disjoint partitioning of feature data across machines. We modify SALIENT to only replicate the graph structure and communicate vertex features on demand and in bulk for each minibatch and its sampled neighborhood. Although distributing the vertex features reduces SALIENT's memory requirement substantially, it also leads to an immediate performance degradation. Specifically, we observe slowdown of roughly \(2\)-\(3\times\) on two or four machines and \(3.5\times\) on eight machines relative to SALIENT with full-replication. This slowdown presents itself in the form of high latencies between GNN model computations (row 2 in Figure 1). Overlapping feature communication with other GNN operations (sampling, local feature slicing, host-to-device transfers, training computations, and model updates) through pipelining offers some improvement, but the system remains bottlenecked by communication (row 3 in Figure 1). If we allow a small memory overhead to cache frequently accessed remote features locally, however, the combined effects of reduced communication volume and pipelining boost performance substantially. The sheer reduction of communication volume due to caching makes it possible for pipelining to (nearly) fully hide communication (4th row in Figure 1). On \(K\) machines, SALIENT++ reduces the total feature memory footprint of SALIENT by almost a factor of \(K\) while matching the performance achieved by SALIENT's full-replication strategy. In summary, this work makes the following contributions: 1. An analysis of vertex inclusion probabilities (VIP) during GNN neighborhood expansion with node-wise sampling. We show how VIP analysis can be used to minimize the expected communication among machines as well as the host-to-device data transfers within each machine. 2. The design and implementation of SALIENT++, a system for distributed GNN training and inference that is both efficient and scalable. The system is based on two key components: a maximum-likelihood static caching policy for remote and local features based on VIP analysis; and a deep pipeline that overlaps feature communication with other GNN operations, ensuring high utilization \begin{table} \begin{tabular}{l c c c c} \hline \hline & \multicolumn{4}{c}{_No. of machines_} \\ \cline{2-5} _System_ & 1 & 2 & 4 & 8 \\ \hline _SALIENT (Full replication)_ & 20.7s & 10.76s & 6.02s & 3.08s \\ _+ Partitioned features_ & — & 33.04s & 15.98s & 10.85s \\ _+ Pipeline communication_ & — & 16.12s & 8.73s & 5.43s \\ _+ Feature caching_ & — & 10.51s & 5.45s & 2.91s \\ \hline \hline \end{tabular} \end{table} Table 1: Per-epoch runtime of a progressively more sophisticated distributed GNN training system on the undirected ogbn-papers100M data set, using a 3-layer GraphSAGE architecture with sampling fanouts (15,10,5) and a hidden layer dimension of 256. For the system with remote feature caching, the size of the cache relative to the size of local-vertex features for each machine was 8% (2 machines), 16% (4 machines), or 32% (8 machines). of available network bandwidth. 3. A systematic evaluation of the end-to-end training performance and scalability of SALIENT++ on three large benchmark graphs. On the largest of these data sets, which does not fit in-memory on one machine, SALIENT++ achieves a speedup of \(1.75\times\) when scaling from 4 to 8 single-GPU machines and an additional \(1.45\times\) when scaling from 8 to 16 single-GPU machines. ## 2 Background and Related Work This section briefly recalls background and introduces notation for GNNs and their training/inference. It also discusses related work on systems and distributed training. ### Graph neural networks This work focuses on the class of _message passing neural networks_ (MPNNs) (Gilmer et al., 2017), which encompasses many GNNs of major interest for massive graphs. Let \(G=(\mathcal{V},\mathcal{E})\) be a graph with \(\mathcal{V}\) being the vertex set and \(\mathcal{E}\) being the edge set. Let \(X\in\mathbb{R}^{N\times D}\) be the vertex feature matrix, where \(N\) is the number of vertices and \(D\) is the feature dimension. A row of \(X\), denoted by \(x_{v}\in\mathbb{R}^{D}\), is the feature vector of a vertex \(v\). Let \(\ell=0,\ldots,L\) denote the layer index and \(\mathcal{N}_{1}(v)\) be the one-hop neighborhood of \(v\). MPNNs use the following update rule to define a layer: \[h_{v}^{\ell}=\textsc{upd}^{\ell}\Big{(}h_{v}^{\ell-1},\textsc{agg}^{\ell} \big{(}\{h_{u}^{\ell-1}\mid u\in\mathcal{N}_{1}(v)\}\big{)}\Big{)}, \tag{1}\] where \(h_{v}^{\ell}\) is the layer-\(\ell\) representation of \(v\), \(\textsc{agg}^{\ell}\) is a set aggregation function, \(\textsc{upd}^{\ell}\) is a two-argument update function, and \(h_{v}^{0}=x_{v}\). One sees that the representation of a vertex \(v\) depends on the past-layer representations of \(v\) and its neighbors in \(\mathcal{N}_{1}(v)\); and this dependence is recursive. GNNs differ in their design of the two functions in (1). For example, in GraphSAGE (Hamilton et al., 2017), \(\textsc{agg}^{\ell}\) is a mean, LSTM, or pooling operator, and \(\textsc{upd}^{\ell}\) concatenates the two arguments and applies a linear layer. In GIN (Xu et al., 2019), \(\textsc{agg}^{\ell}\) is the sum of \(\{h_{u}^{\ell-1}\}\) and \(\textsc{upd}^{\ell}\) is the sum of its arguments followed by an MLP. In GAT (Velickovic et al., 2018), \(\textsc{agg}^{\ell}\) is the identity and \(\textsc{upd}^{\ell}\) computes \(h_{v}^{\ell}\) as a weighted combination of \(W^{\ell-1}h_{u}^{\ell-1}\) for all \(u\in\{v\}\cup\mathcal{N}_{1}(v)\), where the weights are attention coefficients and \(W^{\ell-1}\) is the parameter matrix of the layer. ### Minibatch training Neural networks can be trained with gradient descent (full-batch training) or stochastic gradient descent methods (minibatch training). A majority of the deep learning literature advocates minibatch training, with theoretical and empirical evidence suggesting that it converges faster, generalizes better, and is more suitable for GPU-oriented computing infrastructures (Bottou et al., 2018). Minibatch training incurs a unique challenge for GNNs, often termed the "neighborhood explosion" problem: to compute the training loss for a vertex \(v\), equation (1) indicates that it requests information from the neighborhood recursively, growing its size exponentially with the number of layers. For a reasonably sized minibatch, the multi-hop neighborhood quickly covers a large portion of the graph, incurring a prohibitive time cost that eclipses the saving in convergence speed. Moreover, the storage requirement easily exceeds the memory capacity of a GPU. Figure 1: Illustration of distributed GNN computation profiles and feature data storage for the precursor system SALIENT and successive optimizations leading to our system SALIENT++. **Left:** Utilization of system resources (CPU, GPU, and network) in one machine. The processing of each minibatch is broken into three parts: "MFG": message-flow graph construction. “Feat.”: local feature tensor slicing, feature communication and joining, and host-to-device transfers. “Model”: forward and backward passes, plus communication among machines for model updates. In addition to the highlighted minibatch, the profiles also depict parts of a preceding and a succeeding minibatch in faded colors to show overlap between pipelined operations. **Right:** The color-stacked bars indicate the number of locally stored feature vectors in each of \(K\) total machines. ### Neighborhood sampling Restricting the neighborhood size by sampling is an effective method for tackling the neighborhood explosion problem. Three major types of sampling strategies are node-wise sampling (Hamilton et al., 2017; Ying et al., 2018), layer-wise sampling (Chen et al., 2018; Zou et al., 2019), and subgraph sampling (Chiang et al., 2019; Zeng et al., 2020). Node-wise sampling approaches modify the neighborhood for each vertex \(v\) separately by taking a random subset containing at most \(f\) neighbors (called the _fanout_). Layer-wise sampling approaches collect the neighbors of all vertices in a minibatch and sample the neighborhood from their union. Such sampling proceeds recursively layer by layer and can use a nontrivial sampling distribution to control pre-activation variance while preserving unbiasedness. Nonlinear activation functions destroy unbiasedness anyway, but training convergence results can still be established based on asymptotic consistency (Chen and Luss, 2018). Subgraph sampling approaches sample a connected subgraph and compute the minibatch loss restricted to this subgraph. This work focuses on node-wise sampling for its widespread use. ### Minibatch inference Similar to training, inference can be performed in either full batches or minibatches. Whereas the choice between full batch or minibatch training centers on convergence and generalization, the choice made for inference depends on the computational pattern and implementation effort. Full-batch inference avoids neighborhood sampling but requires a separate implementation of the forward pass for different GNN architectures. On the other hand, minibatch inference can reuse the forward function for training, improving productivity for application developers and architecture designers, but the stochastic nature of neighborhood sampling may return different predictions and does not guarantee the same accuracy as the case of not performing sampling. Nevertheless, the authors of SALIENT demonstrate strong empirical results that show that prediction accuracy is not compromised with a reasonable choice of the fanouts (Kaler et al., 2022). This work follows the practice of minibatch inference. ### Related work Due to the computational pattern of neighborhood aggregation, GNN training systems on massive graphs differ substantially from those for usual neural networks in design and implementation. Many GNN systems are developed based on full-batch training for simplicity, which avoids the complication of neighborhood sampling. Examples include NeuGraph (Ma et al., 2019), Roc (Jia et al., 2020), DeepGalois (Hoang et al., 2021), FlexGraph (Wang et al., 2021), Seastar (Wu et al., 2021), GNAdvisor (Wang et al., 2021), DistGNN (Md et al., 2021), and BNS-GCN (Wan et al., 2022). Some of these systems are built on common deep learning frameworks, such as TensorFlow (Abadi et al., 2015) and PyTorch (Paszke et al., 2019), while others are built on self-developed programming models. Examples of systems that perform minibatch training include DistDGL (Zheng et al., 2020), Zero-Copy (Min et al., 2021), GNS (Dong et al., 2021), and \(P^{3}\)(Gandhi and Iyer, 2021). However, these publications report results on either multiple machines with only CPUs or a single machine with one or multiple GPUs. A newer version of DistDGL (DistDGLv2 (Zheng et al., 2021)), SALIENT (Kaler et al., 2022), and our system SALIENT++ demonstrate results in the distributed multi-GPU setting. SALIENT++ employs edge-cut graph partitioning to distribute data across machines. An alternative approach, adopted by DistGNN (Md et al., 2021), is vertex-cut partitioning, which ensures each edge is local to some machine. A drawback of this approach is that a vertex may be assigned to multiple machines, leading to memory overhead due to feature replication that is reported to be as high as 5\(\times\). SALIENT++, on the other hand, achieves high distributed performance with less than 50% memory overhead due to caching in our experiments. SALIENT++ employs a caching policy to reduce communication and data transfer. We introduce a policy based on an analysis of vertex access probabilities during neighborhood sampling. Although caching has been explored by several other systems in this context, previous caching policies are heuristic, using proxy measures such as vertex degrees (Lin et al., 2020), random walks (Dong et al., 2021; Min et al., 2021), or simulated access frequencies (Yang et al., 2022). A complementary approach to reducing communication time is taken by DGCL (Cai et al., 2021), which uses a communication-planning algorithm to optimize the communication pattern for a specific network topology. Marius and MariusGNN (Mohoney et al., 2021; Waleffe et al., 2022) are out-of-core training systems that work on a single machine by exploiting external memory. They operate in a different setting from ours, but our vertex inclusion probability analysis may be used in complement to optimize on-disk data representation and disk I/O. ## 3 Vertex inclusion probabilities for GNNs with node-wise sampling This section describes a principled approach to estimating and reducing data access costs in distributed GNNs with node-wise sampling. Node-wise sampling was notably introduced in GraphSAGE (Hamilton et al., 2017) and is used with a variety of GNN architectures (Ying et al., 2018; Velickovic et al., 2018; Xu et al., 2019; Liu et al., 2020). We first introduce _vertex-inclusion probability_ (_VIP_) analysis to calculate the probability that any vertex will be present in the sampled \(L\)-hop expanded neighborhood of a minibatch in some partition. VIP analysis takes into account the distinctive structure of neighbor accesses in GNNs with minibatches and node-wise sampling. We then demonstrate that VIP analysis enables a simple but highly effective strategy for reducing data movement during GNN computations. The VIP model for node-wise sampling derived in this section does not apply to other sampling schemes, such as layer-wise or subgraph sampling. It may be possible to derive VIP models for these other sampling schemes in a similar way, but this is outside our scope. ### Analysis of vertex inclusion probabilities in \(L\)-hop neighborhoods with node-wise sampling We analyze the following random process, which models neighborhood expansion in GNN architectures with node-wise sampling. (i) Start from a set of vertices rather than a single vertex. (ii) For each vertex in the starting set, sample a set of direct neighbors without replacement, thereby expanding the walk frontier. (iii) Using the union of sampled neighborhoods as the new starting set, repeat step (ii). The process terminates after \(L\) repetitions (i.e., hops). We assume that sampling is independent across hops and across vertices in the current-hop set. That is, although each vertex samples among its direct neighbors without replacement, different vertices may sample the same direct neighbor. We seek to estimate the vertex inclusion probabilities, or VIP values, in expanded neighborhoods that are obtained per the above random process. The VIP values form a vector of probabilities \(p(u)\) over all graph vertices. We can express \(p(u)\) via hop-wise VIP vectors \(p^{[h]}(u)\) that contain the probabilities that any vertex \(u\) is sampled exactly \(h\) hops away from the starting set. (The hop-\(h\) neighborhood contains the input vertices for the \(\ell\)-th GNN layer, \(\ell=L-h\).) A vertex \(u\) is _not_ sampled at hop \(h\) only if, for each of its neighbors \(v\in\mathcal{N}_{1}(u)\), either \(v\) was not sampled at hop \(h-1\) or \(v\) was sampled but did not pick \(u\) among its neighbors. The following Proposition shows how to propagate the initial-set probabilities through the graph to compute the VIP values. We give a proof in Appendix C. **Proposition 1** (Vertex inclusion probabilities in minibatch neighborhood expansion with node-wise sampling).: _The probability that vertex \(u\in\mathcal{V}\) appears in the node-wise sampled \(L\)-hop expanded neighborhood of any minibatch is_ \[p(u)=1-\prod_{h=1}^{L}\big{(}1-p^{[h]}(u)\big{)}, \tag{2}\] \[p^{[h]}(u)=1-\prod_{v\in\mathcal{N}_{1}(u)}\big{(}1-t_{h}(u,v)\, p^{[h-1]}(v)\big{)}, \tag{3}\] _where \(p^{[0]}(v)\) is the probability that \(v\) is in the minibatch and \(t_{h}(u,v)\) is the transition probability that \(v\) samples \(u\) as a neighbor at hop \(h=1,\ldots,L\)._ The VIP model of Proposition 1 applies to any initial sampling and hop-wise transition probability function for node-wise sampling. For example, if minibatches and vertex-wise neighbors are sampled uniformly at random without replacement as in GraphSAGE, then we have: \(p^{[0]}(u)=B/|\mathcal{T}|\) if \(u\in\mathcal{T}\) and \(0\) otherwise, where \(B\) is the minibatch size and \(\mathcal{T}\) is the set of training vertices; and \(t_{h}(u,v)=\min\{1,f_{h}/d(v)\}\) if \(u\in\mathcal{N}_{1}(v)\) and \(0\) otherwise, where \(d(v)\) is the (outgoing) degree of \(v\). Non-uniform neighbor sampling models are accommodated via the corresponding transition probability matrix or matrices. The neighborhood expansion random process parametrizes a continuum between a random walk and full neighborhood expansion. If the initial set size and layer-wise fanouts are equal to 1, it becomes a random walk. If the fanouts are greater than the max in-degree of graph vertices, it becomes a full neighborhood expansion. The VIP model for the above two special cases is linear, while the generalized model in Proposition 1 is nonlinear; nonetheless, these models all have the same computational complexity: \(O(L(M+N))\). ### Vertex feature caching We now show how to embody VIP analysis into a caching policy for minimizing communication among distributed machines and host-to-device data transfers in each machine. Communication reductionWe consider the optimal static caching policy, in the maximum-likelihood sense, for reducing inter-partition communication volume in distributed GNNs. The policy is straightforward: each machine extends its local vertex feature storage with copies of the remote features that are most likely to be accessed by the machine, thereby minimizing the total expected communication volume. For some given initial partitioning -- and making no assumptions about the order in which minibatch and neighboring vertices are sampled -- this policy is directly related to the VIP analysis. Specifically, we calculate partition-wise VIP values \(p_{k}(u)\) from the corresponding initial probabilities \(p_{k}^{[0]}(u)\). The cache contents for the \(k\)-th partition are then determined by ranking the remote vertices in order of decreasing \(p_{k}(u)\). We measure the size of a remote-feature cache by its corresponding _replication factor_\(\alpha\). The replication factor is defined such that the number of cached feature vectors stored in each machine is \(\alpha N/K\), where \(K\) is the number of partitions or machines. That is, the fraction of cached to local vertices for each partition is \(\alpha\), and each feature vector is stored in \((1+\alpha)\) machines on average. We may say that a partition or cache replicates a remote vertex to mean that it copies the corresponding vertex feature data. Figure 2 compares a number of static feature-caching policies and provides evidence that the analytical VIP model of Proposition 1 effectively yields the optimal policy. The specific policies being compared are as follows: "deg." ranks vertices by degree, after filtering out remote vertices that are not reachable from a partition's training set (Lin et al., 2020); "1-hop" replicates the entire 1-hop halo of each partition; "wPR" ranks vertices by their score after 5 iterations of a weighted reverse-PageRank model (Min et al., 2021) with damping factor 0.85; "#paths" ranks vertices by the number of paths with length \(\leq L\) that reach them from any local training vertex; "sim." ranks vertices by empirical VIP estimates, measured by counting vertex-wise frequencies of access over 2 simulated training epochs (Yang et al., 2022); "VIP" ranks vertices by VIP values as per Proposition 1; and "oracle" retroactively ranks vertices by their actual access frequencies after training, providing a lower bound on communication volume.1 We make the following observations. Footnote 1: With all caching policies, we calculate vertex rankings with respect to each partition. This is different from the original setting in which some of these policies were introduced, where vertices are cached based on a single, global ranking score. * _Optimality._ The analytical VIP policy yields near-optimal communication volume (within 5% of "oracle") across fanouts and replication factors. The bigger gap (\(\sim\)30%) for \(f=(5,5,5)\) and \(\alpha=1.0\) is due to variance in the accesses of lower-ranked vertices; the gap narrows with more samples (e.g., bigger fanouts or more epochs). * _Communication reduction efficacy._ VIP-driven caching is highly effective for reducing communication volume. Compared to no caching, the VIP policy achieves a geometric-mean reduction of \(2.2\times\)-\(5.3\times\) with small replication factors \(\alpha\in[0.05,0.20]\) and more than \(10\times\) with replication factors over \(0.50\). Compared to the other caching policies, it achieves consistently lower communication volume and its relative improvement increases with the replication factor. * _Local information is not sufficient._ The high-degree and 1-hop halo policies, which do not take neighborhood expansion into account, offer only marginal improvements over no caching. Caching multi-hop neighbors will reduce communication further (Lin et al., 2020) but it will also blow up the replication factor. * _Impact of tailoring the model to the expansion process._ The VIP-driven policy is up to \(4\times\) and \(2\times\) more effective than the "wPR" and "#paths" policies, respectively. Both of these policies take graph-structural expansion into account, but "wPR" is agnostic to the GNN fanout and number of layers, while "#paths" does not directly account for sampling. * _Benefits and limitations of empirical estimation._ The empirical and analytical VIP estimates ("sim." and "VIP" policy, respectively) yield comparable results for low replication factors and high fanouts, but the empirical estimates become less effective as the replication factor increases or the fanouts decrease. For replication factors \(0.50\) and \(1.0\), the relative aggregate improvement of the analytical over the empirical policy is \(1.6\times\) and \(3.2\times\), respectively. The empirical approach has the benefit that it can be used for any sampling scheme, but it also requires increasingly many samples to accurately estimate VIP values for infrequently accessed vertices. Host-to-device data transfer reductionVIP analysis can also be used to reduce the volume of host-to-device data transfers for local features on each machine. For example, assume that each GPU can retain a fraction of the local feature data in memory throughout the GNN computations (i.e., across all minibatches). We may rank the local vertices in the \(k\)-th partition by \(p_{k}(u)\) and keep the highest-ranking-vertex features on the GPU. As with remote-vertex caching, this policy minimizes the expected data transfer volume due to local vertices in each partition. Figure 2: Comparison of caching policies with respect to remote feature communication volume. GNN: 3-layer GraphSAGE, varying fanouts \(f\), minibatch size 1024. Data set: ogbn-papers100M (undirected). Partition: 8-way METIS with edge-cut objective plus edge and training/validation/test vertex balancing. **(a)**–**(c)** Average per-epoch communication in number of vertices over 100 epochs (log-scale). Lower is better. The feasible region between the communication upper bound (no caching) and lower bound (oracle caching) is shaded gray. **(d)** Geometric-mean improvement across fanouts, relative to no caching (log-scale). Higher is better. ## 4 SalIENT++: Fast and Scalable Distributed GNN training via Caching and Pipelining This section describes the design of SALIENT++, a fast and scalable system for performing distributed minibatch training of GNNs on large partitioned datasets. The design of SALIENT++ is comprised of three majors components: **Vertex reordering**: A vertex ordering based on the graph partitions and VIP values that facilitates efficient sub-partitioning of local feature data between CPU and GPU to reduce host-to-device data transfers. **Data replication**: An economical data replication strategy that uses VIP analysis to reduce communication volume for fetching remote features while using only a small amount of additional memory. **Pipelined communication**: A pipelined distributed minibatch preparation system that hides latencies due to sampling, data transfers, and inter-machine communication of remote feature data. These three techniques together enable SALIENT++ to perform GNN training on partitioned data-graphs while matching the efficiency of highly optimized GNN training systems that perform distributed computations with full replication of vertex feature data across all machines. This enables SALIENT++ to perform GNN training efficiently on large datasets where full replication is impractical. As we shall discuss in our empirical evaluation in Section 5, SALIENT++ achieves high performance for GNN training on large datasets even when operating in clusters with only modest hardware configurations. ### Partitioning and reordering of vertex features Let us describe how SALIENT++ partitions the vertex features of a graph to reduce inter-machine and host-to-device communication. SALIENT++ employs a two-level strategy for distributing the vertex features across machines and devices, as illustrated in Figure 3. The top level involves distributing vertex features based on a vertex partitioning of the graph, and the bottom level involves dividing each partition's local vertex features between GPU and CPU memory. SALIENT++ operates on graph data sets that are partitioned using a graph partitioning algorithm such as METIS (Karypis and Kumar, 1997). The graph partitions are generated such that the training, validation, and test vertices are balanced. As a heuristic to balance work-per-partition, an additional criterion is used to balance the amount of edges per partition. Each machine is assigned a subset of training/validation/test vertices and stores vertex feature data locally according to the machine's partition. The graph is reordered such that: (a) indices for vertices in the same partition are contiguous; and (b) vertices within a partition are ordered based on how beneficial it is for them to be stored on the GPU. Each machine stores a prefix of its ordered list of vertex features on the GPU, which when using VIP ordering corresponds to those vertices that are accessed most frequently by the local machine. This partitioning structure facilitates efficient determination of whether a vertex is remote or local, where a local vertex is stored on the machine, and index calculations using only a constant amount of additional memory. Figure 3 provides a graphical illustration of the VIP-reordered partitioned dataset. ### Replication of remote vertex features Each machine maintains a replica or static cache of features for vertices in remote partitions, where the size of the cache is determined by a given replication factor \(\alpha\). The vertices whose features are cached in each machine are determined by their VIP rank to reduce network communication, as described in Section 3.2. Once the neighborhood sampling code prepares a batch, SALIENT++ partitions the vertices in the expanded neighborhood into local and remote vertices. Among the subset of remote vertices, an efficient lookup is performed using a hash table to determine whether the features for a remote vertex can be found in the local machine's cache. Only remote vertices that are not resident in the local cache proceed to be requested from remote machines. ### Minibatch preparation pipeline SALIENT++ implements a deep multi-stage pipeline which enables overlap between neighborhood sampling, host-to-device data transfers, network communication between machines, and training computation. SALIENT++'s pipeline is more complex than the one used in SALIENT (Kaler et al., 2022), but it maintains the latter's usability and efficiency. SALIENT++'s pipeline can be used in place of standard data loaders for GNNs by changing just a few lines of code. **Sampling and slicing** SALIENT++ uses a modified version of SALIENT's optimized neighborhood sampling and slicing code to prepare minibatches using shared-memory Figure 3: Illustration of the partitioned data set with VIP-driven local ordering and caching of remote features across machines. parallelism. The original SALIENT batch-preparation code fused the neighborhood sampling and feature tensor slicing operations. In SALIENT++, these tensor-slicing operations are only performed on the subset of the vertices in the sampled neighborhood that are stored locally in the CPU memory of each machine. For the remaining vertices in the sampled neighborhood, SALIENT++ distinguishes between vertices in the following categories: vertices belonging to the local partition whose features are stored on GPU; remote vertices that are replicated on the local machine; and remote vertices that belong to other partitions. **Feature collection pipeline** We briefly summarize the pipeline operations. The expanded neighborhood of each minibatch may include remote vertices, remote vertices whose features were cached on the local machine following VIP analysis, and local vertices which are split across CPU and GPU storage. Immediately following sampling, vertices are categorized by their storage location so that vertex features are properly retrieved. Communication rounds interspersed with host-to-device and device-to-host transfers are enqueued with remote machines to coordinate retrieval of remote features. Replicated and local features partitioned across CPU and GPU storage are sliced locally. Finally, all features are concatenated into a single tensor and reordered for compatability with the message-flow graph generated during neighborhood sampling. A total of \(10\) mini-batches can be "in-flight" in the SALIENT++ pipeline at any time, each mini-batch being processed by a separate stage of the pipeline. Pipelining enables overlap between host-to-device data transfers and network communication, and it also allows for hiding latencies related to CPU-GPU data transfers and inter-machine communication. A more detailed stage-by-stage description of SALIENT++'s pipeline is provided in Appendix D. ## 5 Evaluation In this section, we evaluate the performance of SALIENT++ and investigate the impact of its optimizations relating to pipelining and use of VIP analysis (as developed in Section 3). Additionally, we report end-to-end performance results, model accuracies, and contextualize our performance in relation to existing distributed GNN training systems. ### Experimental setup **Computing environment** Our experiments were run on a cluster consisting of 16 machines, each equipped with a 16-core (2-way hyperthreaded) AMD CPU with 128GB DRAM and 1 NVIDIA A10G GPU with 24GB memory. The cluster was configured using the Amazon Web Services (AWS) ParallelCluster software and employed fleets of AWS _g5.8xlarge_ instances. The network SLA specified for this instance type is 25Gbps. Distributed communications were implemented via PyTorch's DistributedDataParallel module with the NCCL backend. Since our cluster comprises machines with 1 GPU each, experiments with \(K\) GPUs involve \(K\) separate machines communicating over the network. **Datasets** We evaluate SALIENT++ on three standard benchmark data sets: ogbn-products (_products_), ogbn-papers100M (_papers_) (Hu et al., 2020), and lsc-mag240 (_mag240c_) (Hu et al., 2021). The graph and training set in these data sets vary in size, with _papers_ and _mag240c_ being two of the largest open benchmarks at the time of this work. See Table 2 for detailed information. All graphs were made undirected (if originally not), as is common practice. For _mag240c_, we train on the homogeneous papers-to-papers component of the graph. **GNN architectures** We evaluated SALIENT++'s performance using standard GraphSAGE (Hamilton et al., 2017) architectures with each data set's most commonly used hyperparameters. Table 3 lists the GNN architectures and hyperparameters that were used for each data set. \begin{table} \begin{tabular}{l c c c c} \hline \hline _Data Set_ & _\#Vertices_ & _\#Edges_ & _\#Feat._ & _Train. / Val. / Test_ \\ \hline products & 2.4M & 123M & 100 & 197K / 39K / 2.2M \\ papers & 111M & 3.2B & 128 & 1.2M / 125K / 214K \\ mag240c & 121M & 2.6B & 768 & 1.1M / 134K / 88K \\ \hline \hline \end{tabular} \end{table} Table 2: Summary of data sets. Edge counts reflect the number of edges in the graph after standard preprocessing (e.g., making the graph undirected). The _mag240c_ data set is the papers-to-papers citation subgraph of the _lsc-mag240_ heterogeneous graph data set. Figure 4: Impact of pipelining and VIP optimizations in SALIENT++. Illustrates the performance improvements obtained by successively more optimized versions of SALIENT++ for _products_ (4 partitions), _papers_ (8 partitions), and _mag240c_ (16 partitions). The GNN architectures for each benchmark are listed in Table 3. The replication factors for VIP-based caching were \(0.16\), \(0.32\), and \(0.32\) for _products_, _papers_, and _mag240c_, respectively. \begin{table} \begin{tabular}{l c c c c c} \hline \hline _Data Set_ & _GNN_ & _\#Layers_ & _Hidden Dim._ & _Fanout_ & _Batch_ \\ \hline products & SAGE & 3 & 256 & (15, 10, 5) & 1024 \\ papers & SAGE & 3 & 256 & (15, 10, 5) & 1024 \\ mag240c & SAGE & 2 & 1024 & (25, 15) & 1024 \\ \hline \hline \end{tabular} \end{table} Table 3: GNN architecture hyperparameters for all experiments in Section 5. Fanout is for training. Batch size is per GPU. ### Performance analysis of SALIENT++ We analyze the performance of SALIENT++ by investigating the impact of its component optimizations, and measuring end-to-end performance and scalability across three large graph data sets. **Summary of performance improvements** Figure 4 summarizes how SALIENT++'s optimizations result in increasingly better end-to-end training performance on _products_, _papers_, and _mag240c_ in the distributed setting. Significant improvements are observed for both the _papers_ and _mag240c_ benchmarks. In relative terms, the _papers_ benchmark benefits equally from pipelining and VIP-based caching, while the _mag240c_ benchmark benefits slightly more from caching on top of pipelining. This is mainly due to the larger feature dimensionality for _mag240c_, which causes the communication of remote feature data to be relatively more throughput-bound than for _papers_. **Scalability** Figure 5 (left plot) illustrates the reduction in per-epoch runtime when using SALIENT++ to execute the _products_, _papers_, and _mag240c_ benchmarks on \(2\)-\(16\) GPUs. For all three benchmarks, the reported runtimes include warm-up time to fill up the pipeline at the start of each training epoch, which results in diminished scalability once per-epoch runtimes become less than a second. The _products_ benchmark achieves \(1.7\times\) speedup when going from \(2\) to \(4\) GPUs, but does not significantly benefit from more scaling. The _papers_ benchmark achieves \(1.9\times\) speedup from \(2\) to \(4\) GPUs and another \(1.9\times\) from \(4\) to \(8\) GPUs. The _mag240c_ benchmark achieves \(1.75\times\) speedup going from \(4\) to \(8\) GPUs, and \(1.45\times\) speedup from \(8\) to \(16\) GPUs. SALIENT++'s performance matches that of prior fast systems which perform distributed GNN training with full replication (Kaler et al., 2022), while SALIENT++ uses substantially less memory. Figure 5 (right plot) shows the total memory for storing vertex feature data (including replicated vertices) across all machines. Note that full replication with \(K\) machines corresponds to replication factor \(\alpha=K-1\). **Local partition storage on CPU versus GPU** Figure 6 illustrates the performance impact of increasing the percentage of the local partition stored on GPU while running the _papers_ benchmark. Given an ordering of the vertices in the local partition and a percentage \(\beta\%\) of local data to store on GPU, SALIENT++ stores the first \(\beta\%\) of vertex features on the GPU. The results labeled "no reorder" show an essentially linear reduction in per-epoch runtime as a function of \(\beta\%\) when ranking local vertices by their initial ordering. The results labeled "VIP reorder," on the other hand, show that when ranking local vertices by their VIP values, data transfer bottlenecks are effectively eliminated with as little as \(10\%\) of the local partition data on the GPU. **Impact of replication factor** Figure 7 illustrates the impact on per-epoch runtime of increasing the number of replicated vertex features for _papers_ on 4 and 8 partitions (left) and on _mag240c_ for 8 and 16 partitions (right). Figure 7 shows that modest replication factors of \(0.08\)-\(0.16\) and \(0.16\)-\(0.32\) are sufficient for minimizing per-epoch runtime when using \(4\) and \(8\) partitions respectively on the _papers_ dataset. **Performance breakdown for SALIENT++** Figure 8 illustrates the performance bottlenecks in SALIENT++ before and after incorporating pipelining and caching via VIP analysis.2 A comparison of the "pipelining on" and "pipelining Figure 5: Scalability and total memory used by all machines for _products_, _papers_, and _mag240c_. Total memory is plotted as a multiple of the unreplicated data set size \(1+\alpha\) where \(\alpha\) is the replication factor used for the \(K\)-GPU execution. Figure 6: Impact of VIP-based local vertex ordering on per-epoch runtime. Experiment run on \(4\) GPUs with the _papers_ dataset and replication factor \(\alpha=0.15\). Reported numbers are the mean over 10 epochs and vertical lines show the standard deviation. Figure 7: Replication factor impact on per-epoch runtime. Results are shown for _papers_ (left) for \(4\) and \(8\) partitions, and for _mag240c_ for \(8\) and \(16\) partitions for replication factors \(\alpha\) varied between \(0\) and \(0.32\). The percentage of the local partition stored on GPU for this experiment was \(90\%\) for _papers_ and \(10\%\) for _mag240c_. Reported numbers are the mean value over 10 epochs and vertical bars indicate the standard deviation across epoch runtimes. off" breakdowns for \(\alpha=0\) illustrates that network communication is the primary bottleneck for distributed GNN training, and it remains the bottleneck even when communication is pipelined to overlap with computation. When using caching with \(\alpha=0.32\), the time spent performing communication is sufficiently small so that it can be overlapped nearly perfectly with other computation in the program. Performance on a slow networkFigure 9 illustrates the performance of SALIENT++ on a slow network where higher replication factors are needed to alleviate communication bottlenecks. The slower network speeds were enforced using the Linux traffic control subsystem with the token-bucket filter (TBF) queuing discipline (Hubert et al., 2002). In this setting, we compare the two best caching policies from Section 3, VIP (analytic) and VIP (simulation). Recall from Section 3 that these two policies tend to perform very similarly for low replication factors, but diverge as the replication factor grows. On the _papers_ dataset, the relative gap between these two policies grows up to \(30\%\) until \(\alpha=0.64\) and then starts to shrink once communication ceases to bottleneck training time. For the _mag240c_ dataset, which uses node features that are \(6\times\) larger than _papers_, the relative gap between VIP (analytic) and VIP (simulation) is larger (up to \(45\%\) with \(\alpha=0.48\)) and persistent. Whether or not VIP (analytic) is preferred to VIP (simulation) depends on the workload characteristics (e.g., fanout and size of node features) as well as the network bandwidth budget. ### Context for SALIENT++'s performance To conclude our empirical evaluation, we contextualize SALIENT++'s performance by reporting model accuracy results, discussing preprocessing overheads, and comparing our performance to existing systems. Model accuracyThe optimizations in SALIENT++ do not impact model accuracy. SALIENT++ is integrates with PyTorch Geometric (PyG) and can use existing GNN models implemented with PyG. Regardless, we report accuracies for _products_, _papers_ and _mag240c_ so that one can contextualize the performance numbers. For computing accuracies, we executed SALIENT++ on \(8\) machines for \(30\) epochs with a fixed learning rate of \(0.001\) and a batch size of \(1024\) per machine.3 Sampling was used during inference with fanouts \((20,20,20)\) for _papers_ and _products_, and \((25,15)\) for _mag240c_. On _products_, we observed a test accuracy of \(0.785\) for the \(3\)-layer SAGE architecture. On _papers_, we observed a test accuracy of \(0.646\) for the \(3\)-layer SAGE architecture. On _mag240c_, the 2-layer GraphSAGE architecture achieves an accuracy of \(0.651\).4 Footnote 3: These hyperparameters were not tuned for accuracy, but are known to be reasonable values. Footnote 4: Validation accuracy is reported instead of “test-dev” or “test-challenge” accuracy, which we did not measure at the time of different replication factors. Figure 8: Performance breakdown for SALIENT++ (with added synchronization) for an \(8\)-GPU execution of _papers_ with all local node features on GPU. The “pipelining off” breakdown is best able to isolate the time spent performing each operation. The “pipelining on” breakdown adds minimal synchronization to isolate distributed batch preparation from training computation. _Batch Prep (Comm)_ and _Batch Prep (Comp)_ are the time for communication and computation, respectively, in distributed batch preparation. These categories are combined into _Batch Prep_ for the “pipelining on” breakdown. _Startup_ is the time to prepare the first batch and/or fill the pipeline. _Train (sync)_ is the time for parallel workers to synchronize at the first collective operation of the training backward pass. _Train_ measures GPU computation for training. Figure 9: Comparison of VIP-analytic versus VIP-simulation on end-to-end runtime on slow networks. Illustrates the per-epoch runtime of \(16\)-node executions on _papers_ and _mag240c_ when using the VIP-analytic and VIP-simulation caching policies with different replication factors. Preprocessing overheadsSALIENT++'s preprocessing overheads fall into two categories: (a) runtime overheads incurred before each execution on a dataset; and, (b) dataset preparation overheads that are incurred only once and can be amortized over multiple experiments. The runtime overheads for an \(8\)-node execution of SALIENT++ on the _papers_ dataset with replication factor \(\alpha=0.32\) are as follows. Loading the dataset from disk takes approximately \(10\) seconds. Computing the VIP weights for fanouts \((15,10,5)\) takes \(11.8\) seconds when implemented in PyTorch with sparse transition weight matrices and dense hop-wise VIP-vectors. For large graphs, the VIP computation code streams batches of matrix rows to the GPU, overlapping communication and data transfer. The communication of remote feature vectors and the related tensor slicing operations take about \(22\) seconds. The dataset preprocessing overheads are highly dependent on the workflow used for partitioning graphs. Our (unoptimized) workflow for graph partitioning uses serial METIS to partition graphs and, additionally, uses machines with limited memory necessitating the use of swap files. In this setting, partitioning the _papers_ dataset takes \(\sim\!2\) hours and creating a reordered dataset from that partition takes \(30\) minutes. Optimized workflows for partitioning can generate partitions substantially faster. For example, DistDGLv2 (Zheng et al., 2022) reports a \(12\) minute runtime for partitioning when using ParMETIS (Karypis et al., 1998) and \(4\) large multicores. SALIENT++ is agnostic to the source of the graph partitioning, and can be used in conjunction with more scalable graph partitioning codes. Comparison to DistDGLWe compared the performance of SALIENT++ to DistDGL on _papers_ using the GraphSAGE architecture. A summary of this comparison is provided in Table 4. The DistDGL code was obtained from DGL's public GitHub repository and executed in the same computing environment used to evaluate SALIENT++. DistDGL's public code for distributed multi-GPU training was approximately 12.7\(\times\) slower than SALIENT++ on \(8\) GPUs (1 GPU per machine). Of course, DGL is under active development and its support for efficient GNN training (especially in distributed environments) is evolving rapidly. As such, we also report performance results from the recent work "DistDGLv2" (Zheng et al., 2022) that describes innovations in the DistDGL system for improving distributed GNN training performance. Although not all of these innovations are publicly available, their reported performance can be used to contextualize the performance we achieve with SALIENT++. A full comparison of the hardware used by DistDGLv2 and SALIENT++ shows that SALIENT++ consistently achieves similar (often better) performance than what was reported for DistDGLv2, while using substantially less resources. SALIENT++'s \(8\)-GPU runtime is approximately \(1.7\times\) faster than DistDGLv2's reported numbers for executing a training epoch on _papers_ using \(64\) GPUs. This faster per-epoch time is achieved with \(8\times\) fewer GPUs, \(4\times\) smaller network bandwidth, and \(3.2\times\) cheaper hardware. ## 6 Conclusions and Future Work We have presented a distributed multi-GPU system, SALIENT++, for GNN training and inference on massive graphs. This system is built on top of SALIENT, a prior state-of-the-art system that attains efficiency and scalability through fast sampling and pipelining, at the cost of full data replication on all machines. In SALIENT++, we distribute the vertex feature data and address the resulting communication bottleneck through analyzing the access pattern of the out-of-machine (i.e., remote) vertices and proposing a caching strategy that replicates a small amount of the most frequently accessed vertex features. Together with a deep pipelining of all operations from communication to computation, SALIENT++ retains the efficiency and scalability of SALIENT while consuming only a fraction of the storage required by SALIENT. An avenue of future work is to further apply the access pattern analysis to improve the initial graph partitioning, with an aim of reducing the communication volume orthogonally to the use of caching. This would require incorporating the vertex inclusion probabilities in the graph partitioning objective, on top of edge cuts and load balancing. Additionally, a hierarchical graph partitioning may better leverage the higher intra-machine bandwidth among GPUs than inter-machine communication. Another line of future work is to explore distributing the graph structure across machines. Distributing the graph incurs nontrivial challenges in the multi-round communication of node features, but resolving this challenge will further reduce memory consumption and bears the potential of handling graphs that are orders of magnitudes larger than the current largest benchmarks. \begin{table} \begin{tabular}{l l l} \hline \hline _System_ & _Time (s)_ & _Notes_ \\ \hline SALIENT++ & 2.9 & 8 NVIDIA AI0G GPUs, 25Gbps network throughput, 519.5 / hr. \\ DistDGL & 37.0 & Same hardware as is used by SALIENT++. Example distributed code from Github3 \\ DistDGLv2 & \(\approx 5\) & 64 NVIDIA T4 GPUs, 100Gbps network throughput, 862.6 / hr. \\ \hline \hline \end{tabular} \end{table} Table 4: Comparison of SALIENT++, DistDGL (public code), and DistDGLv2 (Zheng et al., 2022). All numbers are reported for a \(3\)-layer GraphSAGE architecture with fanouts 15,10,5 and \(256\) hidden nodes run on the _papers_ dataset. ## Acknowledgements This work was conducted on the SuperCloud computing cluster [https://supercloud.mit.edu](https://supercloud.mit.edu) and the Satori computing cluster [https://mit-satori.github.io](https://mit-satori.github.io). This research was sponsored by MIT-IBM Watson AI Lab and in part by the United States Air Force Research Laboratory and the United States Air Force Artificial Intelligence Accelerator and was accomplished under Cooperative Agreement Number FA8750-19-2-1000. The views and conclusions contained in this document are those of the authors and should not be interpreted as representing the official policies, either expressed or implied, of the United States Air Force or the U.S. Government. The U.S. Government is authorized to reproduce and distribute reprints for Government purposes notwithstanding any copyright notation herein.
2307.00222
Re-Think and Re-Design Graph Neural Networks in Spaces of Continuous Graph Diffusion Functionals
Graph neural networks (GNNs) are widely used in domains like social networks and biological systems. However, the locality assumption of GNNs, which limits information exchange to neighboring nodes, hampers their ability to capture long-range dependencies and global patterns in graphs. To address this, we propose a new inductive bias based on variational analysis, drawing inspiration from the Brachistochrone problem. Our framework establishes a mapping between discrete GNN models and continuous diffusion functionals. This enables the design of application-specific objective functions in the continuous domain and the construction of discrete deep models with mathematical guarantees. To tackle over-smoothing in GNNs, we analyze the existing layer-by-layer graph embedding models and identify that they are equivalent to l2-norm integral functionals of graph gradients, which cause over-smoothing. Similar to edge-preserving filters in image denoising, we introduce total variation (TV) to align the graph diffusion pattern with global community topologies. Additionally, we devise a selective mechanism to address the trade-off between model depth and over-smoothing, which can be easily integrated into existing GNNs. Furthermore, we propose a novel generative adversarial network (GAN) that predicts spreading flows in graphs through a neural transport equation. To mitigate vanishing flows, we customize the objective function to minimize transportation within each community while maximizing inter-community flows. Our GNN models achieve state-of-the-art (SOTA) performance on popular graph learning benchmarks such as Cora, Citeseer, and Pubmed.
Tingting Dan, Jiaqi Ding, Ziquan Wei, Shahar Z Kovalsky, Minjeong Kim, Won Hwa Kim, Guorong Wu
2023-07-01T04:44:43Z
http://arxiv.org/abs/2307.00222v1
# Re-Think and Re-Design Graph Neural Networks in Spaces of Continuous Graph Diffusion Functionals ###### Abstract Graphs are ubiquitous in various domains, such as social networks and biological systems. Despite the great successes of graph neural networks (GNNs) in modeling and analyzing complex graph data, the inductive bias of locality assumption, which involves exchanging information only within neighboring connected nodes, restricts GNNs in capturing long-range dependencies and global patterns in graphs. Inspired by the classic _Brachistochrone_ problem, we seek how to devise a new inductive bias for cutting-edge graph application and present a general framework through the lens of variational analysis. The backbone of our framework is a two-way mapping between the discrete GNN model and continuous diffusion functional, which allows us to design application-specific objective function in the continuous domain and engineer discrete deep model with mathematical guarantees. _First_, we address over-smoothing in current GNNs. Specifically, our inference reveals that the existing layer-by-layer models of graph embedding learning are equivalent to a \(\ell_{2}\)-norm integral functional of graph gradients, which is the underlying cause of the over-smoothing problem. Similar to edge-preserving filters in image denoising, we introduce the total variation (TV) to promote alignment of the graph diffusion pattern with the global information present in community topologies. On top of this, we devise a new selective mechanism for inductive bias that can be easily integrated into existing GNNs and effectively address the trade-off between model depth and over-smoothing. _Second_, we devise a novel generative adversarial network (GAN) to predict the spreading flows in the graph through a neural transport equation. To avoid the potential issue of vanishing flows, we tailor the objective function to minimize the transportation within each community while maximizing the inter-community flows. Our new GNN models achieve state-of-the-art (SOTA) performance on graph learning benchmarks such as _Cora_, _Citeseer_, and _Pubmed_. ## 1 Introduction Graph is a fundamental data structure that arises in various domains, including social network analysis [48], natural language processing [42], computer vision [34], recommender systems [43], and knowledge graphs [25] among others. Tremendous efforts have been made to operate machine learning on graph data (called graph neural networks, or GNNs) at the node [27], link [47], and graph level [31]. The common inductive bias used in GNNs is the homophily assumption that nodes that are connected in a graph are more likely to have similar features or labels. In this context, most GNN models deploy a collection of fully-connected layers to progressively learn graph embeddings by aggregating the nodal feature representations from its topologically-connected neighbors throughout the graph [21]. Under the hood of GNNs, the graph representation learning process is achieved by various learnable operations, such as message passing [5] or graph convolution [27]. Due to the nature of exchanging information in a local graph neighborhood, however, it is challenging to capture global graph representations, which go beyond node-to-node relationship, by leveraging the deep architecture in GNNs while being free of overly smoothing the feature representations for the closely-connected nodes. Fig. 1 demonstrates the root cause of over-smoothing issue in current GNNs, where node color denotes the group label (no color means unlabeled) and edge thickness indicates connection strength. It is clear that nodes #1 and #2 are located at the boundary of two communities. The inductive bias of GNNs (i.e., locality assumption) enforces the node embedding vectors on node #1 and #2 becoming similar due to being strongly connected (highlighted in red), even though the insight of global topology suggests that their node embeddings should be distinct. As additional layers are added to GNNs, the node embeddings become capable of capturing global feature representations that underlie the entire graph topology. However, this comes at the cost of over-smoothing node embeddings across graph nodes due to (1) an increased number of node-to-node information exchanges, and (2) a greater degree of common topology within larger graph neighborhoods. In this regard, current GNNs only deploy a few layers (typically two or three) [30], which might be insufficient to characterize the complex feature representations on the graph. It is evident that mitigating the over-smoothing problem in GNNs will enable training deeper models. From a network architecture perspective, skip connections [18; 45], residual connections [29; 20], and graph attention mechanisms [39; 37] have been proposed to alleviate the information loss in GNNs, by either preserving the local feature representation or making information exchange adaptive to the importance of nodes in the graph. Although these techniques are effective to patch the over-smoothing issue in some applications, the lack of an in-depth understanding of the root cause of the problem poses the challenge of finding a generalized solution that can be scaled up to current graph learning applications. Inspired by the success of neural ordinary differential equations in computer vision [10], research focus has recently shifted to link the discrete model in GNNs with partial differential equation (PDE) based numerical recipes [44; 33; 6; 15]. For example, Graph Neural Diffusion (GRAND) formulates GNNs as a continuous diffusion process [6]. In their framework, the layer structure of GNNs corresponds to a specific discretization choice of temporal operators. Since PDE-based model does not revolutionize the underlying inductive bias in current GNNs, it is still unable to prevent the excessive information change between adjacent nodes as in nodes #1 and #2 in Fig. 1. In this regard, using more advanced PDE solvers only can provide marginal improvements in terms of numerical stability over the corresponding discrete GNN models, while the additional computational cost, even in the feed-forward scenario, could limit the practical applicability of PDE-based methods for large-scale graph learning tasks. In this regard, pioneering work on continuous approaches has prompted to re-think GNN as a graph diffusion process governed by the Euler-Lagrange (E-L) equation of the heat kernel. This formulation is reminiscent of the _Brachistochrone_ problem 1, which emerged over 400 years ago and established the mathematical framework of classical mechanics. The powerful calculus of variations allows us to generate solutions for various mechanics questions (e.g., the slope that yields the fastest ball sliding down the curve is given by a cycloid) through the lens of E-L equation, as shown in Fig. 2 (top). Figure 1: Demonstration of the root cause of over-smoothing in GNNs. Nodes #1 and #2 are located along the boundary of two communities. The locality assumption in GNNs steers the learning of the graph representations by constraining the information exchange via node-to-node connections. However, such link-wise inductive bias opts to neutralize the contrast of node embeddings between nodes #1 and #2, which might undermine the node classification accuracy. Our research framework yields the solution for the over-smoothing issue by enabling heat-kernel diffusion within each community while penalizing the excessive community-to-community information exchanges (highlighted in red). In a similar vein, the question that arises in the context of community detection is: What graph diffusion pattern is best suited for preserving community organizations? The question for graph classification would be: What graph diffusion pattern works best for capturing the system-level characteristics of graph topology? Following the spirit of _Brachistochrone_ problem, we present a general research framework to customize application-specific GNNs in a continuous space of graph diffusion functionals. As shown in Fig. 2 (bottom), we have established a fundamental structure for our framework that involves a two-way mapping between a discrete GNN model and a continuous graph diffusion functional. This allows us to develop application-specific objective functions (with an explainable regularization term) in the continuous domain and construct a discrete deep model with mathematical guarantee. We demonstrate two novel GNN models, one for addressing over-smoothing and one for predicting the flows from longitudinal nodal features, both achieving state-of-the-art performance (_Cora_: 85.6%, _Citeseer_: 73.9%, _Pubmed_: 80.10%, even in 128 network layers). We have made four major contributions. (1) We establish a connection between the discrete model of GNNs and the continuous functional of inductive bias in graph learning by using the E-L equation as a stepping stone to bridge the discrete and continuous domains. (2) We introduce a general framework to re-think and re-design new GNNs that is less "black-box". (3) We devise a novel selective mechanism upon inductive bias to address the over-smoothing issue in current GNNs and achieve state-of-the-art performance on graph learning benchmarks. (4) We construct a novel GNN in the form of a generative adversarial network (GAN) to predict the flow dynamics in the graph by a neural transport equation. ## 2 Methods In the following, we first elucidate the relationship between GNN, PDE, and calculus of variations (COV), which sets the stage for the _GNN-PDE-COV_ framework for new GNN models in Section 2.2. Re-think GNNs: Connecting dots across graph neural networks, graph diffusion process, Euler-Lagrange equation, and Lagrangian mechanics **Graph diffusion process.** Given graph data \(\mathcal{G}=(V,W)\) with \(N\) nodes \(V=\left\{v_{i}|i=1,\ldots,N\right\}\), the adjacency matrix \(W=\left[w_{ij}\right]_{i,j=1}^{N}\in\mathbb{R}^{N\times N}\) describes connectivity strength between any two nodes. For each node \(v_{i}\), we have a graph embedding vector \(x_{i}\in\mathcal{R}^{m}\). In the context of graph topology, the graph gradient \(\left(\nabla_{\mathcal{G}}x\right)_{ij}=w_{ij}\left(x_{i}-x_{j}\right)\) indicates the feature difference between \(v_{i}\) and \(v_{j}\) weighted by the connectivity strength \(w_{ij}\), where \(\nabla_{\mathcal{G}}\) is a \(\mathbb{R}^{N}\rightarrow\mathbb{R}^{N\times N}\) operator. Thus, the graph diffusion process can be formulated as \(\frac{\partial x(t)}{\partial t}=div\left(\nabla_{\mathcal{G}}x(t)\right)\), where the evolution of embedding vectors \(x=\left[x_{i}\right]_{i=1}^{N}\) is steered by the graph divergence operator. **Connecting GNN to graph diffusion.** In the regime of GNN, the regularization in the loss function often measures the smoothness of embeddings \(x\) over the graph by \(x^{T}\Delta x\), where \(\Delta=div(\nabla_{\mathcal{G}})\) is the graph Laplacian operator [27]. To that end, the graph smoothness penalty encourages two connected nodes to have similar embeddings by information exchange in each GNN layer. Specifically, the new graph embedding \(x^{l}\) in the \(l^{th}\) layer is essentially a linear combination of the graph embedding \(x^{l-1}\) in the previous layer, i.e., \(x^{l}=A_{W,\Theta}x^{l-1}\), where the matrix \(A\) depends on graph adjacency matrix Figure 2: Top: The _Brachistochrone_ problem played a pivotal role in the development of classical mechanics and the powerful mathematical tool known as the calculus of variations. Bottom: We introduce a general framework to answer _”Brachistochrone”_ problems regarding diffusion patterns on graphs that allows us to re-think and re-design application-specific deep model of GNNs with enhanced mathematical interpretability. \(W\) and trainable GNN parameter \(\Theta\). After rewriting \(x^{l}=Ax^{l-1}\) into \(x^{l}-x^{l-1}=(A-I)x^{l-1}\), updating graph embeddings \(x\) in GNN falls into a discrete graph diffusion process, where the time parameter \(t\) acts as a continuous analog of the layers in the spirit of Neural ODEs [10]. It has been shown in [6] that running the graph diffusion process for multiple iterations is equivalent to applying a GNN layer multiple times. **GNN is a discrete model of Lagrangian mechanics via E-L equation.** The diffusion process \(\frac{\partial x(t)}{\partial t}=div\left(\nabla_{\mathcal{G}}x(t)\right)\) has been heavily studied in image processing in decades ago, which is the E-L equation of the functional \(\min\limits_{x}\int_{\Omega}|\nabla x|^{2}dx\). By replacing the 1D gradient operator defined in the Euclidean space \(\Omega\) with the graph gradient \(\left(\nabla_{\mathcal{G}}x\right)_{ij}\), it is straightforward to find that the equation governing the graph diffusion process \(\frac{\partial x(t)}{\partial t}=div\left(\nabla_{\mathcal{G}}x(t)\right)\) is the E-L equation of the functional \(\min\limits_{x}\int_{\mathcal{G}}|\nabla_{\mathcal{G}}x|^{2}dx\) over the graph topology. Since the heat kernel diffusion is essentially the mathematical description of the inductive bias in current GNNs, we have established a mapping between the mechanics of GNN models and the functional of graph diffusion patterns in a continuous domain. **Tracing the smoking gun of over-smoothing in GNNs.** In Fig. 1, we observed that the inductive bias of link-wise propagation is the major reason for excessive information exchange, which attributes to the over-smoothing problem in GNNs. An intuitive approach is to align the diffusion process with high-level properties associated with graph topology, such as network communities. After connecting the GNN inductive bias to the functional of graph diffusion process, we postulate that the root cause of over-smoothing is the isotropic regularization mechanism encoded by the \(\ell_{2}\)-norm. More importantly, connecting GNN to the calculus of variations offers a more principled way to design new deep models with mathematics guarantees and model mechanistic explainability. ### Re-design GNNs: Revolutionize inductive bias, derive new E-L equation, and construct deeper GNN The general roadmap for re-designing GNNs typically involves three major steps: (1) formulating inductive bias into the functional of graph diffusion patterns; (2) deriving the corresponding E-L equation; and then (3) developing a new deep model of GNN based on the finite difference solution of E-L equation. Since the graph diffusion functional is application-specific, we demonstrate the construction of new GNN models in the following two graph learning applications. #### 2.2.1 Develop _VERY_ deep GNNs with a selective mechanism for link-adaptive inductive bias **Problem formulation.** Taking the feature learning component (learnable parameters \(\Theta\)) out of GNNs, the graph embeddings \(x^{L}\) (output of an \(L\)-layer GNN) can be regarded as the output of an iterative smoothing process (\(L\) times) underlying the graph topology \(\mathcal{G}\), constrained by the data fidelity \(\left\|x^{L}-x^{0}\right\|_{2}^{2}\) (w.r.t. the initial graph embeddings \(x^{0}\)) and graph smoothness term \(\int_{\mathcal{G}}|\nabla_{\mathcal{G}}x|^{2}dx\). Inspired by the great success of total variation (TV) for preserving edges in image denoising [35], reconstruction [41] and restoration [8], we proposed to address the over-smoothing issue in current GNN by replacing the quadratic Laplacian regularizer with TV on graph gradients, i.e., \(\mathcal{J}_{TV}(x)=\int|\nabla_{\mathcal{G}}x|dx\). Thus, the TV-based objective function for graph diffusion becomes: \(\min\limits_{x}\bigl{(}\left\|x-x^{0}\right\|_{2}^{2}+\mathcal{J}_{TV}(x))\). However, the \(\ell_{1}\)-norm function, denoted by \(|\cdot|\) in the definition of the total variation functional \(\mathcal{J}_{TV}\), is not differentiable at zero. Following the dual-optimization schema [4; 7], we introduce the latent auxiliary matrix \(z\in\mathbb{R}^{N\times N}\) and reformulate the TV-based functional as \(\mathcal{J}_{TV}(x,z)=\max\limits_{z}\min\limits_{x}\int(z\otimes\nabla_{ \mathcal{G}}x)dx\), subject to \(|z|\leq\mathbf{1}^{N\times N}\), where \(\otimes\) is Hadamard operation between two matrices. Furthermore, we use an engineering trick of element-wise operation \(z_{ij}(\nabla_{\mathcal{G}}x)_{ij}\) to keep the degree always non-negative (same as we take the absolute value), which makes the problem solvable. In the end, we reformulate the minimization of \(\mathcal{J}_{TV}(x)\) into a dual _min-max_ functional as \(\mathcal{J}_{TV}(x,z)\), where we maximize \(z\) (\(z\to\mathbf{1}^{N\times N}\)) such that \(\mathcal{J}_{TV}(x,z)\) is close enough to \(\mathcal{J}_{TV}(x)\). Therefore, the new objective function is reformulated as: \[\mathcal{J}(x,z)=\max\limits_{z}\min\limits_{x}\left\|x-x^{0}\right\|_{2}^{2}+ \lambda\int(z\nabla_{\mathcal{G}}x)dx, \tag{1}\] which \(\lambda\) is a scalar balancing the data fidelity term and regularization term. Essentially, Eq. 1 is the dual formulation with _min-max_ property for the TV distillation problem [50]. **Constructing E-L equations.** To solve Eq. 1, we present the following two-step alternating optimization schema. _First_, the inner minimization problem (solving for \(x_{i}\)) in Eq. 1 can be solved by letting \(\frac{\partial}{\partial x_{i}}\mathcal{J}(x_{i},z_{i})=0\): \[\frac{\partial}{\partial x_{i}}\mathcal{J}(x_{i},z_{i})=2(x_{i}-x_{i}^{0})+ \lambda z_{i}\nabla_{\mathcal{G}}x_{i}=0\ \ \Rightarrow\ \ \hat{x}_{i}=x_{i}^{0}-\tfrac{\lambda}{2}z_{i}\nabla_{\mathcal{G}}x_{i} \tag{2}\] Replacing \(\left(\nabla_{\mathcal{G}}x\right)_{ij}\) with \(w_{ij}\left(x_{i}-x_{j}\right)\), the intuition of Eq. 2 is that each element in \(\hat{x}_{i}\) is essentially the combination between the corresponding initial value in \(x_{i}^{0}\) and the overall graph gradients \(z_{i}\nabla_{\mathcal{G}}x_{i}=\sum_{j\in\mathcal{N}_{i}}w_{ij}(x_{i}-x_{j}) z_{i}\) within its graph neighborhood \(\mathcal{N}_{i}\). In this regard, Eq. 2 characterizes the dynamic information exchange on the graph, which is not only steered by graph topology but also moderated by the attenuation factor \(z_{i}\) at each node. _Second_, by substituting Eq. 2 back into Eq. 1, the objective function of \(z_{i}\) becomes \(\mathcal{J}(z_{i})=\max\limits_{|x_{i}|\leq 1}\left\|\tfrac{\lambda}{2}z_{i} \nabla_{\mathcal{G}}x_{i}\right\|_{2}^{2}+\lambda z_{i}\nabla_{\mathcal{G}}(x _{i}^{0}-\tfrac{\lambda}{2}z_{i}\nabla_{\mathcal{G}}x_{i})\). With simplification (in Eq. 8 to Eq. 10 of Supplementary), the optimization of each \(z_{i}\) is achieved by \(\operatorname*{arg\,min}\limits_{|z_{i}|\leq 1}z_{i}\nabla_{\mathcal{G}}x_{i}z _{i}\nabla_{\mathcal{G}}x_{i}-\tfrac{4}{\lambda}z_{i}\nabla_{\mathcal{G}}x_{i} ^{0}\). Specifically, we employ the majorization-minimization (MM) method [16] to optimize \(z_{i}\) by solving this constrained minimization problem (the detailed derivation process is given in Eq. 8 to Eq. 19 of Section 5.1 of Supplementary), where \(z_{i}\) can be iteratively refined by: \[z_{i}^{l}=clip\underbrace{(z_{i}^{l-1}+\frac{2}{\beta\lambda}\nabla_{ \mathcal{G}}x_{i},1)}_{b}=\left\{\begin{array}{cc}b&|b|\leq 1\\ 1&b>1\\ -1&b<-1\end{array}\right. \tag{3}\] \(\beta\) is a hyper-parameter that is required to be no less than the largest eigenvalue of \((\nabla_{\mathcal{G}}x_{i})(\nabla_{\mathcal{G}}x_{i})^{\intercal}\). **Develop new GNN network architecture with a selective inductive bias.** The building block in vanilla GNN [27] is a FC (fully-connected) layer where the input is the embedding vectors after isotropic graph diffusion (in \(\ell_{2}\)-norm). Since the estimation of graph embeddings \(x\) in Eq. 2 depends on the latest estimation of \(z^{(l)}\), such recursive _min-max_ solution for Eq. 1 allows us to devise a new network architecture that disentangles the building block in vanilla GNN into the feature representation learning and graph diffusion underling TV. As shown in Fig. 3, we first deploy a FC layer to update the graph embeddings \(x^{(l)}\). After that, we concatenate a diffusion-clip (DC) layer for selective graph diffusion, which sequentially applies (1) node-adaptive graph diffusion (blue arrow in Fig. 3) on \(x^{(l)}\) by Eq. 22, and (2) clip operation (purple arrow in Fig. 3) to each \(x_{i}^{(l)}\) by Eq. 3. Footnote 2: Since the optimization schema has been switched to the layer-by-layer manner, the initialization \(x_{0}\) becomes \(x^{(l-1)}\) from the previous layer. **Remarks.** Eq. 3 indicates that larger connective degree results in larger value of \(z\). Thus, the DC layer shifts the diffusion patterns by penalizing the inter-community information exchange (due to strong connections) while remaining the heat-kernel diffusion within the community. The preference of such link-adaptive diffusion can be adjusted by the hyper-parameter \(\lambda\)3 in Eq. 1. Recall our intuitive solution for over-smoothing problem in Fig. 1, the DC layer offers the exact global insight of graph topology to keep the node embeddings distinct between nodes #1 and #2. We demonstrate the effect of DC layer on the real-world graph data in Fig. 8 of Supplementary document. Figure 3: Our new deep model integrates a novel diffusion-clip (DC) layer (for selective graph diffusion) after the conventional fully-connected (FC)layer (for graph representation learning). #### 2.2.2 Predict flow dynamics through graph neural transport equation **Problem formulation.** We live in a world of complex systems, where everything is intricately connected in multiple ways. A holistic insight of how the system's components interact with each other and how changes in one part of the system can affect the behavior of the whole sheds new light on the dynamic behaviors of these complex systems over time. However, oftentimes it is an ill-posed problem. Taking the toy system in Fig. 4(a) as an example, while it is simple to calculate the future focal patterns based on the focal patterns at the current time point and the node-to-node flow information, determining flow dynamics based on longitudinal nodal observations is computationally hard since the solution is not unique. The naive solution to predict the spreading flow is to (1) train a GNN to learn the intrinsic node embeddings and (2) predict the flow based on the difference of learned embeddings. However, this two-step approach might suffer from vanishing flow due to over-smoothing in GNNs. Following the spirit of _Brachistochrone_ problem, we ask the question "What flow field \(f(t)=[f_{ij}(t)]_{i,j=1}^{N}\) underlines the system mechanics to the extent that it is able to predict the behaviors in the future?" In this paper, we focus on the conservative system of energy transportation [2]. The system mechanics is formulated as: \[\frac{dx}{dt}+div(q)=0 \tag{4}\] where \(q=[q_{ij}]_{i,j=1}^{N}\) is the flux field which propagates the potential energy \(u(t)=[u_{i}(t)]_{i=1}^{N}\) (conserved quantity) over time. Similar to a gravity field driving water flow, the intuition of Eq. 4 is that the change of energy density \(u\) (we assume there is a non-linear mapping \(\phi\) from external force \(x\) to \(u\), i.e., \(u_{i}=\phi(x_{i})\)) leads to energy transport throughout the entire graph. As flux is closely related to the difference of energy \(\nabla_{\mathcal{G}}u\) underlying the graph topology, we assume the energy flux \(q\) is regulated by the potential energy field \(\nabla_{\mathcal{G}}u\), i.e., \(q=\alpha\otimes\nabla_{\mathcal{G}}u\), where \(\alpha=[\alpha_{ij}]_{i,j=1}^{N}\) is a learnable matrix characterizing the link-wise contribution of each energy potential \(\nabla_{\mathcal{G}}u_{ij}\) to the potential energy flux \(q_{ij}\). By plugging \(q=\alpha\otimes\nabla_{\mathcal{G}}u\) into Eq. 4, the energy transport process can be reformulated as: \[\frac{\partial u}{\partial t}=-\phi^{-1}(\alpha\otimes div(\nabla_{\mathcal{G }}u))=-\phi^{-1}(\alpha\otimes\Delta u), \tag{5}\] where \(\Delta=div(\nabla_{\mathcal{G}})\) is the graph Laplacian operator. Since the PDE in Eq. 5 is equivalent to the E-L equation of the quadratic functional \(\mathcal{J}(u)=\min\limits_{u}\int_{\mathcal{G}}\alpha\otimes|\nabla_{ \mathcal{G}}u|^{2}du\) (after taking \(\phi\) away), a major issue is the over-smoothness in \(u\) that might result in vanishing flows. In this context, we propose to replace the \(\ell_{2}\)-norm integral functional \(\mathcal{J}(u)\) with TV-based counterpart \(\mathcal{J}_{TV}(u)=\min\limits_{u}\int_{\mathcal{G}}\alpha\otimes|\nabla_{ \mathcal{G}}u|du\). **Renovate new E-L equation - graph neural transport equations.** Following the _min-max_ optimization schema in Eq. 1-3, we introduce an auxiliary matrix \(f\) to lift the undifferential-able barrier. After that, the minimization of \(\mathcal{J}_{TV}(u)\) boils down into a dual _min-max_ functional \(\mathcal{J}_{TV}(u,f)=\min\limits_{u}\max\limits_{f}\int_{\mathcal{G}}\alpha \otimes f(\nabla_{\mathcal{G}}u)du\). Since \(u(t)\) is a time series, it is difficult to derive the deterministic solutions (as Eq. 2-3) by letting \(\frac{\partial}{\partial u}\mathcal{J}_{TV}=0\) and \(\frac{\partial}{\partial f}\mathcal{J}_{TV}=0\). Instead, we use \(G\ddot{a}\acute{e}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute {a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a} \acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a} \acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a} \acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a} \acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a} \acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a} \acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a} \acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a} \acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a} \acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a} \acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a} \acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a} \acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a} \acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a} \acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a} \acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a} \acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a} \acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a} \acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a} \acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a} \acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a} \acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a} \acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a} \acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a} \acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a} \acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a} \acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a} \acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a} \acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a} \acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a} \acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a} \acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a} \acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a} \acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a} \acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a} \acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a} \acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a} \acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a} \acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a}\acute{a} \acute{a}\acute **Remarks.** The solution to Eq. 6 is known as continuous max-flow and constitutes a continuous version of a graph-cut [1]. Since \(\alpha\) is a latent variable and potential energy \(u\) is given, the maximization of \(f\) opts towards maximizing the spreading flow through the lens of \(\alpha\). In this regard, the mechanistic role of auxiliary matrix \(f\) is essentially the latent (maximized) spreading flows that satisfy \(u(t+1)_{i}=u(t)_{i}+\sum_{j=1}^{N}f_{ij}(t)\). The potential energy \(\hat{u}\) can be solved via a wave equation (\(u_{tt}=div(f_{t})=\alpha^{2}\otimes\Delta u\)), where the system dynamics is predominated by the adjusted Lagrangian mechanics \(\alpha^{2}\otimes\Delta u\). By determining \(\alpha\) at a granularity of graph links, we devise a novel GAN model to predict the spreading flows \(f\) which not only offers explainability underlying the _min-max_ optimization mechanism in Eq. 6 but also sets the stage to understand system dynamics through machine learning. **Develop a GAN model of flow prediction with TV-based Lagrangian Mechanics.** The overall network architecture is shown in Fig. 4 (b), which consists of a generator (red solid box) and a discriminator module (blue solid box). Specifically, the generator (\(G\)) consists of (1) a GCN component [15] to optimize \(\hat{u}\) through the wave equation \(u_{tt}=\alpha^{2}\otimes\Delta u\) and (2) a FC layer to characterize the non-linear mapping function \(\hat{x}(t+1)=\phi^{-1}(\hat{u}(t))\). In contrast, the discriminator (\(D\)) is designed to (1) synthesize \(\alpha\) and (2) construct the future \(\tilde{u}_{t+1}\) based on the current \(u_{t}\) and current estimation of spreading flow \(f=\alpha\otimes\nabla_{G}u\) (orange dash box). To make the network architecture consistent between generator and discriminator modules, we include another GCN to map the synthesized \(\tilde{u}(t+1)\) to the external force \(\tilde{x}(t+1)\). Note, since the working mechanism of this adversarial model underlines the min-max optimization in the energy transport equation, the nature of predicted spreading flows is carved by the characteristics of _max-flow_. The driving force of our network is to minimize (1) the MSE (mean square error) between the output of the generator \(\hat{x}_{t+1}\) and the observed regional features, (2) the distance between the synthesized regional features \(\tilde{x}_{t+1}\) (from the discriminator) and the output of generator \(\hat{x}_{t+1}\) (from the generator). In the spirit of probabilistic GAN [49], we use one loss function \(\mathcal{L}_{D}\) to train the discriminator (\(D\)) and another one \(\mathcal{L}_{G}\) to train the generator (\(G\)): \[\left\{\begin{array}{c}\mathcal{L}_{D}=D\left(x_{t+1}\right)+\left[\xi-D \left(G\left(x_{t}\right)\right)\right]^{+}\\ \mathcal{L}_{G}=D\left(G\left(x_{t}\right)\right)\end{array}\right. \tag{7}\] where \(\xi\) denotes the positive margin and the operator \([\cdot]^{+}=\max(0,\cdot)\). Minimizing \(\mathcal{L}_{G}\) is similar to maximizing the second term of \(\mathcal{L}_{D}\) except for the non-zero gradient when \(D(G(x_{t}))\geq\xi\). ## 3 Experiments In this section, we evaluate the performance of the proposed _GNN-PDE-COV_ framework with comparison to six graph learning benchmark methods on a wide variety of open graph datasets [36], as well as a proof-of-concept application of uncovering the propagation pathway of pathological events in Alzheimer's disease (AD) from the longitudinal neuroimages. ### Datasets and experimental setup **Dataset and benchmark methods.** We evaluate the new GNN models derived from our proposed GNN framework in two different applications. _First_, we use three standard citation networks, namely _Cora_, _Citeseer_, and _Pubmed_[36] for node classification (the detailed data statistic is shown in Table 3 of Supplementary). We adopt the public fixed split [46] to separate these datasets into training, validation, and test sets. We follow the experimental setup of [9] for a fair comparison with six benchmark GNN models (vanilla GCN [27], GAT [39], GCNII [9], ResGCN [29], DenseGCN [29], GRAND [6]). Since our DC-layer can be seamlessly integrated into existing GNNs as a plug-in. The corresponding new GNN models (with DC-layer) are denoted GCN+, GAT+, GCNII+, ResGCN+, DenseGCN+, and GRAND+, respectively. _Second_, we apply the GAN model in Section 2.2.2 to predict the concentration level of AD-related pathological burdens and their spreading pathways from longitudinal neuroimages. Currently, there is no _in-vivo_ imaging technique that can directly measure the flow of information across brain regions. Here, our computational approach holds great clinical value to understand the pathophysiological mechanism involved in disease progression [26]. Specifically, we parcellate each brain into 148 cortical surface regions and 12 sub-cortical regions using Destrieux atlas [13]. The wiring topology of these 160 brain regions is measured by diffusion-weighted imaging [3] and tractography techniques [19]. The regional concentration levels AD pathology including amyloid, tau, and fluorodeoxyglucose (FDG) and cortical thickness (CoTh) are measured from PET (positron emission tomography) and MRI (magnetic resonance imaging) scans [23]. We use a total of \(M=1,291\) subjects from ADNI [32], each having longitudinal imaging data (2-5 time points). The details of image statistics and pre-processing are shown in Sec. 6.1.2. Since we apply the flow prediction model to each modality separately, we differentiate them with _X-FlowNet_ (\(X\) stands for amyloid, tau, FGD, and CoTh). **Experimental setup**. In the node classification task, we verify the effectiveness and generality of DC-layer in various number of layers (\(L=2,4,8,16,32,64,128\)). All baselines use their own default parameter settings. Evaluation metrics include accuracy, precision and F1-score. To validate the performance of _X-FlowNet_, we examine (1) prediction accuracy (MAE) of follow-up concentration level, (2) prediction of the risk of developing AD using the baseline scan, and (3) understand the propagation mechanism in AD by revealing the node-to-node spreading flows of neuropathologies. The main results of graph node classification and flow prediction are demonstrated in Section 3.2 and 3.3, respectively. Other supporting results such as ablation study and hyper-parameter setting are shown in Section 6 of the Supplementary document. \begin{table} \begin{tabular}{c l l l l l l l l} \hline \hline **Dataset** & **Model** & \(L=2\) & \(L=4\) & \(L=8\) & \(L=16\) & \(L=32\) & \(L=64\) & \(L=128\) \\ \hline \multirow{4}{*}{**Cora**} & GCN & 81.30 & 79.90 & 75.70 & 25.20 & 20.00 & 31.80 & 20.80 \\ & **GCN+** & **82.761\({}^{*}_{*,007}\)** & **82.726\({}^{*}_{*,007}\)** & **82.306\({}^{*}_{*,007}\)** & **70.604\({}^{*}_{*,04}\)** & **67.804\({}^{*}_{*,08}\)** & **66.605\({}^{*}_{*,04}\)** & **59.903\({}^{*}_{*,017}\)** \\ \cline{2-10} & GAT & 82.40 & 80.30 & 57.90 & 31.90 & - & - & - \\ & **GAT+** & **82.600\({}_{*,020}\)** & **80.500\({}_{*,020}\)** & **69.701\({}^{*}_{*,01}\)** & **66.003\({}^{*}_{*,01}\)** & **63.60\({}^{*}_{*,01}\)** & **54.60\({}^{*}_{*,04}\)** & **45.70\({}^{*}_{*,07}\)** \\ \cline{2-10} & **GRAND+** & **81.931\({}^{*}_{*,03}\)** & **83.45\({}^{*}_{*,01}\)** & **81.259\({}^{*}_{*,02}\)** & **82.47\({}^{*}_{*,12}\)** & **83.15\({}^{*}_{*,01}\)** & **81.52\({}^{*}_{*,01}\)** & **81.09\({}^{*}_{*,01}\)** \\ \cline{2-10} & **ResGCN** & 76.30 & 77.30 & 76.20 & 77.60 & 73.30 & 31.90 & 31.90 \\ & **ResGCN+** & **77.801\({}^{*}_{*,007}\)** & **78.701\({}^{*}_{*,007}\)** & **78.601\({}^{*}_{*,007}\)** & **76.903\({}^{*}_{*,007}\)** & **76.801\({}^{*}_{*,01}\)** & **73.60\({}^{*}_{*,01}\)** & **33.60\({}^{*}_{*,01}\)** \\ \cline{2-10} & **DenseGCN** & 76.60 & 78.50 & 76.00 & - & - & - & - \\ & **DenseGCN+** & **78.701\({}^{*}_{*,104}\)** & **78.700\({}_{*,020}\)** & **76.901\({}^{*}_{*,104}\)** & - & - & - & - \\ \cline{2-10} & **GCNII** & 76.40 & 81.90 & 81.50 & 84.80\({}^{*}_{*,01}\)** & 84.703\({}^{*}_{*,01}\)** & **85.20\({}^{*}_{*,01}\)** & **85.040\({}^{*}_{*,001}\)** & **86.30\({}^{*}_{*,007}\)** & **85.60\({}^{*}_{*,007}\)** \\ \cline{2-10} & **GCNII+** & **84.706\({}^{*}_{*,007}\)** & **84.802\({}^{*}_{*,007}\)** & **84.703\({}^{*}_{*,01}\)** & **85.20\({}^{*}_{*,01}\)** & **85.20\({}^{*}_{*,01}\)** & **85.040\({}^{*}_{*,001}\)** & **85.60\({}^{*}_{*,007}\)** & **85.60\({}^{*}_{*,007}\)** \\ \hline \multirow{4}{*}{**Citeseer**} & GCN & 70.20 & 62.50 & 62.90 & 21.00 & 11.90 & 22.90 & 19.80 \\ & **GCN+** & **72.904\({}^{*}_{*,207}\)** & **67.300\({}^{*}_{*,207}\)** & **72.000\({}^{*}_{*,01}\)** & **54.703\({}^{*}_{*,31}\)** & **70.303\({}^{*}_{*,24}\)** & **48.42\({}^{*}_{*,25}\)** & **46.60\({}^{*}_{*,28}\)** \\ \cline{2-10} & **GCN+** & **72.905\({}^{*}_{*,207}\)** & **67.300\({}^{*}_{*,207}\)** & **72.000\({}^{*}_{*,01}\)** & **54.703\({}^{*}_{*,31}\)** & **70.303\({}^{*}_{*,24}\)** & **48.42\({}^{*}_{*,25}\)** & **46.60\({}^{*}_{*,28}\)** \\ \hline \multirow{4}{*}{**Citeseer**} & GAT & 71.70 & 58.60 & 26.60 & 18.10 & - & - & - \\ & **GAT+** & **73.004\({}^{*}_{*,107}\)** & **69.501\({}^{*}_{*,017}\)** & **47.606\({}^{*}_{*,01}\)** & **31.801\({}^{*}_{*,17}\)** & **31.303\({}^{*}_{*,17}\)** & **30.605\({}^{*}_{*,01}\)** & **29.30\({}^{*}_{*,01}\)** \\ \cline{2-10} & **GRAND+** & 71.94 & 72.58 & 73.87 & 75.00 & 75.16 & 72.90 & 69.52 \\ & **GRAND+** & **72.262\({}^{*}_{*,027}\)** & **73.550\({}^{*}_{*,017}\)** & **75.161\({}^{*}_{*,207}\)** & **75.650\({}^{*}_{*,05}\)** & **75.52\({}^{*}_{*,007}\)** & **74.521\({}^{*}_{*,027}\)** & **72.26\({}^{*}_{*,74}\)** \\ \cline{2-10} & **ResGCN** & 67.10 & 66.00 & 63.60 & 65.00 & 62.50 & 18.80 & 80.00 & 18.10 \\ \cline{2-10} & **ResGCN+** & **68.000\({}^{*}_{*,007}\)** & **66.001\({}^{*}_{*,001}\)** & **66.000\({}^{*}_{*,02}\)** & **66.000\({}^{*}_{*,001}\)** & **66.000\({}^{*}_{*,05}\)** & **65.80\({}^{*}_{*,01}\)** & **24.30\({}^{*}_{*,207}\)** \\ \cline{2-10} & **DenseGCN** & 67.40 & 64.00 & 62.20 & - & - & - & - & - \\ ### Experimental results on graph node classification We postulate that by mitigating the over-smoothing issue, we can leverage the depth of GNN models to effectively capture complex feature representations in graph data. As shown in Table 1, we investigate the graph node classification accuracy as we increase the number of GNN layers by six benchmark GNN models and their corresponding plug-in models (indicated by '+' at the end of each GNN model name) with the DC-layer. The results demonstrate that: (1) the new GNN models generated from the _GNN-PDE-COV_ framework have achieved SOTA in _Cora_ (86.30% by GCNII+), _Citeseer_ (75.65% by GRAND+), and _Pubmed_ (80.10 % by GCNII+); (2) all of new GNN models outperforms their original counterparts with significant improvement in accuracy; (3) the new GNN models exhibit less sensitivity to the increase of model depth compared to current GNN models; (4) the new GNN models are also effective in resolving the gradient explosion problem [30] (e.g, the gradient explosion occurs when training GAT on all involved datasets with deeper than 16 layers, while our GAT+ can maintain reasonable learning performance even reaching 128 layers.) It is important to note that due to the nature of the graph diffusion process, graph embeddings from all GNN models (including ours) will eventually become identical after a sufficiently large number of layers [11]. However, the selective diffusion mechanism (i.e., penalizing excessive diffusion across communities) provided by our _GNN-PDE-COV_ framework allows us to control the diffusion patterns and optimize them for specific graph learning applications. ### Application for uncovering the propagation mechanism of pathological events in AD _First_, we evaluate the prediction accuracy between the ground truth and the estimated concentration values by our _X-FlowNet_ and six benchmark GNN methods. The statistics of MAE (mean absolute error) by _X-FlowNet_, GCN, GAT, GRAND, ResGCN, DenseGCN and GCNII, at different noise levels on the observed concentration levels, are shown in Fig. 5 (a). It is clear that our _X-FlowNet_ consistently outperforms the other GCN-based models in all imaging modalities. _Second_, we have evaluated the potential of disease risk prediction and presented the results in Table 4 in Supplementary document, where our _GNN-PDE-COV_ model not only achieved the highest diagnostic accuracy but also demonstrated a significant improvement (paired _t_-test \(p<0.001\)) in disease risk prediction compared to other methods. These results suggest that our approach holds great clinical value for disease early diagnosis. _Third_, we examine the spreading flows of tau aggregates in CN (cognitively normal) and AD groups. As the inward and outward flows shown in Fig. 5(b), it is evident that there are significantly larger amount of tau spreading between sub-cortical regions and entorhinal cortex in CN (early sign of AD onset) while the volume of subcortical-entorhinal tau spreading is greatly reduced in the late stage of AD. This is consistent with current clinical findings that tau pathology starts from sub-cortical regions and then switches to cortical-cortical propagation as disease progresses [28]. However, our _Tau-FlowNet_ offers a fine-granularity brain mapping of region-to-region spreading flows over time, which provides a new window to understand the tau propagation mechanism in AD etiology [14]. ## 4 Conclusion In this work, we present the _GNN-PDE-COV_ framework to re-think and re-design GNN models with great mathematical insight. On top of this, we devise the selective inductive bias to address the over-smoothing problem in GNN and develop new GNN model to predict the pathology flows _in-vivo_ via longitudinal neuroimages. Future work may involve exploring innovative graph regularization techniques and conducting further validation on a broader range of graph-based learning tasks. ## 5 Solving variational problems: From objective functional to E-L equations ### Step-by-step derivation of min-max optimization in Section 2.2.1 By substituting Eq. 2 into Eq. 1 in the main manuscript, we can obtain the objective function of subscript \(z\) (we temporarily drop \(i\) for clarity): \[\mathcal{J}(z) =\max_{|z|\leq\mathbf{1}}\left\|\frac{\lambda}{2}z\nabla_{\mathcal{ G}}x\right\|_{2}^{2}+\lambda z\nabla_{\mathcal{G}}(x^{0}-\frac{\lambda}{2}z \nabla\mathcal{G}x) \tag{8}\] \[=\max_{|z|\leq\mathbf{1}}-\frac{\lambda^{2}}{4}z\nabla_{ \mathcal{G}}xz\nabla_{\mathcal{G}}x+\lambda z\nabla_{\mathcal{G}}x^{0} \tag{9}\] Next, we convert Eq. 9 into a minimization problem as follows: \[z=\begin{array}{c}\operatorname*{arg\,min}\\ |z|\leq\mathbf{1}\end{array}\quad z\nabla_{\mathcal{G}}xz\nabla_{\mathcal{G}}x -\tfrac{4}{\lambda}z\nabla_{\mathcal{G}}x^{0} \tag{10}\] By letting the derivative with respect to \(z_{i}\) to zero, we have the following equation \[\nabla_{\mathcal{G}}xz\nabla_{\mathcal{G}}x=\frac{4}{\lambda}\nabla_{ \mathcal{G}}x^{0} \tag{11}\] Since \(z\) might be in high dimensional space, solving such a large system of linear equations under the constraint \(|z|\leq 1\) is oftentimes computationally challenging. In order to find a practical solution for \(z\) that satisfies the constrained minimization problem in Eq. 10, we resort to the majorization-minimization (MM) method [16]. First, we define: \[M(z)=z\nabla_{\mathcal{G}}xz\nabla_{\mathcal{G}}x-\frac{4}{\lambda}z\nabla_{ \mathcal{G}}x^{0} \tag{12}\] By setting \(z^{l}\) as point of coincidence, we can find a separable majorizer of \(M(z)\) by adding the non-negative function \[(z-z^{l})^{\intercal}(\beta I-\nabla_{\mathcal{G}}x\nabla_{ \mathcal{G}}x^{\intercal})(z-z^{l}) \tag{13}\] to \(M(z)\), where \(\beta\) is greater than or equal to the maximum eigenvalue of \(\nabla_{\mathcal{G}}x\nabla_{\mathcal{G}}x^{\intercal}\). Note, to unify the format, we use the matrix transpose property in Eq. 13. Therefore, a majorizer of \(M(z)\) is given Figure 5: (a) Prediction accuracy by _X-FlowNet_ and six benchmark GNN models w.r.t. various noise levels. (b) The subcortical\(-\)cortical tau flows are profound in CN. But in AD, there is a diminished extent of such flows. by: \[M(z)+(z-z^{l})^{\intercal}(\beta I-\nabla_{\mathcal{G}}x\nabla_{\mathcal{G}}x^{ \intercal})(z-z^{l}) \tag{14}\] And, using the MM approach, we can obtain the update equation for \(z\) as follows: \[\begin{split} z^{l+1}&=\operatorname*{arg\,min}_{|z |\leq 1}(M(z)+(z-z^{l})^{\intercal}(\beta I-\nabla_{\mathcal{G}}x\nabla \mathcal{G}x^{\intercal})(z-z^{l}))\\ &=\operatorname*{arg\,min}_{|z|\leq 1}(\beta z^{\intercal}z-2( \nabla_{\mathcal{G}}(\frac{2}{\lambda}x^{0}-\nabla\mathcal{G}xz^{l})+\beta z ^{l})^{\intercal}z)\\ &=\operatorname*{arg\,min}_{|z|\leq 1}(z^{\intercal}z-2(\frac{1}{ \beta}\nabla_{\mathcal{G}}(\frac{2}{\lambda}x^{0}-\nabla\mathcal{G}xz^{l})+z ^{l})^{\intercal}z)\\ &=\operatorname*{arg\,min}_{|z|\leq 1}(z^{\intercal}z-2b^{\intercal}z) \end{split} \tag{15}\] where \(b=z^{l}+\frac{1}{\beta}\nabla_{\mathcal{G}}(\frac{2}{\lambda}x^{0}-\nabla_{ \mathcal{G}}xz^{l})\). Then, the next step is to find \(z\in\mathcal{R}^{N}\) that minimizes \(z^{\intercal}z-2bz\) subject to the constraint \(|z|\leq 1\). Let's first consider the simplest case where \(z\) is a scalar: \[\operatorname*{arg\,min}_{|z|\leq 1}\quad z^{2}-2bz \tag{16}\] The minimum of \(z^{2}-2bz\) is at \(z=b\). If \(b\leq 1\), then the solution is \(z=b\). If \(|b|\geq 1\), then the solution is \(z=sign(b)\). We can define the clipping function as: \[clip(b,1):=\left\{\begin{array}{cc}&b\quad|b|\leq 1\\ &sign(b)\quad|b|\geq 1\end{array}\right. \tag{17}\] as illustrated in the middle of Fig. 3 in the main text, then we can write the solution to Eq. 16 as \(z=clip(b,1)\). Note that the vector case Eq. 15 is separable - the elements of \(z\) are uncoupled so the constrained minimization can be performed element-wise. Therefore, an update equation for \(z\) is given by: \[z^{l+1}=clip(z^{l}+\frac{1}{\beta}\nabla_{\mathcal{G}}(\frac{2}{\lambda}x^{0} -\nabla_{\mathcal{G}}xz^{l}),1) \tag{18}\] where \(l\) denotes the index of the network layer, the representation of \((l+1)^{th}\) is given by Eq. (1) in the main manuscript. Because the optimization problem is convex, the iteration will converge from any initialization. We may choose, say \(z^{0}=0\). We call this the iterative _diffusion-clip (DC) algorithm_. This algorithm can also be written as \[\begin{split} x^{l+1}&=x^{0}-\frac{\lambda}{2}\nabla _{\mathcal{G}}{}^{\intercal}z^{l}\\ z^{l+1}&=clip\left(z^{l}+\frac{2}{\beta\lambda} \nabla_{\mathcal{G}}x^{l+1},1\right).\end{split} \tag{19}\] By scaling \(z\) with a factor of \(\lambda/2\), we have the following equivalent formulations: \[\begin{split} x^{l+1}&=x^{0}-\nabla_{\mathcal{G}}{} ^{\intercal}z^{l}\\ z^{l+1}&=clip\left(z^{(i)}+\frac{1}{\beta}\nabla_{ \mathcal{G}}x^{l+1},\frac{\lambda}{2}\right)\end{split} \tag{20}\] We summarize the process of the diffusion-clip (DC) layer in Algorithm 1 (it is similar to the iterative shrinkage threshold algorithm [12]): The objective function: \[\mathcal{J}(x)=\min_{x}\bigl{(}\bigl{\|}x-x^{(0)}\bigr{\|}_{2}^{2}+\mathcal{J}_{ TV}(x)\bigr{)}\] can be minimized by alternating the following two steps: \[x^{l} =x^{0}-\nabla_{\mathcal{G}}x^{\intercal}z^{l-1}\] \[z^{l} =clip\left(z^{l-1}+\tfrac{1}{\beta}\nabla_{\mathcal{G}}x^{l}, \tfrac{\lambda}{2}\right)=clip\left(z^{l-1}+\tfrac{2}{\beta\lambda}\nabla_{ \mathcal{G}}x^{l},1\right)\] for \(l\geq 1\) with \(z^{0}=0\) and \(\beta\geq maxeig(\nabla_{\mathcal{G}}x^{\intercal}\nabla_{\mathcal{G}}x)\) ### The step-by-step derivation of min-max optimization schema in Section 2.2.2 According to the introduction of Section 2.2.2 (Eq. 4 and Eq. 5) in the main manuscript, we summarize the following equations, \[\left\{\begin{array}{c}\frac{dx}{dt}+div(q)=0\\ u_{i}=\phi(x_{i})\\ q=\alpha\otimes\nabla u\\ \Delta u=div(\nabla u)\end{array}\right.\xrightarrow{\text{ derive}}\left\{\begin{array}{c}\frac{dx}{dt}=-div(q)\\ \frac{du}{dt}=-\phi^{-1}div(q)\\ \frac{du}{dt}=-\phi^{-1}div(\alpha\otimes q)\\ \frac{du}{dt}=-\phi^{-1}(\alpha\otimes\Delta u)\end{array}\right. \tag{21}\] Since the PDE in Eq. 5 in the main manuscript is equivalent to the E-L equation of the quadratic functional \(\mathcal{J}(u)=\min\limits_{u}\int_{\mathcal{G}}\alpha\otimes|\nabla_{ \mathcal{G}}u|^{2}du\) (after taking \(\phi\) away), we propose to replace the \(\ell_{2}\)-norm integral functional \(\mathcal{J}(u)\) with TV-based counterpart \[\mathcal{J}_{TV}(u)=\min\limits_{u}\int_{\mathcal{G}}\alpha\otimes|\nabla_{ \mathcal{G}}u|du \tag{22}\] We then introduce an auxiliary matrix \(f\) to lift the undifferentiable barrier, and reformulate the TV-based functional as a dual min-max functional \[\mathcal{J}_{TV}(u,f)=\min\limits_{u}\max\limits_{f}\int_{\mathcal{G}}\alpha \otimes f(\nabla_{\mathcal{G}}u)du \tag{23}\] where we maximize \(f\) such that \(\mathcal{J}_{TV}(u,f)\) is close enough to \(\mathcal{J}_{TV}(u)\). Using Gateaux variations, we assume \(u\to u+\varepsilon a\), \(f\to f+\varepsilon b\), and the directional derivatives in the directions \(a\) and \(b\) defined as \(\frac{d\mathcal{J}}{d\varepsilon}(u+\varepsilon a)\big{|}_{\varepsilon\to 0}\) and \(\frac{d\mathcal{J}}{d\varepsilon}(f+\varepsilon b)\big{|}_{\varepsilon\to 0}\). Given a functional \(\mathcal{J}_{TV}(u,f)\), its Gateaux variations is formulated by: \[\mathcal{J}_{TV}(u+\varepsilon a,f+\varepsilon b)=\int\alpha \otimes[(f+\varepsilon b)\cdot(\nabla u+\varepsilon\nabla a)]du \tag{24}\] \[\Rightarrow\frac{\partial\mathcal{J}}{\partial\varepsilon}\bigg{|} _{\varepsilon\to 0}=\int\alpha\otimes[(f\cdot\nabla a)+(\nabla ub)]\ du\] \[\Rightarrow\frac{\partial\mathcal{J}}{\partial\varepsilon}\bigg{|} _{\varepsilon\to 0}=\alpha\otimes f\cdot a-\int\alpha\otimes(a\cdot\nabla f)du+ \int\alpha\otimes(b\nabla u)du\] Since we assume either \(u\) is given at the boundary (Dirichlet boundary condition), the boundary term \(\alpha\otimes f\cdot a\) can be dropped. After that, the derivative of \(\mathcal{J}_{TV}(u,f)\) becomes: \[\frac{\partial\mathcal{J}}{\partial\varepsilon}\bigg{|}_{\varepsilon\to 0}=-\int \alpha\otimes(\nabla f\cdot a+\nabla u\cdot b) \tag{25}\] Since the dummy functional \(a\) and \(b\) are related to \(u\) and \(f\) respectively, the E-L equation from the Gateaux variations in Eq. 25 leads to two coupled PDEs: \[\left\{\begin{array}{l}\max\limits_{f}\frac{df}{dt}=\alpha\otimes\nabla_{\! \!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\! \!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\! \!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\! \!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\! \!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\! \!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\! \!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\! \!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\! \!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\! \!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\! \!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\! \!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\! \!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\! \!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\! \!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\! \!\! * Following the region parcellations, we calculate the regional concentration level (the Cerebellum as the reference) of the amyloid, FDG, CoTh and tau pathologies for each brain region (red arrows in Fig. 6), yielding the input \(x\in\mathcal{R}^{160}\) for training _X-FlowNet_, respectively. Following the clinical outcomes, we partition the subjects into the cognitive normal (CN), early-stage mild cognitive impairment (EMCI), late-stage mild cognitive impairment (LMCI), and AD groups. To facilitate population counts, we regard CN and EMCI as "CN-like" group, while LMCI and AD as "AD-like" groups. Table 3 summarizes the statistics of the two datasets. ### Experiments on node classification Fig 7 presents the performance of different evaluation criteria (accuracy, precision, and F1-score) across different network layers for node classification by benchmark GNN model (patterned in dash lines) and the counterpart novel GNN model from our _GNN-PDE-COV_ framework (patterned by solid lines), where each row is associated with a specific instance of GNN model. It is evident that our proposed _GNN-PDE-COV_ consistently outperforms other methods across different layers, with significantly enhanced degrees in accuracy, precision, and F1-score. Moreover, the GNN model yielded from our _GNN-PDE-COV_ framework consistently achieves the highest accuracy on all three datasets. Overall, these results demonstrate the state-of-the-art performance by our _GNN-PDE-COV_ framework in graph node classification. The effect of anti-smoothing by clip operation is shown in Fig. 8. To set up the stage, we put the spotlight on the links that connect two nodes with different categorical labels. In this context, 2,006 \begin{table} \begin{tabular}{l c c c c c c} \hline \hline Algorithm & Optimizer & Learning rate & Weight decay & Hidden layer & Dropout & Epoch \\ \hline _GCN_ & Adam & 0.01 & \(5\times 10^{-4}\) & \(M\to 2^{i}\rightarrow...\to 2^{4}\to C\) & 0.5 & 1500 \\ \hline _GAT_ & Adam & 0.001 & \(5\times 10^{-4}\) & head=8, \(M\to 2^{i}...\to C\) & 0.6 & 2000 \\ \hline _RGCN_ & Adam & 0.005 & \(5\times 10^{-4}\) & hidden dimension=64 & 0.1 & 2500 \\ \hline _DGCN_ & Adam & 0.001 & \(5\times 10^{-4}\) & hidden dimension=64 & 0.1 & 2500 \\ \hline _GRAND_ & Adam & 0.01 & \(5\times 10^{-4}\) & hidden dimension=16 & 0.5 & 200 \\ \hline _GCNII_ & Adam & 0.005 & \(5\times 10^{-4}\) & hidden dimension=128 & 0.6 & 2000 \\ \hline \hline _GCN_ & Adam & 0.001 & \(5\times 10^{-4}\) & hidden dimension=16 & 0.2 & 500 \\ \hline _GAT_ & Adam & 0.001 & \(5\times 10^{-4}\) & head=8, hidden dimension=4 & 0.5 & 800 \\ \hline _RGCN_ & Adam & 0.001 & \(5\times 10^{-4}\) & hidden dimension=16 & 0.1 & 500 \\ \hline _DGCN_ & Adam & 0.01 & \(5\times 10^{-4}\) & hidden dimension=8 & 0.1 & 500 \\ \hline _GCNII_ & Adam & 0.005 & \(5\times 10^{-4}\) & hidden dimension=16 & 0.6 & 1500 \\ \hline _GRAND_ & Adam & 0.01 & \(5\times 10^{-4}\) & hidden dimension=16 & 0.5 & 500 \\ \hline _X-FlowNet_ & Adam & 1e-4/3e-3 & \(1\times 10^{-5}\) & hidden dimension=16 & 0.5 & 500 \\ \hline _PDENet_ & Adam & 0.01 & \(1\times 10^{-5}\) & hidden dimension=16 & 0.5 & 500 \\ \hline \hline \end{tabular} \end{table} Table 2: Parameters setting on Citation network (top) and ADNI data (bottom). \(M\) denotes the feature dimension and \(C\) denotes the number of classes. For _Cora_ dataset, we set \(i=4\) when network layer \(L=2\), \(i=8\) if \(L=4\), \(i=10\) if \(L=8,16,32,64,128\). For _Citeseer_ dataset, we set \(i=4\) when network layer \(L=2\), \(i=8\) if \(L=4\), \(i=11\) if \(L=8,16,32,64,128\). For Pubmed dataset, we set \(i=4\) when network layer \(L=2\), \(i=8\) if \(L=4,8,16,32,64,128\). The hidden dimension of \(l^{th}\) is twice that of layer \((l-1)^{th}\). Take Cora as an example (8 layers), the dimension of the hidden layer is: 1433 \(\rightarrow\) 1024 \(\rightarrow\)512 \(\rightarrow\) 256\(\rightarrow\)128\(\rightarrow\)64\(\rightarrow\)32\(\rightarrow\)16\(\rightarrow\)7. After exceeding 8 layers, the number of hidden layers is doubled according to the total network layer. \begin{table} \begin{tabular}{l c c c|l c c} \hline \hline \multicolumn{4}{c|}{**Node classification (Citation)**} & \multicolumn{3}{c}{**Application on flow prediction (ADNI)**} \\ \hline \multirow{2}{*}{Dataset} & \multicolumn{3}{c}{Description} & \multicolumn{1}{c}{Features} & \multicolumn{1}{c}{\# of subjects (CN/AD)} \\ \cline{2-7} & Classes & Nodes & Edges & Features & Amyloid (160) & 304/83 \\ \hline _Cora_ & 7 & 2708 & 5429 & 1433 & Tau (160) & 124/37 \\ _Citeseer_ & 6 & 3327 & 4732 & 3703 & FDG (160) & 211/63 \\ _Pubmed_ & 3 & 19717 & 44338 & 500 & Cortical thickness (160) & 359/110 \\ \hline \hline \end{tabular} \end{table} Table 3: Dataset statistics. links from _Cora_, 2,408 links from _Citeseer_, and 17,518 links from _Pubmed_ datasets are selected, called inter-class links. For each inter-class link, we calculate node-to-node similarity in terms of Pearson's correlation between two associated graph embedding vectors 4 by benchmark methods (in red) and the counterpart GNN models derived from _GNN-PDE-COV_ framework (in green). We find that (1) more than 70% nodes are actually associated with inter-class links which confirms the hypothesis of over-smoothing in Fig. 1 of our manuscript; (2) Our novel GNN models have the ability to learn feature representations that better preserve the discriminative power for node classification (as indicated by the distribution of node-to-node similarity shifting towards the sign of anti-correlation). Footnote 4: the learned feature representations for node classification ### Application on uncovering the propagation mechanism of pathological events in AD _Firstly_, we examine the prediction accuracy for each modality of concentration (tau, amyloid, FDG, CoTh) level at different noise levels. Specifically, to evaluate the robustness of our _X-FlowNet_ model to noise, we conducted an experiment by adding uncorrelated additive Gaussian noise levels with standard deviation ranging from 0.02 to 1 to the observed concentration levels of tau, amyloid, FDG, and CoTh. We then evaluated the prediction accuracy (MAE) using 5-fold cross-validation. The prediction results, as shown in Fig. 9, indicate that our _X-FlowNet_ model is less sensitive to noise added to the imaging features than all other counterpart GNN methods. _Secondly_, we conduct an ablation study to compare our _X-FlowNet_ model with _PDENet_ (marked as #7 in Fig. 9). Our model, which is in a GAN architecture and incorporates a TV constraint to avoid over-smoothing, integrates the two steps of estimating the PEF and uncovering the spreading flows into a unified neural network, resulting in significantly improved prediction accuracy compared to _PDENet_. _Thirdly_, we perform a disease risk prediction experiment, which can be regarded as a graph classification problem. We assume that we have baseline amyloid, tau, FDG, and CoTh scans, and evaluate the prediction accuracy, precision and F1-score of various models in forecasting the risk of Figure 6: General workflows for processing T1-weighted image (yellow arrows), diffusion-weighted image (white arrows), and PET images (red arrows). The output is shown at the bottom right, including the brain network, and regional concentration level of amyloid, FDG, CoTh and tau aggregates. developing AD. We consider two dichotomous cases: one included only AD vs. CN groups and the other involved AD/LMCI vs. CN/EMCI. The results of the mean of 5-fold cross-validation are shown in Table 4. Our _GNN-PDE-COV_ outperforms all other methods in terms of accuracy, precision and F1-score indicated by an asterisk (**'*') at the significance level of 0.001. _Fourthly_, we examine the propagation pattern of tau spreading flows on an individual basis (Fig. 10). _First_, we visualize the top flows (ranked in terms of flow volume) uncovered in a CN subject (Fig. 10(a)). It is apparent that subcortex-cortex flows are the predominant patterns, where most of the tau aggregates spread from subcortical regions (globus pallidus, hippocampus, and putamen) to the temporal lobe, limbic lobe, parietal lobe, and insula lobe. Note, we find inferior temporal gyrus (\(t_{6}\)) and entorhinal cortex (\(t_{8}\)) are actively involved in the subcortex-cortex flows, which are the footprints of early stage tau propagation frequently reported in many pathology studies [28; 40]. _Second_, we visualize the top flows uncovered in an AD subject (Fig. 10(b)). It is apparent that the propagation of tau is restricted on the brain cortex, mainly spreading from temporal lobe regions to other regions (such as frontal lobe, limbic lobe and occipital lobe), which is aligned with current clinical and pathology findings that predominant amount of tau aggregates propagate throughout brain cortex in the late stage of AD. ### Discussion and limitations _Discussion._ In our experiments, we found adding DC layer right after every FC layer usually does not yield best performance. Instead, we empirically set to add DC layer from the first several FC layers. For example, we add DC layer after the \(3^{rd}\) FC layer in an 8-layer GNN model, after the \(5^{th}\) FC layer in a 16-layer GNN model, and after \(8^{th}\) FC layer in a GNN model with more than 16 layers. One possible explanation is that the clip operation in DC layer depends on a good estimation of cap \(b\) in Eq. 3 (in the main manuscript). Given that the estimation of \(b\) may lack stability during the initial stages of graph learning, it can be advantageous to postpone the clip operation from an engineering perspective. However, delaying the addition of the DC layer too much can result in missed opportunities to address the problem of over-smoothing. Regarding the computational time, we record the additional computational time of training our DC layer on different datasets. Specifically, the extra training time is 2.2 ms/epoch in _Cora_, 9.8 \begin{table} \begin{tabular}{c|c|c c c c|c c c c|c c} \hline \hline **Tau** & Unit (\%) & GCN & **GCN+** & GAT & **GAT+** & GCNII & **GCNI+** & RGCN & **RGCN+** & DGGCN+** & GRAND & **GRAND+** \\ \hline AD/LMCI & Precision & 80.15 & **90.03**(*) & 69.91 & **86.18*** & 83.93 & **90.03**(*) & 84.64 & **89.46*** & 84.03 & **91.58*** & 87.95 & **88.22*** \\ vs. & Accuracy & 82.30 & **88.74*** & 81.05 & **87.50*** & 83.79 & **88.75*** & 86.03 & **90.00*** & 85.54 & **91.25*** & 88.75 & **86.12*** \\ CN/EMCI & F1-score & 75.55 & **84.49*** & 72.87 & **84.72*** & 88.44*** & 83.18 & **85.54*** & 82.45 & **91.39*** & 88.41 & **89.44*** \\ \hline AD & Precision & 89.29 & **91.92*** & 97.82 & 96.90*** & 83.65 & **88.52*** & 92.61 & **95.72*** & 92.61 & **95.91*** & 91.77 & **95.76*** \\ vs. & Accuracy & 86.64 & **90.91*** & 84.86 & **88.14*** & 76.84 & 86.36 & 91.01 & 97.45*** & 91.97 & **95.65*** & 90.91 & **95.45*** \\ CN & F1-score & 86.54 & **90.26*** & 83.39 & **89.71*** & **76.1*** & 75.11 & **84.68*** & 90.45 & 95.32*** & 90.54 & 95.55*** & 88.86 & **95.38*** \\ \hline **Amyloid** & Unit (\%) & GCN & **GCN+** & GAT & **GAT+** & GCNII & **GCNI+** & RGCN & **RGCN & **DGCN+** & GRAND & **GRAND+** \\ \hline AD/LMCI & Precision & 76.36 & **83.78*** & 67.73 & **71.79*** & 60.87 & **0.01**(*) & 72.53 & **83.21*** & 74.92 & **60.17*** & 79.00 & **79.93*** \\ vs. & Accuracy & 76.40 & **79.44*** & 75.43 & **75.37*** & **75.43*** & 74.61*** & 75.90 & **78.50*** & 76.92 & 75.77 & **80.37** & **81.31*** \\ CN/EMCI & F1-score & 70.33 & **72.58*** & 67.66 & **66.93*** & 63.57 & **67.31*** & 70.66 & **70.67*** & **70.62*** & **76.62*** & **77.79*** & **79.63*** \\ \hline AD & Precision & 81.58 & **88.37*** & 81.54 & **87.98*** & 70.59 & **79.98*** & 85.75 & **93.09*** & 83.87 & **90.56*** & 65.53 & **89.62*** \\ vs. & Accuracy & 80.77 & **88.10*** & 80.78 & **85.10*** & 75.02 & **81.24*** & 85.56 & **92.86*** & 85.29 & **90.48*** & 80.95 & **87.80*** \\ CN & F1-score & 78.14 & **87.68*** & 78.07 & **87.98*** & 65.87 & **77.42*** & 85.34 & **92.92*** & **82.30** & **92.07*** & 72.43 & **88.22*** \\ \hline **FDG** & Unit (\%) & GCN & GCN & **GAT+** & GCNII & **GCNI+** & RGCN & **RGCN & DGCN+** & GRAND & **GRAND+** \\ \hline AD/LMCI & Precision & 84.83 & **67.20*** & 55.86 & **62.90*** & 60.88 & **93.04*** & 90.45 & **85.14*** & 90.45 & **85.14*** & 91.38 & **86.25*** \\ vs. & Accuracy & 73.17 & **76.00*** & 72.17 & **77.00*** & 71.78 & **74.54*** & 70.98 & **74.26*** & 70.98 & **74.26*** & 71.10 & **75.00*** \\ CN/EMCI & F1-score & 89.46 & **81.56*** & 69.12 & **65.90*** & 61.02 & **69.07*** & 85.89 & **63.29*** & 85.86 & **63.29*** & 59.42 & **64.29*** \\ \hline AD & Precision & 81.31 & **87.25*** & 61.90 & **82.33*** & 74.11 & **81.06*** & 90.57 & **89.77** & 89.50*** & 63.84 & **81.77*** & 70.91 & **72.24****** \\ vs. & Accuracy & 82.17 & **84.62*** & 72.82 & **78.95*** & 79.55 & **82.05*** & 73.35 & **79.58*** & 73.80*** & **80.11*** & 84.21 & **86.32*** \\ CN & F1-score & 79.40 & **82.04*** & 64.23 & **69.66*** & 73.38 & **88.09*** & 62.77 & **75.98*** & **63.92*** & **76.58*** & **76.59*** & **78.06*** \\ \hline \hline CoIn & Unit (\%) & GCN & **GCN-** & GAT & **GAT+** & GCNII & **GCNI+** & RGCN & **RGCN+** & GRAND & **GRAND+** \\ AD/LMCI & Precision & 74.85 & **74.74*** & 62.63 & **67.15*** & 62.63 & **74.71*** & 62.63 & **68.77*** & 62.63 & **64.59****** & 63.81 & **68.77*** \\ vs. & Accuracy & 80.68 & **82.32*** & 9.10 & **79.19*** & **79.34*** & 9.10 & **80.37*** & 99.10 & **80.37*** & **97.88** & **82.93*** \\ CN/EMCI & F1-score & 73.55 & **75.93*** & 69.89 & **70.44*** & 69.89 & **72.72*** & 69.89 & **75.19*** & 69.89 & **71.62*** & 70.94 & **75.19*** \\ \hline AD & Precision & 83.45 & **85.77*** & 71.24 & **72.80*** & **78.0*** & 76.14 & **79.84*** & 65.04 & ** ms/epoch in _Citeseer_, 7.8 ms/epoch in _Pubmed_, and 0.3 ms/epoch in _ADNI_, respectively, where the data descriptions are listed in Table 3. It is apparent that the TV-based constraint effectively addresses the over-smoothing issue in GNN without imposing a significant computational burden. _Limitations._ Our current graph learning experiments are limited to citation networks. In the future, we will evaluate our _GNN-PDE-COV_ framework on other graph datasets such as drug medicine and protein networks. _Societal impact._ Our major contribution to the machine learning field is a novel research framework which allows us to develop new GNN models with a system-level understanding. We have provided a new approach to address the common issue of over-smoothing in GNN with a mathematical guarantee. From the application perspective, the new deep model for uncovering the _in-vivo_ propagation flows has great potential to establish new underpinning of disease progression and disentangle the heterogeneity of diverse neurodegeneration trajectories.
2308.08945
Interpretable Graph Neural Networks for Tabular Data
Data in tabular format is frequently occurring in real-world applications. Graph Neural Networks (GNNs) have recently been extended to effectively handle such data, allowing feature interactions to be captured through representation learning. However, these approaches essentially produce black-box models, in the form of deep neural networks, precluding users from following the logic behind the model predictions. We propose an approach, called IGNNet (Interpretable Graph Neural Network for tabular data), which constrains the learning algorithm to produce an interpretable model, where the model shows how the predictions are exactly computed from the original input features. A large-scale empirical investigation is presented, showing that IGNNet is performing on par with state-of-the-art machine-learning algorithms that target tabular data, including XGBoost, Random Forests, and TabNet. At the same time, the results show that the explanations obtained from IGNNet are aligned with the true Shapley values of the features without incurring any additional computational overhead.
Amr Alkhatib, Sofiane Ennadir, Henrik Boström, Michalis Vazirgiannis
2023-08-17T12:35:02Z
http://arxiv.org/abs/2308.08945v3
# Interpretable Graph Neural Networks for Tabular Data ###### Abstract Data in tabular format is frequently occurring in real-world applications. Graph Neural Networks (GNNs) have recently been extended to effectively handle such data, allowing feature interactions to be captured through representation learning. However, these approaches essentially produce black-box models, in the form of deep neural networks, precluding users from following the logic behind the model predictions. We propose an approach, called IGNNet (Interpretable Graph Neural Network for tabular data), which constrains the learning algorithm to produce an interpretable model, where the model shows how the predictions are exactly computed from the original input features. A large-scale empirical investigation is presented, showing that IGNNet is performing on par with state-of-the-art machine-learning algorithms that target tabular data, including XGBoost, Random Forests, and TabNet. At the same time, the results show that the explanations obtained from IGNNet are aligned with the true Shapley values of the features without incurring any additional computational overhead. ## 1 Introduction In some application domains, e.g., medicine and law, predictions made by machine learning models need justification for legal and ethical considerations Lakkaraju et al. (2017); Goodman and Flaxman (2017). In addition, users may put trust in such models only with a proper understanding of the reasoning behind the predictions. A direct solution is to use learning algorithms that produce interpretable models, such as logistic regression Berkson (1944), which provides both local (instance-specific) and global (model-level) explanations for the predictions. However, such algorithms often result in a substantial loss in predictive performance compared to algorithms that generate black-box models, e.g., XGBoost Chen and Guestrin (2016), Random Forests Breiman (2001), and deep learning algorithms Pintelas et al. (2020); Mori and Uchihira (2019). Post-hoc explanation techniques, e.g., SHAP Lundberg and Lee (2017), LIME Ribeiro et al. (2016), and Anchors Ribeiro et al. (2018), have been put forward as tools to explain predictions of the black-box models. However, the explanations provided by such techniques are limited in that they either do not show how exactly the predictions are computed, but merely present feature scores, such as LIME and SHAP, or come with no guarantees on the fidelity, i.e., that the provided explanation agrees with the underlying model Yeh et al. (2019); Delaunay, Galarraga, and Largouet (2020). As extensively argued in Rudin (2019), there are hence several reasons to consider generating interpretable models in the first place, if trustworthiness is a central concern. Graph Neural Networks (GNNs) have emerged as a powerful framework for representation learning of graph-structured data Xu et al. (2019). The application of GNNs has been extended to tabular data, where a GNN can be used to learn an enhanced representation for the data points (rows) or to model the interaction between different features (columns). TabGNN Guo et al. (2021) is an example of the first approach, where each data point is represented as a node in a graph. In comparison, TabularNet Du et al. (2021) and Table2Graph Zhou et al. (2022) follow the second approach, where the first uses a Graph Convolutional Network to model the relationships between features, and the second learns a probability adjacency matrix for a unified graph that models the interaction between features of the data points. GNNs can also be combined with other algorithms suited for tabular data, e.g., as in BGNN Ivanov and Prokhorenkova (2021), which combines gradient-boosted decision trees and a GNN in one pipeline, where the GNN addresses the graph structure and the gradient-boosted decision trees handle the heterogeneous features of the tabular data. To the best of our knowledge, all previous approaches to using GNNs for tabular data result in black-box models and they are hence associated with the issues discussed above when applied in contexts with strong requirements on trustworthiness. In this work, we propose a novel GNN approach for tabular data, with the aim to eliminate the need to apply post-hoc explanation techniques without sacrificing predictive performance. The main contributions of this study are: * a novel approach, called Interpretable Graph Neural Network for tabular data (IGNNet), that exploits powerful graph neural network models while still being able to show exactly how the prediction is derived from the input features in a transparent way * a large-scale empirical investigation evaluating the explanations of IGNNet as well as comparing the predictive performance of IGNNet to state-of-the-art approaches for tabular data; XGBoost, Random Forests, and multi-layer perceptron (MLP), as well as to an algorithm generating interpretable models; TabNet [12] * an ablation study comparing the performance of the proposed approach to a black-box version, i.e., not constraining the learning algorithm to produce transparent models for the predictions In the next section, we briefly review related work. In Section 3, we describe the proposed interpretable graph neural network. In Section 4, results from a large-scale empirical investigation are presented and discussed, in which the explanations of the proposed method are evaluated and the performance is compared both to interpretable and powerful black-box models. Finally, in the concluding remarks section, we summarize the main conclusions and point out directions for future work. ## 2 Related Work In this section, we provide some pointers to self-explaining (regular and graph) neural networks, and briefly discuss their relation to model-agnostic explanation techniques and interpretable models. We also provide pointers to work on interpretable deep learning approaches for tabular data. ### Self-Explaining Neural Networks Several approaches to generating so-called self-explaining neural networks have been introduced in the literature; in addition to generating a prediction model, they all incorporate a component for explaining the predictions. They can be seen as model-specific explanation techniques, in contrast to model-agnostic techniques, such as LIME and SHAP, but sharing the same issues regarding fidelity and lack of detail regarding the exact computation of the predictions. Approaches in this category include the method in [13], which is an early self-explaining neural network for text classification, the Contextual Explanation Network (CEN) [12], which generates explanations using intermediate graphical models, the Self-explaining Neural Network (SENN) [1], which generalizes linear classifiers to neural networks using a concept autoencoder, and the CBM-AUC [14], which improves the efficiency of the former by replacing the decoder with a discriminator. Some approaches generate explanations in the form of counterfactual examples, e.g., CounterNet [15], and Variational Counter Net (VCNet) [16]. Again, such explanations do not provide detailed information on how the original predictions are computed and how exactly the input features affect the outcome. ### Self-Explaining Graph Neural Networks The Self-Explaining GNN (SE-GNN) [1] uses similarities between nodes to make predictions on the nodes' labels and provide explanations using the most similar K nodes with labels. ProtGNN [17] also computes similarities, but between the input graph and prototypical graph patterns that are learned per class. Cui et al. [18] proposed a framework to build interpretable GNNs for connectome-based brain disorder analysis that resembles the signal correlation between different brain areas. Similar to the (standard) self-explaining neural networks, the approaches that target graph neural networks provide abstract views of the predictions; the users cannot trace the exact computations, in contrast to when using interpretable models, which in principle allows for the inferences to be executed by hand. ### Interpretable Deep Learning for Tabular Data In an endeavor to provide an interpretable regression model for tabular data while retaining the performance of deep learning models, and inspired by generalized linear models (GLM), LocalGLMnet was proposed to make the regression parameters of a GLM feature dependent, allowing for quantifying variable importance and also conducting variable selection [15]. TabNet [12] is another interpretable method proposed for tabular data learning, which employs a sequential attention mechanism and learnable masks for selecting a subset of meaningful features to reason from at each decision step. The feature selection is instance-based, i.e., it differs from one instance to another. The feature selection masks can be visualized to highlight important features and show how they are combined. However, it is not obvious how the features are actually used to form the predictions. ## 3 The Proposed Approach: IGNNet This section describes the proposed method to produce an interpretable model using a graph neural network. We first outline the details of a GNN for graph classification and then show how it can be constrained to produce interpretable models. Afterward, we show how it can be applied to tabular data. Finally, we show how the proposed approach can maintain both interpretability and high performance. ### Interpretable Graph Neural Network The input to a GNN learning algorithm is a set of graphs denoted by \(\mathcal{G}=(V,E,X,\mathcal{W})\), consisting of a set of nodes \(V\), a set of edges \(E\), a set of node feature vectors \(X\), and a set of edge weights \(\mathcal{W}\), where \(V=\{v_{1},\dots,v_{N}\}\), \(E\subseteq\{(v_{i},v_{j})|v_{i},v_{j}\in V\}\), \(X=\{\mathbf{x}_{1},\dots,\mathbf{x}_{N}\}\), and the weight of edge \((v_{i},v_{j})\) is represented by a scalar value \(\delta_{i,j}\) in the set of edge weights \(\mathcal{W}\), where \(\delta_{i,j}=\mathcal{W}(i,j)\). A GNN algorithm learns a representation vector \(\mathbf{h}_{i}\) for each node \(v_{i}\), which is initialized as \(\mathbf{h}_{i}^{(0)}=\mathbf{x}_{i}\). The key steps in a GNN for graph classification can be summarized by the following two phases [12]: 1. **Message Passing:** Each node passes a message to the neighboring nodes, then aggregates the passed information from the neighbors. Finally, the node representation is updated with the aggregated information. A neural network can also be used to learn some message functions between nodes. The message passing phase can be formulated as: \[\textbf{h}_{i}^{(l+1)}=\varphi(\textbf{w}^{(l+1)}(\sum_{u\in\mathcal{N}(i)}\delta_ {i,u}\textbf{h}_{u}^{(l)}+\delta_{i,i}\textbf{h}_{i}^{(l)})) \tag{1}\] where \(\delta_{i,u}\) is the weight assigned to the edge between node \(v_{i}\) and node \(v_{u}\). \(\textbf{h}_{i}^{(l)}\) is the hidden representation of the node \(v_{i}\) in the \(l\)-th layer, \(\textbf{w}^{(l+1)}\) represents the learnable parameters, and \(\varphi\) is a non-linearity function. The adjacency matrix \(\boldsymbol{A}\) of size \(|V|\times|V|\) contains the edge weights and can be normalized similar to a Graph Convolutional Network (GCN) [10] as shown in (2). \[\tilde{\boldsymbol{A}}=\boldsymbol{D}^{-\frac{1}{2}}\boldsymbol{A}\boldsymbol {D}^{-\frac{1}{2}} \tag{2}\] Here \(\boldsymbol{D}\) is the degree matrix \(\boldsymbol{D}_{ii}=\sum_{j}\boldsymbol{A}_{ij}\)[10]. **Graph Pooling (Readout):** A representation of the whole graph \(\mathcal{G}\) is learned using a simple or advanced function [13], e.g, sum, mean, or MLP. The whole graph representation obtained from the **graph pooling** phase can be submitted to a classifier to predict the class of the graph, which can be trained in an end-to-end architecture [11, 12]. _The pooling function can be designed to provide an interpretable graph classification layer_. Thus, the final hidden representation of each node is mapped to a single value, for instance, through a neural network layer or dot product (\(f(\textbf{h}_{i}^{(l+1)}\in\mathbb{R}^{n})=h_{i}\in\mathbb{R}^{1}\)), and concatenated to obtain the final representation **g** of the graph \(\mathcal{G}\) where a scalar value in **g** corresponds to a node in the graph. Consequently, if a set of weights is applied to classify the graph, we can trace the contribution of each node to the predicted outcome, i.e., the user can find out which nodes contributed to the predicted class. For example, **g** can be used directly as follows: \[\hat{y}=\text{link}(\sum_{i=1}^{n}\textbf{w}_{i}\textbf{g}_{i}) \tag{3}\] where \(\textbf{w}_{i}\) is the weight assigned to node \(v_{i}\) represented in \(\textbf{g}_{i}\).The link function is applied to accommodate a valid range of outputs, e.g., the sigmoid function for binary and softmax for multi-class classification. This is equivalent to: \[\hat{y}=\text{link}(\sum_{i=1}^{n}\textbf{w}_{i}f(\textbf{h}_{i}^{(l+1)})) \tag{4}\] In the case of binary classification, one vector of weights (**w**) is applied, and for multiple classes, each class has a separate vector of weights. ### Representing Tabular Data Points as Graphs The proposed readout function in the previous subsection allows for determining the contribution of each node in a prediction, if a white-box classification layer is used for the latter. Therefore, we propose representing each data instance as a graph where _the features are the nodes_ of that graph and the _linear correlation between features are the edge weights_, as we assume that not all features are completely independent. The initial representation of a node is a vector of one dimension, and the value is just the feature value, which can be embedded into a higher dimensionality. The idea is outlined in Algorithm 1 and illustrated in Figure 1. ``` Data: a set of graphs \(\mathbb{G}\) and labels \(y\) Result: Model parameters \(\theta\) Initialize \(\theta\) fornumber of training iterationsdo \(\mathcal{L}\gets 0\) foreach \(\mathcal{G}_{j}\in\mathbb{G}\)do \(\boldsymbol{H}_{j}\leftarrow\)messagePassing\((\mathcal{G}_{j})\) \(\textbf{g}_{j}\leftarrow\)readout\((\textbf{H}_{j})\) \(\hat{y}_{j}\leftarrow\)predict\((\textbf{g}_{j})\) \(\mathcal{L}\leftarrow\mathcal{L}+\)loss\((\hat{y}_{j},y_{j})\) end Compute gradients \(\nabla_{\theta}\mathcal{L}\) Update \(\theta\leftarrow\theta-\nabla_{\theta}\mathcal{L}\) end for ``` **Algorithm 1**IGNNet In order to make a prediction for a test instance, the data point has to be converted to a graph using the same procedure for building the input graphs to IGNNet, and for which graph node representations are obtained using a GNN with parameters \(\theta\). Finally, the output layer is used to form the prediction. ### How can IGNNet achieve high performance while maintaining interpretability? An expressive GNN can potentially capture complex patterns and dependencies in the graph, allowing nodes to be mapped to distinct representations based on their characteristics and relationships [11]. Moreover, a GNN with an injective aggregation scheme can not only distinguish different structures but also map similar structures to similar representations [13]. Therefore, if the tabular data are properly presented as graphs, GNNs with the aforementioned expressive capacities can model relationships and interactions between features, and consequently approximate complex non-linear mappings from inputs to predictions. On top of that, it has been shown by [10] that GCNs based on 1-Lipschitz continuous activation functions can be improved in stability and robustness with Lipschitz normalization and continuity analysis; similar findings have also been demonstrated on graph attention networks (GAT) [1]. This property is of particular importance when the application domain endures adversarial attacks or incomplete tabular data. The proposed readout function in subsection 3.1 can produce an interpretable output layer. However, it does not guarantee the interpretability of the whole GNN without message-passing layers that consistently maintain relevant representations of the input features. Accordingly, we constrain the message-passing layer to produce interpretable models using the following conditions: 1. Each feature is represented in a distinct node throughout the consecutive layers. 2. Each node is bounded to interact with a particular neighborhood, where it maintains correlations with the nodes within that neighborhood. As a result, the aggregated messages could potentially hold significance to the input feature values. Since the edge weights are the correlation values, they determine the strength and the sign of the messages obtained from a neighborhood, allowing each node to store information not only concerning the original input feature but also features that are correlated with it. The proposed graph pooling function, combined with the constrained message-passing layers that keep representative information about the input features, allows tracking each feature's contribution at the output layer and also through the message-passing layers all the way to the input features. ## 4 Empirical Investigation This section evaluates both the explanations and predictive performance of IGNNet. We begin by outlining the experimental setup, then by evaluating the explanations produced by IGNNet, and lastly, we benchmark the predictive performance. ### Experimental Setup A GNN consists of one or more message-passing layers, and each layer can have a different design, e.g., different activation functions and batch normalization, which is the intra-layer design level [20]. There is also the inter-layer design level which involves, for instance, how the message-passing layers are organized into a neural network and if the skip connections are added between layers [20]. While the intra-layer and inter-layer designs can vary based on the nature of the prediction task, we propose a general architecture for our empirical investigation. However, it is up to the user to modify the architecture of the GNN. The number of message-passing layers, number of units in linear transformations, and other hyperparameters were found based on a quasi-random search and evaluation on development sets of the following three datasets: Churn, Electricity, and Higgs. We have six message-passing layers in the proposed architecture, each with a Relu activation function. Multiple learnable weights are also applied to the nodes' representation, followed by a Relu function. Besides three batch normalization layers, four skip connections are added as illustrated in Figure 2. After all the GNN layers, we use a feedforward neural network (FNN) to map the multidimensional representation of each node into a single value. In the FNN, we do not include any activation functions in order to keep the mapping linear, but a sigmoid function is applied after the final layer to obtain a value between 0 and 1 for each node. The FNN is composed of 8 layers with the following numbers of units (128, 64, 32, 16, 8, 4, 2, 1) and 3 batch normalization layers after the second, fourth, and sixth hidden layers. After the FNN, the nodes' final values are concatenated to form a representation of the whole graph (data instance). Finally, the weights that are output are used to make predictions. The GNN is trained end-to-end, starting from the embeddings layer and ending with the class prediction. We also provide an opaque variant of IGNNet (OGNNet, opaque graph neural net for tabular data), where the FNN, along with the output layer, is replaced by an MLP of one hidden layer with 1024 hidden units and a Relu activation function. All the learned node representations just before the FNN are concatenated and passed to the MLP for class prediction. The OGNNet is introduced to determine, by an ablation study, how much predictive performance we may lose by squashing the learned multidimensional representation of the nodes into scalar values and applying a white box classifier instead of a black box. In the experiments, 35 publicly available datasets are used.1 Each dataset is split into training, development, and test sets. The development set is used for overfitting detection and early stopping of the training process, the training set is used to train the model, and the test set is used to evaluate the model.2 For a fair comparison, all the compared learning algorithms are trained without hyperparam Figure 1: **An overview of our proposed approach. Each data instance is represented as a graph by embedding the feature values into a higher dimensionality, and the edge between two features (nodes) is the correlation value. Multiple iterations of message passing are then applied. Finally, the learned node representation is projected into a single value, and a whole graph representation is obtained by concatenating the projected values.** eters tuning using the default settings on each dataset. In cases where the learning algorithm does not employ the development set to measure performance progress for early stopping, the development and training subsets are combined into a joint training set. The adjacency matrix uses the correlation values computed on the training data split. The weight on edge from the node to itself (self-loop) is a user-adjustable hyperparameter, constitutes between 70% to 90% (on average) of the weighted summation to keep a strong message per node that does not fade out with multiple layers of message-passing. Weak correlation values are excluded from the graph, so if the absolute correlation value is below 0.2, the edge is removed unless no correlation values are above 0.2; in case of the latter, the procedure is repeated using a reduced threshold of 0.05.3 The Pearson correlation coefficient (Pearson 1895) is used to estimate the linear relationship between features. In the data preprocessing step, the categorical features are binarized using one-hot encoding, and all the feature values are normalized using min-max normalization (the max and min values are computed on the training split). The normalization keeps the feature values between 0 and 1, which is essential for the IGNNet to have one scale for all nodes. Footnote 3: In the technical appendix, we provide an ablation study on the effects of different hyperparameter preferences on predictive performance. The following algorithms are also evaluated in the experiments: XGBoost, Random Forests, MLP and TabNet. XGBoost and Random Forests are trained on the combined training and development sets. The MLP has two layers of 1024 units with Relu activation function and is trained on the combined training and development sets with early stopping and 0.1 validation fraction. TabNet is trained with early stopping after 20 consecutive epochs without improvement on the development set, and the best model is used in the evaluation. For imbalanced binary classification datasets, we oversample the minority class in the training set to align the size with the majority class. All the compared algorithms are trained using the oversampled training data. While for multi-class datasets, no oversampling is conducted. The area under the ROC curve (AUC) is used to measure the predictive performance, as it is not affected by the decision threshold. For the multi-class datasets, weighted AUC is calculated, i.e., the AUC is computed for each class against the rest and weighted by the support. ### Evaluation of Explanations The feature scores produced by IGNNet should ideally reflect the contribution of each feature toward the predicted outcome and, therefore, they should be equivalent to the true Shapley values. As it has been shown that KernelSHAP converges to the true Shapley values when provided with an infinite number of samples (Covert and Lee 2021; Jethani et al. 2022), it is anticipated that the explanations generated by KernelSHAP will progressively converge to more similar values to the scores of IGNNet as the sampling process continues. This convergence arises from KernelSHAP moving towards the true values, while the scores of IGNNet are expected to align with these true values. To examine this conjecture, we explain IGNNet using KernelSHAP and measure the similarity between KernelSHAP's explanations and IGNNet's scores following each iteration of data sampling and KernelSHAP evaluation.4 For the feasibility of the experiment, 500 examples are randomly selected from the test set of each dataset to be explained. The cosine similarity and Spearman rank-order correlation are used to quantify the similarity between explanations. The cosine similarity measures the similarity in the orientation (Han, Kamber, and Pei 2012), while the Spearman rank-order measures the similarity in ranking the importance scores (Rahnama et al. 2021). Footnote 4: KernelSHAP experiments were conducted using the following open-source implementation: [https://github.com/iancovert/shapley-regression](https://github.com/iancovert/shapley-regression) The results demonstrate a general trend wherein KernelSHAP's explanations converge to more similar values to IGNNet's scores across various data instances and the 35 Figure 2: **IGNNet default architecture. It starts with the embedding layer, a linear transformation from one dimension to 64 dimensions. A Relu activation function follows each message-passing layer and each green block as well. The feedforward network at the end has no activation functions between layers to ensure a linear transformation into a single value. A sigmoid activation function follows the feedforward network to obtain the final value for each feature between 0 and 1.** datasets, as depicted in Figure 10. The consistent convergence to more similar values clearly indicates that IGNNet provides transparent models with feature scores aligned with the true Shapley values.56 Footnote 5: The complete results of the 35 datasets are provided in the technical appendix. Footnote 6: We provide illustrations of individual explanations in the technical appendix. ### Evaluation of Predictive Performance Detailed results for IGNNet and the five competing algorithms on the 35 datasets are shown in Table 1. The ranking of the five algorithms across 35 datasets, based on their AUC values, reveals OGNNet to exhibit superior performance, claiming the top position, closely followed by IGNNet and XGBoost. In order to investigate whether the observed differences are statistically significant, the Friedman test [14] was employed, which indeed allowed to reject the null hypothesis, i.e., that there is no difference in predictive performance, as measured by the AUC, at the 0.05 level. The result of subsequently applying the post-hoc Nemenyi test [12] to determine what pairwise differences are significant, again at the 0.05 level, is summarized in Figure 4. However, the result shows no specific significant pairwise differences between any of the compared algorithms. Furthermore, the results show that using IGNNet instead of the black-box variant, OGNNet, does not significantly reduce the predictive performance while maintaining performance at the level of other powerful algorithms for tabular data, e.g., XGBoost and Random Forests. ## 5 Concluding Remarks We have proposed IGNNet, an algorithm for tabular data classification, which exploits graph neural networks to produce transparent models. In contrast to post-hoc explanation techniques, IGNNet does not approximate or require costly computations, but provides the explanation while computing the prediction, and where the explanation prescribes exactly how the prediction is computed. We have presented results from a large-scale empirical investigation, in which IGNNet was evaluated with respect to explainability and predictive performance. IGNNet was shown to generate explanations with feature scores aligned with the Shapley values without further computational cost. IGNNet was also shown to achieve a similar predictive performance as XGBoost, Random Forests, TabNet, and MLP, which are all well-known for their ability to generate high-performing models. One direction for future research is to explore approaches to model feature interaction in the adjacency matrix that go beyond linear correlations. Understanding how such non-linear interactions between features may impact the model's interpretability could be an intriguing area of exploration. A second direction is to investigate alternative encoders for categorical features rather than relying on one-hot encoding. It would also be interesting to extend IGNNet to handle non-tabular datasets, including images and text, which would require entirely different approaches to representing each data point as a graph. Another important direction for future work is to use IGNNet for studying possible adversarial attacks on a predictive model. Finally, an important direction would be to complement the empirical evaluation with user-grounded evaluations, e.g., measuring to what extent certain tasks could be more effectively and efficiently solved when the users are provided with a transparent model that shows how the prediction has been computed from the input. ## 6 Acknowledgement This work was partially supported by the Wallenberg AI, Autonomous Systems and Software Program (WASP) funded by the Knut and Alice Wallenberg Foundation.
2310.13849
A Dual-Stream Neural Network Explains the Functional Segregation of Dorsal and Ventral Visual Pathways in Human Brains
The human visual system uses two parallel pathways for spatial processing and object recognition. In contrast, computer vision systems tend to use a single feedforward pathway, rendering them less robust, adaptive, or efficient than human vision. To bridge this gap, we developed a dual-stream vision model inspired by the human eyes and brain. At the input level, the model samples two complementary visual patterns to mimic how the human eyes use magnocellular and parvocellular retinal ganglion cells to separate retinal inputs to the brain. At the backend, the model processes the separate input patterns through two branches of convolutional neural networks (CNN) to mimic how the human brain uses the dorsal and ventral cortical pathways for parallel visual processing. The first branch (WhereCNN) samples a global view to learn spatial attention and control eye movements. The second branch (WhatCNN) samples a local view to represent the object around the fixation. Over time, the two branches interact recurrently to build a scene representation from moving fixations. We compared this model with the human brains processing the same movie and evaluated their functional alignment by linear transformation. The WhereCNN and WhatCNN branches were found to differentially match the dorsal and ventral pathways of the visual cortex, respectively, primarily due to their different learning objectives. These model-based results lead us to speculate that the distinct responses and representations of the ventral and dorsal streams are more influenced by their distinct goals in visual attention and object recognition than by their specific bias or selectivity in retinal inputs. This dual-stream model takes a further step in brain-inspired computer vision, enabling parallel neural networks to actively explore and understand the visual surroundings.
Minkyu Choi, Kuan Han, Xiaokai Wang, Yizhen Zhang, Zhongming Liu
2023-10-20T22:47:40Z
http://arxiv.org/abs/2310.13849v2
# A Dual-Stream Neural Network Explains the ###### Abstract The human visual system uses two parallel pathways for spatial processing and object recognition. In contrast, computer vision systems tend to use a single feed-forward pathway, rendering them less robust, adaptive, or efficient than human vision. To bridge this gap, we developed a dual-stream vision model inspired by the human eyes and brain. At the input level, the model samples two complementary visual patterns to mimic how the human eyes use magnocellular and parvocellular retinal ganglion cells to separate retinal inputs to the brain. At the backend, the model processes the separate input patterns through two branches of convolutional neural networks (CNN) to mimic how the human brain uses the dorsal and ventral cortical pathways for parallel visual processing. The first branch (WhereCNN) samples a global view to learn spatial attention and control eye movements. The second branch (WhatCNN) samples a local view to represent the object around the fixation. Over time, the two branches interact recurrently to build a scene representation from moving fixations. We compared this model with the human brains processing the same movie and evaluated their functional alignment by linear transformation. The WhereCNN and WhatCNN branches were found to differentially match the dorsal and ventral pathways of the visual cortex, respectively, primarily due to their different learning objectives, rather than their distinctions in retinal sampling or sensitivity to attention-driven eye movements. These model-based results lead us to speculate that the distinct responses and representations of the ventral and dorsal streams are more influenced by their distinct goals in visual attention and object recognition than by their specific bias or selectivity in retinal inputs. This dual-stream model takes a further step in brain-inspired computer vision, enabling parallel neural networks to actively explore and understand the visual surroundings. ## 1 Introduction The human visual system comprises two parallel and segregated streams of neural networks: the "where" stream and the "what" stream [1]. The "where" stream originates from magnocellular retinal ganglion cells and extends along the dorsal visual cortex. The "what" stream originates from parvocellular retinal ganglion cells and extends along the ventral visual cortex [2]. The two streams exhibit selective responses to different aspects of visual stimuli [3]. The "where" stream is tuned to coarse but fast information from a wide view, while the "what" stream is selective to fine but slow information from a narrow view [2; 4]. The two streams are thought to serve different purposes. The "where" stream zooms out for spatial analysis [5], visual attention [6; 7; 8], and guiding actions [9] such as eye movements [10], while the "what" stream zooms in to recognize the object around the fixation [11]. While being largely parallel, the two streams interact with each other [12]. In one way of their interaction, the "where" stream decides where to look next and guides the "what" stream to focus on a salient location for visual perception. As the eyes move around the visual environment, the interaction between the "where" and "what" streams builds a scene representation by accumulating object representations over time and space. This dual-stream architecture allows the brain to efficiently process visual information and support dynamic visual behaviors [13]. In contrast, computer vision systems tend to use a single stream of feedforward processing, acting as passive observers that sample visual information all at once with fixed and uniform patterns [14; 15; 16]. Compared to human vision, this processing is less robust, especially given adversarial attacks [17; 18]; it is less efficient since it samples visual information equally regardless of salience or nuisance [19]; it is less adaptive, lacking spatial attention for active sensing [20; 21]. These distinctions define a major gap between human and computer vision. Many visual tasks that are straightforward for humans are Figure 1: **Brain-inspired dual-stream vision model. The top illustrates the subcortical (dashed arrows) and cortical (solid arrows) pathways for parallel visual processing in the brain. Given a scene (e.g., “two foxes on the lawn”), the retina samples incoming light relative to the fixation of the eyes (shown as the cross). Magnocellular (orange) and parvocellular (blue) retinal ganglion cells encode complementary visual information into two sets of retinal inputs relayed onto separate layers in the lateral geniculate nuclei (LGN) and further onto different neurons in the primary visual cortex (V1). Within V1, the relative ratio of magnocellular vs. parvocellular projections is higher for the periphery and lower for the fovee. Beyond V1, the magnocellular pathway continues along the dorsal visual cortex towards the intraparietal areas and further onto the frontal eye field (FEF) for oculomotor control, while the parvocellular pathway continues along the ventral visual cortex towards the inferior temporal cortex and further onto the superior temporal areas for semantic cognition. The bottom illustrates our model architecture including WhereCNN and WhatCNN. The model’s frontend mimics the human retina and generates two separate input patterns relative to the fixation. One pattern is wider but coarser while the other is narrower but finer, providing the respective inputs to WhereCNN and WhatCNN. With the wide-view input, WhereCNN generates a probability map of saliency from which the next fixation is sampled. With a narrow-view input, WhatCNN generates an object representation per each fixation and constructs a scene representation recurrently from multiple fixations.** still challenging for machines [22; 23]. Therefore, computer vision may benefit from taking further inspiration from the brain by using a dual-stream architecture to learn adaptive and robust visual behaviors. To gain insights into the computational mechanisms of human vision, researchers have developed image-computable models by utilizing goal-driven deep neural networks that simulate human perceptual behavior. In particular, convolutional neural networks (CNNs) are leading models of visual perception, capturing the hierarchical processing by the brain's ventral visual stream [24; 25; 26; 27; 28]. Previous models of this nature commonly utilize CNNs trained through supervised learning [24; 27; 25; 29; 26; 30], adversarial training [31; 32], unsupervised learning [33; 34], or self-supervised learning [35; 36; 37]. However, models of the dorsal stream remain relatively under-explored, despite few studies [38; 39; 40; 41]. Existing testing of these models has primarily focused on static images presented briefly to the fovea, thus limiting their assessment to a narrow range of visual behaviors and processes [42]. A more comprehensive approach is needed to develop models that incorporate both dorsal and ventral stream processing and to assess those models against brain responses when humans engage both the dorsal and ventral streams to freely explore complex and dynamic visual environments, which may be simulated in experimental settings [43]. To meet this need, we have developed a dual-stream model to mimic the parallel ventral and dorsal streams in the human brain [1; 2; 3; 9]. The model includes two branches of convolutional neural networks: WhereCNN and WhatCNN, which share the same architecture but receive distinct visual inputs and generate different outputs. WhereCNN samples a wide view to learn spatial attention and where to direct the subsequent gaze, while WhatCNN samples a narrow view to learn object representations. By taking multiple gazes at a given scene, the model sequentially samples the salient locations and progressively constructs a scene representation over both space and time. To evaluate this dual-stream model as a model of the human visual system, we have tested its ability to reproduce human gaze behavior and predict functional brain scans from humans watching a movie with unconstrained eye movements. Our hypothesis is that the model's WhereCNN and WhatCNN branches can effectively predict the brain responses along the brain's dorsal and ventral visual pathways, respectively. In addition, we have also conducted experiments to evaluate the underlying factors contributing to the functional segregation of the brain's dorsal and ventral visual streams. Of particular interest were the relative contributions of retinal sampling, spatial attention, and attention-guided eye movement in shaping the function of the dorsal stream and its interplay with the ventral stream during dynamic natural vision. ## 2 Related Works ### Dorsal-stream vision Image-computable models of the brain's dorsal stream have been relatively limited compared to models of the ventral stream. Previous work has attempted to model the dorsal stream by training deep neural networks to detect motion [38] or classify actions [40] using video inputs. However, these models do not fully capture the neuroscientific understanding that the dorsal stream is involved in locating objects and guiding actions, leading to its designation as the "where" or "how" visual pathway. More recent work by Mineault et al. focused on training a dorsal-stream model to emulate human head movements during visual exploration [39]. Additionally, Bakhtiari et al. utilized predictive learning to train parallel pathways and observed the ventral-like and dorsal-like representations as an emergent consequence of structural segregation [41]. However, no prior work has explored neural network models that emulate how the dorsal stream learns spatial attention and guides eye movements for visual navigation. ### Spatial attention and eye movement Prior research in the field of computer vision has attempted to train models to attend to and selectively focus on salient objects within a scene [44; 21; 45], rather than processing the entire scene as a whole. This approach aligns with the brain's mechanism of spatial attention, where the dorsal stream acts as a global navigator, and the ventral stream functions as a local perceiver. In line with this mechanism, previous studies have employed dual-stream neural networks that process global and local features in parallel, aiming to achieve enhanced computational efficiency as a unified system [46; 44; 47; 48; 49]. However, these models do not fully replicate the way human eyes sample visual inputs during active exploration of the scene and thus still fall short in biological relevance. ### Foveated vision and retinal transformation The human retina functions as a sophisticated camera that intelligently samples and transmits visual information. It exhibits the highest visual acuity in the central region of the visual field, a phenomenon referred to as foveated vision [50; 51; 52]. In contrast, peripheral vision uses lower spatial acuity but higher temporal sensitivity, making it better suited for detecting motion. These properties of retinal sampling are potentially useful for training neural networks to enhance performance [53; 54; 55; 56] or robustness [57; 58; 19], augment data or synthesize images [59]. The retina also transmits information to the brain using distinct types of cells. The magnocellular and parvocellular retinal ganglion cells have different distributions, selectivity, and relay information through largely separate pathways. Taken together, the retina transforms visual information into segregated inputs for parallel visual processing. This biological mechanism has not been systematically investigated. Unlike the above prior works, our work combines multiple biologically inspired mechanisms into an integral learnable model. It uses a frontend inspired by the human retina and applies complementary retinal sampling and transformation. It uses two parallel pathways inspired by the human dorsal and ventral streams. It uses spatial attention and object recognition as the distinct learning objectives for training the two pathways. It further uses the attention to move fixations and thus allows the two pathways to interact for active sensing. Although these mechanisms have been explored separately in prior studies, their combination is novel and motivates our work to build and test such a model against the human brain and behavior in a naturalistic condition of freely watching a movie. ## 3 Methods In our model, WhereCNN and WhatCNN serve distinct functions in processing objects within a scene. WhereCNN identifies the spatial location of an object, determining "where" it is situated, while WhatCNN focuses on recognizing the identity of the object, determining "what" it is. When multiple objects are present in a scene, WhereCNN learns spatial attention and "how" to sequentially locate and fixate on each object. This allows the model to selectively attend to different objects in a sequence, mirroring the dynamic nature of human eye movements during visual exploration. Fig.1 illustrates and describes the human visual system that inspires us to design our model. ### Model design and training Akin to the human eyes [60; 61], our model uses retinal transformation [62] to generate separate inputs to WhereCNN and WhatCNN. For both, the retinal input consists of \(64\times 64\) samples non-uniformly distributed around the fixation. When describing a point in the retinal image and its corresponding point in the visual world in terms of the radial distance and the polar angle with respect to the fixation, their polar angles are the same while their radial distances are related by Eq. 1. \[r=g(r^{\prime})=\frac{b}{\sqrt{\pi}}\frac{1-\exp(\ln(a)r^{\prime}/2)}{1-\exp( \ln(a)/2)} \tag{1}\] where \(r^{\prime}\) and \(r\) are the radial distances in the retinal and original images, respectively, \(b\) is a constant that ensures \(r_{\max}/g(r^{\prime}_{\max})=1\), and \(a\) controls the degree of center-concentration. Given a larger \(a\), more retinal samples are closer to the fovea relatively to the periphery. We set \(a=15\) for WhatCNN and \(a=2.5\) for WhereCNN. In this setting, WhereCNN is more selective to global features, while WhatCNN is more selective to local features, mirroring the sampling bias of magnocellular and parvocellular retinal ganglion cells, as illustrated in Fig.1. Both WhereCNN and WhatCNN use similar backbone architectures. The backbone consists of four blocks of convolutional layers. Each block includes two Conv2D layers (kernel size \(3\times 3\)) followed by ReLU and BatchNorm. Applying \(2\times 2\) MaxPool between adjacent blocks progressively reduces the spatial dimension. The feature dimension following each block is \(64\), \(128\), \(256\), or \(512\). Atop this backbone CNN, both WhereCNN and WhatCNN use additional components to support different goals. For WhereCNN, the feature maps from the 3rd and 4th convolutional blocks are resized to \(16\times 16\) and concatenated, providing the input to an additional convolutional block. Its output feature map is subject to SoftMax to generate a probability map of visual saliency. By random sampling by the probability of saliency, WhereCNN decides a single location for the next fixation. To avoid future fixations to revisit previously attended areas, inhibition of return (IOR) [63] is used. IOR keeps records of locations of prior visits as defined in Eq.2. \[\textbf{IOR}(t)=\textbf{ReLU}\Big{(}\textbf{1}-\sum_{\tau=1}^{t}G(\boldsymbol{ \mu}=\boldsymbol{l}_{\tau},\boldsymbol{\Sigma}=\sigma^{2}\boldsymbol{I})\Big{)} \tag{2}\] where \(G(\boldsymbol{\mu},\boldsymbol{\Sigma})\) is a 2D Gaussian function centered at \(\boldsymbol{l}_{\tau}\) (prior fixations) with a standard deviation \(\sigma\) at the \(\tau\)-th step. Its values are normalized so that its maximum equals 1. By applying the IOR to the predicted saliency map using an element-wise multiplication, the future fixations would not revisit the areas already explored. For WhatCNN, the output feature map from the 4th convolutional block, after global average pooling, is given as the input to an additional layer of Gated Recurrent Units (GRU) [64], which recurrently update the representation from a sequence of fixations to construct a cumulative representation following another fully-connected layer. We first pre-train each stream separately and then fine-tune them together through three stages. **Stage 1 - WhereCNN**. We first train WhereCNN for image recognition using ILSVRC2012 [65] for object recognition and then fine-tune it for generating the saliency map to match human attention using SALICON dataset [66]. In this stage, we use random fixations to generate the retinal inputs to WhereCNN. Adam optimizer [67] (lr=\(0.002\), \(\beta_{1}\)=0.9, \(\beta_{2}\)=0.99) is used with \(25\) epochs for SALICON training. At this stage, WhereCNN learns spatial attention from humans. **Stage 2 - WhatCNN**. We first train WhatCNN for single-object recognition using ILSVRC2012 [65] and then fine-tune it for multi-object recognition using MSCOCO [68]. In this stage, we use the pre-trained WhereCNN to generate a sequence of eight fixations and accordingly apply the retinal transformation to generate a sequence of retinal inputs to WhatCNN for recurrent object recognition. Note that the training in Stage 2 is confined to WhatCNN, while leaving WhereCNN as pre-trained in Stage 1. Adam optimizer (lr=\(0.002\), \(\beta_{1}\)=0.9, \(\beta_{2}\)=0.99) is used with \(40\) epochs for MSCOCO training. **Stage 3 - WhereCNN & WhatCNN**. Lastly, we equally combine the two learning objectives to train both WhereCNN and WhatCNN altogether and end-to-end using eight fixations. Adam optimizer (lr=\(0.0002\), \(\beta_{1}\)=0.9, \(\beta_{2}\)=0.99) is used with \(25\) epochs for training. In this stage, SALICON, which contain labels for both saliency prediction and object recognition, is used for training. More details can be found at Appendix B1. Footnote 1: The code and appendix are available at [https://github.com/minkyu-choi04/DualStreamBrains/](https://github.com/minkyu-choi04/DualStreamBrains/) ### Model evaluation with human gaze behavior and fMRI responses We use two criteria to evaluate how well a model matches the brain given naturalistic and dynamic visual stimuli. First, the model should generate similar human visual behaviors, such as visual perception and gaze behavior. Second, the model's internal responses to the stimuli should predict the brain's responses to the same stimuli through linear projection implemented as linear encoding models [69]. For our dual-stream model, we hypothesize that WhereCNN better predicts dorsal-stream voxels and WhatCNN better predicts ventral-stream voxels. For this purpose, we use a publicly available fMRI dataset from a prior study [70], in which a total of 11 human subjects (\(4\) females) were instructed to watch the movie Raiders of the Lost Ark (\(115\) minutes) with unconstrained eye movements. The movie was displayed on an LCD projector with a visual angle of \(17^{\circ}\times 22.7^{\circ}\). Whole-brain fMRI data was acquired in a 3-T MRI system with a gradient-recalled echo planar imaging sequence (TR/TE = \(2.5\)s/\(35\)ms, flip angle = \(90^{\circ}\), nominal resolution = \(3\)mm \(\times\)\(3\)mm \(\times\)\(3\)mm). We preprocess the data by using the minimal preprocessing pipeline released by the Human Connectome Project (HCP) [71] We test how well the model can predict the voxel-wise fMRI response to the movie stimuli through a learnable linear projection of artificial units in the model. To evaluate whether and how the two branches in the model differentially predict the two streams in the brain, we define two encoding models for each voxel: one based on WhereCNN and the other based on WhatCNN. We train and test the encoding models with data during different segments of the movie. To avoid overfitting, we apply dimension reduction to the internal responses in either WhereCNN or WhatCNN by applying principal component analysis (PCA) first to each layer and then to all layers while retaining \(99\)% of the variance [30; 33]. We further convolve the resulting principal components with a canonical hemodynamic response function (HRF) that peaks at \(5\) seconds, down-sample them to match the sampling rate of fMRI, generating the linear regressors used in the encoding model. Using the training data (\(81\)% of the total data), we estimate the encoding parameters using L2-regularized least squares estimation. Using the held-out testing data (\(19\)%), we test the encoding models for their ability predicting the fMRI responses observed at each voxel and measure the accuracy of prediction as the correlation between the predicted and measured fMRI responses, denoted as \(r_{where}\) and \(r_{what}\) for the encoding models based on WhereCNN and WhatCNN. We test the significance of the prediction using a block permutation test [72] with a block size of \(20\)-seconds and \(100,000\) permutations and apply the false discovery rate (FDR) (\(p<0.05\)). We further differentiate the relative roles of the brain's WhereCNN vs. WhatCNN in predicting the brain's dorsal and ventral streams for single voxels as well as regions of interest. For this, we define a relative performance (Eq.3). \[p_{where}=\frac{r_{where}^{2}}{r_{where}^{2}+r_{what}^{2}} \tag{3}\] In the range from \(0\) to \(1\), \(p_{where}>0.5\) indicates better predictive performance by WhereCNN, while \(p_{where}<0.5\) indicates better predictive performance by WhatCNN. ### Alternative models and control experiments By design, the WhereCNN and WhatCNN branches within our model exhibit two key distinctions. WhereCNN is specifically trained to learn spatial attention by utilizing wider views, while WhatCNN focuses on object recognition through the use of local views. To explore the impact of input views and learning objectives on the model's capacity to predict brain responses, we introduce two modified control streams: ControlCNN-a and ControlCNN-b, designed as hybrid variants encapsulating diverse input views and learning objectives. ControlCNN-a receives a narrower view as its input and is trained for saliency prediction. Conversely, ControlCNN-b is curated to accommodate a broader view and primarily focuses its training on object recognition. These adjustments yield a versatile examination of their respective influences and functionalities. By combining WhereCNN or WhatCNN with ControlCNN-a or ControlCNN-b, we create four alternative dual-stream models (illustrated in Fig.4) and examine their abilities to explain the functional segregation of the brain's dorsal and ventral streams. ## 4 Results ### WhereCNN learns attention and WhatCNN learns perception The WhereCNN and WhatCNN branches in our model are specifically designed to fulfill different objectives: predicting human visual saliency and recognizing visual objects, respectively. In Fig.2, we present examples comparing human attention with the model's attention based on the SALICON's validation set. WhereCNN can successfully identify salient locations where humans are more likely to direct gaze. Additionally, WhereCNN can mimic human saccadic eye movements by generating a sequence of fixations that navigate the model's attention to those salient locations. In contrast, WhatCNN can recognize either single or multiple objects (macro F1 score on MSCOCO's validation set: 61.0). ### WhereCNN and WhatCNN matches dorsal and ventral visual streams By using linear encoding models, we use the WhereCNN and WhatCNN branches to predict fMRI responses during the processing of identical movie stimuli by both the model and the brain. Together, these two branches can predict responses across a wide range of cortical locations involved in visual processing. However, they exhibit distinct predictive power in relation to the dorsal and ventral streams. Generally, the WhereCNN branch exhibits superior predictive performance for the Figure 3: **Differential encoding of the dorsal and ventral streams. (a) Relative contributions of WhereCNN and WhatCNN to the prediction of the fMRI response observed at each cortical location. Color highlights the locations significantly predictable by the model (FDR<0.05, block permutation test). The color itself indicates the degree by which WhereCNN is more predictive than WhatCNN (warm-tone) or the opposite (cool-tone). Visual areas are delineated and labeled based on brain atlas [73]. Panel (b) plots the predictive performance by WhereCNN (y-axis) against that by WhatCNN (x-axis) and shows a clear separation of voxels (left panel) or ROIs (right panel) along the dorsal stream (red) vs. ventral stream (blue) relative to the dashed line of equal predictability. See Appendix A for the full ROI labels.** Figure 2: **Saliency prediction. Given an image (1st row), WhereCNN generates a saliency map (3rd row) similar to the map of human attention (2nd row). Sampling this saliency map generates a sequence of fixations (as red/orange/blue circles in the order of time in the 4th row) similar to human saccadic eye movements (not shown).** dorsal stream, while the WhatCNN branch performs better in predicting responses within the ventral stream (Fig.3). For the early visual areas (V1, V2, V3), WhereCNN better predicts the peripheral representations, while WhatCNN better predicts the foveal representations. ### Factors underlying the functional segregation of the dorsal and ventral streams We further investigate the underlying factors contributing to the model's ability to explain the functional segregation of the brain's dorsal and ventral visual streams (as depicted in Fig.3). Specifically, we examine the input sampling pattern and output learning objective, both of which are distinct for the WhereCNN and WhatCNN branches in our dual-stream model. To investigate the contributing factors of the functional segregation in predicting human ventral and dorsal streams, we introduce four variations of the proposed model, where the two branches either share their inputs or have the same learning objectives, and compare their abilities to account for the functional segregation of the dorsal and ventral visual streams (as shown in Fig. 4). When the two branches solely differ in their input sampling, they are unable to explain the dorsal-ventral segregation (combination 1 and 2). However, when the two branches exclusively differ in their learning objectives, the functional segregation is better explained (combination 3 and 4). Moreover, when the two branches differ in both input sampling and learning objectives (combination 5), as utilized in our proposed model, the functional segregation is even more pronounced. These ablation experiments suggest that the distinct learning objectives of the brain's dorsal and ventral streams is the primary factor underlying their functional segregation. ### Dual-stream: a better brain model than single-stream We also compare our dual-stream model with single-stream alternatives. One of these alternatives is a baseline CNN that shares the same backbone architecture as a single branch in our dual-stream model. However, this baseline CNN is trained with original (224x224) images to recognize objects in ImageNet [65] and MS-COCO [68]. Thus, it serves as a direct comparison with either the WhereCNN or WhatCNN branch in our model. In addition, we also include AlexNet [14], ResNet18, Figure 4: **Contributing factors of the dorsal-ventral functional segmentation.** (a) Alternative designs of the two-stream model for investigating the contributing factors of the functional segregation of two streams in the proposed model. In addition to WhereCNN and WhatCNN in the proposed model, we included ControlCNN-a (narrow input field of view for predicting location) and ControlCNN-b (wide input field of view for predicting perception) for an ablation study. (b) The predictive performances and functional segregations by the two streams are plotted for the dorsal (red squares) vs. ventral (blue triangles) ROIs for each of the alternative models in (a), correspondingly. The dashed diagonal lines represent equal predictive abilities of ventral and dorsal ROIs. (c) Quantitative evaluation of the functional segregation of the dorsal and ventral ROIs relative to the dashed line of equal predictability. Separability measures how far the predictions are away from the dashed line. Assuming the coordinates of a certain ROI is (\(x,y\)), separability is calculated as the average of \(|x-y|\) for all ROIs. and ResNet34 [15] as additional alternatives, which have been previously evaluated in relation to brain responses [30; 74]. We compare these single-stream alternatives with either branch in our model in terms of their ability to predict brain responses within dorsal or ventral visual areas (Fig.5). Despite their use of the same backbone architecture, the baseline under-performs WhatCNN in predicting responses in ventral visual areas, and under-performs WhereCNN in predicting responses in dorsal visual areas. This result suggests that the interactive and parallel nature of the dual-stream model renders each stream more akin to the functioning of the human brain, surpassing the performance of isolating a single stream. Moreover, WhatCNN or WhereCNN also performs better than AlexNet and comparably with ResNet18 and ResNet34, which are deeper than the architecture of our model. ### Attention-driven eye movements improve encoding Similar to human gaze behavior towards salient objects, our model learns spatial attention to guide fixations for parallel visual processing. In this study, we investigate whether and how the model's ability to predict brain responses depends on its utilization of attention-driven fixations. To examine this, we conduct experiments where the model is allowed to use either attention-driven fixations or random fixations to collect retinal samples, and we evaluate how this choice impacts the model's capability to predict brain responses by calculating \(\Delta r=r^{learned}-r^{random}\) for all voxels, where \(r^{learned}\) and \(r^{random}\) are encoding performances of each voxel using learned or random fixations respectively. As depicted in Fig.6, employing attention-driven fixations leads to higher encoding accuracy by both WhereCNN and WhatCNN compared to the use of random fixations for a majority of visual cortical locations within both the dorsal and ventral streams. Figure 5: WhatCNN (left) or WhereCNN (right) vs. alternative single-stream CNNs. The boxplot shows the encoding performance of different models for ventral or dorsal visual areas. Each dot within the box plot signifies the average prediction accuracy r within a respective ROI in the ventral or dorsal region. Asterisk (*) represents a significant difference by the Wilcoxon signed-rank test (\(\alpha=0.05\)). Figure 6: **Effects of attention-driven eye movements. The use of attention to determine fixations vs. the use of random fixations is evaluated in terms of the resulting difference in the encoding performance by WhereCNN (left) and WhatCNN (right), denoted and color-coded as \(\Delta r_{where}\) and \(\Delta r_{what}\), respectively. Voxels displayed in warm colors indicate that the predictions are more accurate with learned fixations, whereas those in cool colors signify better predictions with random fixations.** Discussion In summary, we introduce a new dual-stream neural network that incorporates the brain's mechanisms for parallel visual processing. The defining features of our model include 1) using retinal transformation to separate complementary inputs to each stream, 2) using different learning objectives to train each stream to learn either spatial attention or object recognition, and 3) controlling sequential fixations for active and interactive visual sensing and processing. We demonstrate that the combination of these features renders the model more akin to the human brain and better predictive of brain responses in humans freely engaged in naturalistic visual environments. Importantly, the two streams in our model differentially explain the two streams in the brain, contributing to the computational understanding as to how and why the brain exhibits and organizes distinct responses and processes along the structurally segregated dorsal and ventral visual pathways. Our findings suggest that the primary factor contributing to the dorsal-ventral functional segregation is the different goals of the dorsal and ventral pathways. That is, the dorsal pathway learns spatial attention to control eye movements [75, 7, 76, 77], while the ventral stream learns object recognition. Although our model demonstrates initial steps to model parallel visual processing in the brain, it has limitations that remain to be addressed in future studies. For one limitation, the model uses different spatial sampling to generate the retinal inputs to the two streams but does not consider different temporal sampling that makes the dorsal stream more sensitive to motion than the ventral stream [38, 40, 39, 41]. For another limitation, the interaction between the two streams is limited to the common fixation that determines the complementary retinal input to each stream. Although attention-driven eye movement is an important aspect of human visual behavior shaping brain responses for both dorsal and ventral streams, the two streams also interact and exchange information at higher levels. The precise mechanisms for dorsal-ventral interactions remain unclear but may be important to understanding human vision or improving brain-inspired computer vision. ## 6 Acknowledgements This research is supported by the Collaborative Research in Computational Neuroscience (CRCNS) program from National Science Foundation (Award#: IIS 2112773) and the University of Michigan.
2307.14531
Controlling the Inductive Bias of Wide Neural Networks by Modifying the Kernel's Spectrum
Wide neural networks are biased towards learning certain functions, influencing both the rate of convergence of gradient descent (GD) and the functions that are reachable with GD in finite training time. As such, there is a great need for methods that can modify this bias according to the task at hand. To that end, we introduce Modified Spectrum Kernels (MSKs), a novel family of constructed kernels that can be used to approximate kernels with desired eigenvalues for which no closed form is known. We leverage the duality between wide neural networks and Neural Tangent Kernels and propose a preconditioned gradient descent method, which alters the trajectory of GD. As a result, this allows for a polynomial and, in some cases, exponential training speedup without changing the final solution. Our method is both computationally efficient and simple to implement.
Amnon Geifman, Daniel Barzilai, Ronen Basri, Meirav Galun
2023-07-26T22:39:47Z
http://arxiv.org/abs/2307.14531v2
# Controlling the Inductive Bias of Wide Neural Networks by Modifying the Kernel's Spectrum ###### Abstract Wide neural networks are _biased_ towards learning certain functions, influencing both the rate of convergence of gradient descent (GD) and the functions that are reachable with GD in finite training time. As such, there is a great need for methods that can modify this _bias_ according to the task at hand. To that end, we introduce Modified Spectrum Kernels (MSKs), a novel family of constructed kernels that can be used to approximate kernels with desired eigenvalues for which no closed form is known. We leverage the duality between wide neural networks and Neural Tangent Kernels and propose a preconditioned gradient descent method, which alters the trajectory of GD. As a result, this allows for a polynomial and, in some cases, exponential training speedup without changing the final solution. Our method is both computationally efficient and simple to implement. Machine Learning, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent Descent, Gradient Descent, Gradient Descent, Gradient Descent Descent, Gradient Descent Descent, Gradient Descent, Gradient Descent, Gradient Descent Descent, Gradient Descent Descent, Gradient Descent Descent, Gradient Descent, Gradient Descent Descent, Gradient Descent, Gradient Descent Descent, Gradient Descent, Gradient Descent Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent Descent, Gradient Descent, Gradient Descent Descent, Gradient Descent, Gradient Descent Descent, Gradient Descent, Gradient Descent Descent, Gradient Descent, Gradient Descent Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent Descent, Gradient Descent, Gradient Descent Descent, Gradient Descent, Gradient Descent, Gradient Descent Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent Descent, Gradient Descent Descent, Gradient Descent, Gradient Descent, Gradient Descent Descent, Gradient Descent, Gradient Descent, Gradient Descent, Gradient Descent Descent, Gradient Descent, Gradient Descent Descent, Gradient Descent Descent, Gradient Descent, Gradient Descent Descent, Gradient Descent Descent, Gradient Descent, Gradient Descent Descent, Gradient Descent, Gradient Descent Descent, Gradient Descent, Gradient Descent Descent, Gradient Descent Descent, Gradient Descent, Gradient Descent Descent, Gradient Descent, Gradient Descent Descent, Gradient Descent, Gradient Descent Descent, Gradient Descent Descent, Gradient Descent, Gradient Descent, Gradient Descent Descent, Gradient Descent, Gradient Descent Descent, Gradient Descent Descent, Gradient Descent Descent, Gradient Descent Descent, Gradient Descent Descent, Gradient Descent Descent, Gradient Descent Descent, Gradient Descent Descent, Gradient Descent Descent, Gradient Descent Descent, Gradient Descent Descent, Gradient Descent Descent, Gradient Descent Descent Descent, Gradient Descent Descent, Gradient Descent Descent, Gradient Descent Descent, Gradient Descent Descent Descent, Gradient Descent Descent, Gradient Descent Descent, Gradient Descent Descent, Gradient Descent Descent, Gradient Descent Descent Descent, Gradient Descent Descent Descent, Gradient Descent Descent, Gradient Descent Descent Descent, Gradient Descent Descent, Gradient Descent Descent Descent, Gradient Descent Descent, Gradient Descent Descent Descent, Gradient Descent Descent Descent, Gradient Descent Descent Descent, Gradient Descent Descent, Gradient Descent Descent Descent Descent, Gradient Descent Descent Descent, Gradient Descent Descent Descent Descent, Gradient Descent Descent Descent Descent Descent, Gradient Descent kernels for which a closed form is unknown (Section 3). 2. We introduce preconditioned gradient descent and prove its convergence for wide neural networks (Section 4.1). 3. We prove that our method is consistent, meaning that the preconditioning does not change the final network prediction on test points (Section 4.2). 4. We provide an algorithm that enables a wide range of spectral bias manipulations, yielding a significant convergence speedup for training wide neural networks. We finally demonstrate this acceleration on synthetic data (Section 4.3). ## 2 Preliminaries and Background We consider positive definite kernels \(\mathbf{k}:\mathcal{X}\times\mathcal{X}\rightarrow\mathbb{R}\) defined over a compact metric space \(\mathcal{X}\) endowed with a finite Borel measure \(\mu\). Given such \(\mathbf{k}\), its corresponding (linear) integral operator \(L_{\mathbf{k}}:L_{\mu}^{2}(\mathcal{X})\to L_{\mu}^{2}(\mathcal{X})\) is defined as \[L_{\mathbf{k}}(f)(\mathbf{x})=\int_{\mathbf{\mathbf{z}}\in\mathcal{X}} \mathbf{k}(\mathbf{x},\mathbf{z})f(\mathbf{z})d\mu(\mathbf{z}).\] This is a compact, positive self-adjoint operator that therefore has an eigen-decomposition of the form \[L_{\mathbf{k}}(f)=\sum_{i\geq 0}\lambda_{i}\langle f,\Phi_{i} \rangle_{\mu}\Phi_{i},\] where the inner product \(\langle,\rangle_{\mu}\) is with respect to \(L_{\mu}^{2}(\mathcal{X})\), and \(\lambda_{i},\Phi_{i}\) are the eigenvalues and eigenfunctions of the integral operator satisfying \[L_{\mathbf{k}}(\Phi_{i})=\lambda_{i}\Phi_{i}.\] According to Mercer's Theorem, \(\mathbf{k}\) can be written using the eigen-decomposition of the integral operator as \[\mathbf{k}(\mathbf{x},\mathbf{z})=\sum_{i\in I}\lambda_{i}\Phi_{i}( \mathbf{x})\Phi_{i}(\mathbf{z}),\ \ \ \mathbf{x},\mathbf{z}\in\mathcal{X}. \tag{1}\] Furthermore, each such kernel is associated with a unique Reproducing Kernel Hilbert Space (RKHS) \(\mathcal{H}_{\mathbf{k}}\subseteq L_{\mu}^{2}(\mathcal{X})\) (which we denote by \(\mathcal{H}\) when the kernel is clear by context), consisting of functions of the form \(f(\mathbf{x})=\sum_{i\in I}\alpha_{i}\Phi_{i}(\mathbf{x})\) whose RKHS norm is finite, i.e., \(\|f\|_{\mathcal{H}}:=\sum_{i\in I}\frac{\alpha_{i}^{2}}{\lambda_{i}}<\infty\). The latter condition restricts the set of functions in an RKHS, allowing only functions that are sufficiently smooth in accordance to the asymptotic decay of \(\lambda_{k}\). For any positive definite kernel there exists a feature map \(\phi:\mathcal{X}\rightarrow\mathcal{H}\) s.t \(\mathbf{k}(\mathbf{x},\mathbf{z})=\langle\phi(\mathbf{x}),\phi(\mathbf{z})\rangle_ {\mathcal{H}}\). As such, we may occasionally call the RKHS \(\mathcal{H}\) the _feature space_ of \(\mathbf{k}\). Given training data \(X=\{\mathbf{x}_{1},...,\mathbf{x}_{n}\}\), \(\mathbf{x}_{i}\in\mathcal{X}\), corresponding labels \(\{y_{i}\}_{i=1}^{n}\), \(y_{i}\in\mathbb{R}\), and a regularization parameter \(\gamma>0\), the problem of _Kernel Ridge Regression (KRR)_ is formulated as \[\min_{f\in\mathcal{H}}\sum_{i=1}^{n}(f(\mathbf{x}_{i})-y_{i})^{2} +\gamma\|f\|_{\mathcal{H}}. \tag{2}\] The solution satisfies \(f(\mathbf{x})=\mathbf{k}_{\mathbf{x}}^{T}(K+\gamma I)^{-1}\mathbf{y}\), where the entries of \(\mathbf{k}_{\mathbf{x}}\in\mathbb{R}^{n}\) are \(\frac{1}{n}\mathbf{k}(\mathbf{x},\mathbf{x}_{i})\), \(K\) is the \(n\times n\) kernel matrix with \(K_{ij}=\frac{1}{n}\mathbf{k}(\mathbf{x}_{i},\mathbf{x}_{j})\), and \(\mathbf{y}=(y_{1},...,y_{n})^{T}\). ## 3 Modified Spectrum Kernels Our aim in this section is to describe and analyze the construction of novel kernels for which no closed form is known. We do so by manipulating the spectrum of existing kernels whose matrix is easy to compute. Since a constructed kernel may not have a closed form, we directly manipulate the kernel matrix of an existing kernel to fit our desired spectrum. The theory in this section refers to arbitrary kernels, and the connection to NTK and wide neural networks is deferred to Sec. 4. **Definition 3.1**.: **Modified Spectrum Kernel (MSK).** Let \(\mathbf{k}(\mathbf{x},\mathbf{z}):=\sum_{k=1}^{\infty}\lambda_{k}\Phi_{k}(\mathbf{ x})\Phi_{k}(\mathbf{z})\) be a Mercer kernel with eigenvalues \(\lambda_{i}\) and eigenfunction \(\Phi_{i}(\cdot)\) and \(g:\mathbb{R}\rightarrow\mathbb{R}\) a function which is non-negative and \(L\)-Lipschitz. The Modified Spectrum Kernel (w.r.t. \(\mathbf{k}\)) is defined as \(\mathbf{k}_{g}(\mathbf{x},\mathbf{z}):=\sum_{k=1}^{\infty}g(\lambda_{k})\Phi_{k}( \mathbf{x})\Phi_{k}(\mathbf{z})\). The MSK has the same eigenfunctions as the source kernel \(\mathbf{k}\), while its eigenvalues are modified by \(g\). Clearly, constructing a closed-form solution to the modified kernel is rarely possible. However, it is possible to approximate the modified kernel efficiently under certain conditions, given the values of the original kernel \(\mathbf{k}\), as proved in Theorem 3.2. **Theorem 3.2**.: _Let \(g,\mathbf{k},\mathbf{k}_{g}\) be as in (3.1) and assume that \(\forall\mathbf{x}\in\mathcal{X},|\Phi_{i}(\mathbf{x})|\leq M\). Let \(K,K_{g}\) be the corresponding kernel matrices on i.i.d samples \(\mathbf{x}_{1},...,\mathbf{x}_{n}\in\mathcal{X}\). Define the kernel matrix \(\tilde{K}_{g}=VDV^{T}\) where \(V=(\mathbf{v}_{1},..,\mathbf{v}_{n})\) with \(\mathbf{v}_{i}\) the 'th eigenvector of \(K\) and \(D\) is a diagonal matrix with \(D_{ii}=g(\hat{\lambda}_{i})\) where \(\hat{\lambda}_{i}\) is the 'th eigenvalue of \(K\). Then, for \(n\rightarrow\infty\)_ \[\left\|\tilde{K}_{g}-K_{g}\right\|_{F}\overset{a.s.}{\rightarrow }0,\] _where a.s. stands for almost surely._ We next provide a proof sketch. The full proof is given in Appendix C. For an eigenfunction \(\Phi\) of \(\mathbf{k}(\mathbf{x},\mathbf{z})\), we let \(\Phi(X):=(\Phi(\mathbf{x}_{1}),\dots,\Phi(\mathbf{x}_{n}))^{T}\in\mathbb{R}^ {n}\) be the evaluation of the eigenfunctions on the data. By the definition of the kernels, \(K=\sum_{k=1}^{\infty}\lambda_{k}\Phi_{k}(X)\Phi_{k}(X)^{T}\), and similarly, \(K_{g}\) can be written as \(K_{g}=\sum_{k=1}^{\infty}g(\lambda_{k})\Phi_{k}(X)\Phi_{k}(X)^{T}\). Since \(\tilde{K}_{g}\) has the eigenvectors of \(K\) with the eigenvalues \(g(\lambda_{k})\), we would like to say that the eigenvalues of \(K_{g}\) are close to \(g(\lambda_{k})\) and that the eigenvectors of \(K\) are close to those of \(K_{g}\). It is already known that the eigenvalues of a kernel matrix converge to those of its integral operator (with the suitable normalization) (Rosasco et al., 2010), and as such, we know that the eigenvalues of \(\tilde{K}_{g}\) should be close to those of \(K_{g}\). The challenge is that the eigenvectors \(\mathbf{v}_{k}\) do not have to be close to \(\Phi_{k}(X)\), the evaluations of the eigenfunctions on the data (for example when there is an eigenvalue of multiplicity greater than 1). This means that the eigenvectors of \(\tilde{K}_{g}\) can be very different from those of \(K_{g}\). We work around this by showing that for large \(n\), if \(\mathbf{v}_{l},..,\mathbf{v}_{d}\) are the eigenvectors of \(K\) corresponding to eigenvalue \(\lambda_{k}\) and \(\Phi\) is some eigenfunction, then \[\sum_{i=l}^{d}(\mathbf{v}_{i}^{T}\Phi(X))^{2}\rightarrow\begin{cases}1\ \ \text{if}\ \Phi\ \text{is an eigenfunction of}\ \lambda_{k}\\ 0\ \ \text{else},\end{cases}\] allowing us to show that the norm between the eigenspaces of \(\tilde{K}_{g}\) and \(K_{g}\) tends to 0. Kernel Construction with MSKs.Generating new kernels from existing ones is a long-standing problem in kernel theory (Saitoh & Sawano, 2016). The classical kernel theory uses arithmetic operations such as addition and multiplication of kernels to generate new kernels with unique RKHSs. Recent papers provided tools to building data dependent kernels based on training points (Simon, 2022; Sindhwani et al., 2005; Ionescu et al., 2017). Nevertheless, there are still many kernels for which a closed form is unknown. MSKs allow extending existing RKHS theory by computing new kernels with predetermined Mercer decomposition even when a closed form is unknown and, specifically, solve KRR with these new kernels. Suppose we would like to solve the problem of KRR as defined in (2). Let \(\mathbf{k}(\mathbf{x},\mathbf{z})=\sum_{k=1}^{\infty}\lambda_{k}\Phi_{k}(\mathbf{ x})\Phi_{k}(\mathbf{z})\) and \(\mathbf{k}_{g}(\mathbf{x},\mathbf{z})=\sum_{k=1}^{\infty}g(\lambda_{k})\Phi_{k}( \mathbf{x})\Phi_{k}(\mathbf{z})\) be two Mercer kernels where \(\mathbf{k}(\mathbf{x},\mathbf{z})\) has a known closed form, whereas \(\mathbf{k}_{g}(\mathbf{x},\mathbf{z})\) does not. Assuming we obtain i.i.d. samples of training points \(\mathbf{x}_{1},..,\mathbf{x}_{n}\) and a test point \(\mathbf{x}\), we can build \(\tilde{K}_{g}\) (as in Theorem 3.2) using the \(n+1\) points \(\mathbf{x}_{1},..,\mathbf{x}_{n},\mathbf{x}\). Then, by a continuity argument, Theorem 3.2 guarantees that the predictor \(f^{*}(\mathbf{x})=[\tilde{K}_{g}]_{n+1,1:n}([\tilde{K}_{g}]_{1:n,1:n}+\gamma I )^{-1}\mathbf{y}\) converges to the KRR prediction with the kernel \(\mathbf{k}_{g}\), where \([\ \cdot\ ]_{,:}\) corresponds to the sub-matrix induced by the specified indices. ## 4 Provable NTK Based Preconditioning for Neural Networks In this section, we develop and analyze a preconditioning scheme for accelerating the convergence rate of gradient descent in the training phase of neural networks while minimizing the Mean Squares Error (MSE) loss. The acceleration is achieved by manipulating the spectrum of the NTK, overcoming the spectral bias of neural networks. We begin by explaining how the convergence rate of neural networks is related to the spectrum of the NTK. Then, we introduce a preconditioning scheme for wide neural networks and prove that it attains a global optimum. We further prove that in the infinite width limit and when training the network to completion, preconditioned and standard gradient descent converge to the same global minimum. We consider a fully connected neural network parameterized as follows: \[\mathbf{g}^{(0)}(\mathbf{x}) =\mathbf{x}\] \[\mathbf{f}^{(l)}(\mathbf{x}) =W^{(l)}\mathbf{g}^{(l-1)}(\mathbf{x})+\mathbf{b}^{(l)}\in\mathbb{ R}^{d_{l}},\ \ \ \ l=1,\ldots L\] \[\mathbf{g}^{(l)}(\mathbf{x}) =\rho\left(\mathbf{f}^{(l)}(\mathbf{x})\right)\in\mathbb{R}^{d_{l }},\ \ \ \ l=1,\ldots L\] \[f(\mathbf{x},\mathbf{w}) =f^{(L+1)}(\mathbf{x})=W^{(L+1)}\cdot\mathbf{g}^{(L)}(\mathbf{x} )+b^{(L+1)}.\] where \(\mathbf{w}\in\mathbb{R}^{p}\) is the set of all the network parameters. We select a simple architecture and note that our results can easily extend to many other architectures. We denote by \(m\) the width of the network and assume that \(d_{1}=d_{2}=..=d_{L}=m\). The activation function is denoted by \(\rho\) and the following quantities \(|\rho(0)|\), \(\left\|\rho^{\prime}\right\|_{\infty}\), and \(\sup_{x\neq x^{\prime}}|\rho^{\prime}(x)-\rho^{\prime}(x^{\prime})|/|x-x^{ \prime}|\) should be finite. We use standard initialization that assures that the network is trained in the NTK regime (see more details in Appendix A). We denote the vector of labels for all the data points \((y_{1},\ldots,y_{n})\) by \(\mathbf{y}\in\mathbb{R}^{n}\) and the vector of network predictions \(f(\mathbf{x}_{i},\mathbf{w})\) by \(f(X,\mathbf{w})\in\mathbb{R}^{n}\). The residual at time \(t\) is \(\mathbf{r}_{t}:=f(X,\mathbf{w}_{t})-\mathbf{y}\). Letting \(\mathcal{L}\) be the squared error loss, \(\mathcal{L}(\mathbf{w}_{t})=\frac{1}{2}\left\|\mathbf{r}_{t}\right\|^{2}\), a gradient descent iteration for optimizing \(\mathbf{w}\in\mathbb{R}^{p}\) is given by \[\mathbf{w}_{t+1}-\mathbf{w}_{t}=-\eta\nabla_{\mathbf{w}}\mathcal{L}(\mathbf{w} _{t})=-\eta\nabla_{\mathbf{w}}f(X,\mathbf{w}_{t})^{T}\mathbf{r}_{t}, \tag{3}\] where \(\eta\) is the learning rate, and \(\nabla_{\mathbf{w}}f(X,\mathbf{w}_{t})\in\mathbb{R}^{n\times p}\) is the Jacobian of the network. The empirical NTK matrix at time \(t\), \(K_{t}\in\mathbb{R}^{n\times n}\), and the NTK matrix, \(K\in\mathbb{R}^{n\times n}\), are defined as \[K_{t}= \frac{1}{m}\nabla_{\mathbf{w}}f(X,\mathbf{w}_{t})\nabla_{\mathbf{ w}}f(X,\mathbf{w}_{t})^{T} \tag{4}\] \[K= \text{lim}_{m\rightarrow\infty}K_{0}. \tag{5}\] (Arora et al., 2019) showed that for a wide neural network with ReLU activation, small initialization, and a small learning rate, it holds that for every \(\epsilon>0\), the residual at time evolves with the following linear dynamics \[\left\|\mathbf{r}_{t}\right\|=\left\|(I-\eta K)^{t}\mathbf{y}\right\| \pm\epsilon=\sqrt{\sum_{i=1}^{n}(1-\eta\lambda_{i})^{2t}(\mathbf{v}_{i}^{T} \mathbf{y})^{2}}\pm\epsilon, \tag{6}\] where \(\{\lambda_{i}\}_{i=1}^{n}\) and \(\{\mathbf{v}_{i}\}_{i=1}^{n}\) respectively are the eigenvalues and eigenvectors of the NTK matrix \(K\). Eq. (6) reveals the relation between the inductive bias of neural networks and the spectrum of the NTK matrix (Basri et al., 2020). Specifically, to learn an eigen-direction \(\mathbf{v}_{i}\) of a target function within accuracy \(\delta>0\), it is required that \((1-\eta\lambda_{i})^{t}<\delta+\epsilon\). When the learning rate is sufficiently small to imply convergence, \(0<\eta<\frac{2}{\lambda_{i}}\), the number of iterations needed is \[t>-\log(\delta+\epsilon)/\eta\lambda_{i}=O\left(\frac{\lambda_{1}}{\lambda_{ i}}\right).\] The eigenvalues and eigenvectors of \(K\) depend on the data distribution and are not yet fully characterized for arbitrary distributions (e.g., (Basri et al., 2020)). In the case of a fully connected network with ReLU activation and with data points distributed uniformly on the sphere \(\mathbb{S}^{d-1}\), the eigenvectors are discretizations of the spherical harmonics and the eigenvalues asymptotically decay as \(\lambda_{k}\approx k^{-d}\), where \(k\) is the frequency (Basri et al., 2020; Bietti and Bach, 2020). In this scenario, learning a high-frequency eigenvector with gradient descent is computationally prohibitive, even for a low-dimension sphere. With other activation functions, the asymptotic decay of the eigenvalues might be even exponential (Murray et al., 2022), yielding an infeasible computational learning cost for learning high frequency target functions. ### Preconditioned Gradient Descent To accelerate the convergence of standard gradient descent (3), we propose a _preconditioned gradient descent_ (PGD). The update rule of our PGD is given by \[\mathbf{w}_{t+1}=\mathbf{w}_{t}-\eta\nabla_{\mathbf{w}}f(X,\mathbf{w}_{t})^{T }S\mathbf{r}_{t}, \tag{7}\] where \(S\in\mathbb{R}^{n\times n}\) is a preconditioning matrix that satisfies \(S\succ 0\). In contrast to standard preconditioning techniques, which multiply the complete gradient with a preconditioning matrix, we manipulate only the network's gradient, hence reducing the cost per iteration for a generic preconditioner from \(p^{2}\) (where \(p\), the number of parameters in the network, is usually huge) to \(n^{2}\), where in the over-parameterized case \(n\ll p\). We next show an analogous result to the linear dynamics of the form of (6) for PGD. The key difference, is that carefully choosing \(S\) enables to manipulate the dynamics of gradient descent almost arbitrarily. **Theorem 4.1**.: _Let \(\eta_{0},\delta_{0},\epsilon>0\), \(S\in\mathbb{R}^{n\times n}\) such that \(S\succ 0\) and \(\eta_{0}<\frac{2}{\lambda_{min}(KS)+\lambda_{max}(KS)}\). Then, there exists \(N\in\mathbb{N}\) such that for every \(m\geq N\), the following holds with probability at least \(1-\delta_{0}\) over random initialization when applying preconditioned GD with learning rate \(\eta=\eta_{0}/m\)_ \[\mathbf{r}_{t}=(I-\eta_{0}KS)^{t}\mathbf{y}\pm\xi(t),\] _where \(\left\|\xi\right\|_{2}\leq\epsilon\)._ Recall that we assume \(K\succ 0\) and \(S\succ 0\), so while \(KS\) is not necessarily positive definite or symmetric, it has positive real eigenvalues. As such, the term \(\frac{2}{\lambda_{min}(KS)+\lambda_{max}(KS)}\) is positive and defines the maximal feasible learning rate. The formal proof of Theorem 4.1 is given in Appendix A, and here we give some key points of the proof. The proof relies on Lemma 4.2, which shows that PGD finds a global minimum in which the weights are close to their initial values. In particular, for any iteration \(t\), \(K_{t}S\approx K_{0}S\approx KS\). Based on the results of Lemma 4.2, Theorem 4.1 carefully bounds the distance \(\xi(t)\) between \(\mathbf{r}_{t}\) and the linear dynamics \((I-\eta_{0}KS)^{t}\mathbf{y}\). **Lemma 4.2**.: _For \(\delta_{0}>0\), \(\frac{2}{\lambda_{min}(KS)+\lambda_{max}(KS)}>\eta_{0}\) and \(S\) such that \(S\succ 0\), there exist \(C>0\), \(N\in\mathbb{N}\) and \(\kappa>1\), such that for every \(m\geq N\), the following holds with probability at least \(1-\delta_{0}\) over random initialization. When applying preconditioned gradient descent as in (7) with learning rate \(\eta=\eta_{0}/m\)_ 1. \(\left\|\mathbf{r}_{t}\right\|_{2}\leq\left(1-\frac{\eta\lambda_{min}}{3} \right)^{t}C\)__ 2. \(\sum_{j=1}^{t}\left\|\mathbf{w}_{j}-\mathbf{w}_{j-1}\right\|_{2}\leq\frac{3 \kappa C}{\lambda_{min}}m^{-1/2}\)__ 3. \(\sup_{t}\left\|(K_{0}-K_{t})S\right\|_{F}\leq\frac{6\kappa^{3}C}{\lambda_{min }}m^{-1/2}\)_,_ _where \(\lambda_{min}\) is the minimal eigenvalue of \(KS\)._ The full proof of Lemma 4.2 is given in Appendix A. Theorem 4.1 implies that the dynamics of preconditioned gradient descent are characterized by \(KS\) instead of \(K\). In particular, if \(KS\) is symmetric, PGD follows the dynamics \[\left\|\mathbf{r}_{t}\right\|=\left\|(I-\eta KS)^{t}\mathbf{y}\right\|\pm \epsilon=\sqrt{\sum_{i=1}^{n}(1-\eta\hat{\lambda}_{i})^{2t}(\hat{\mathbf{v}}_{ i}^{T}\mathbf{y})^{2}}\pm\epsilon, \tag{8}\] where now, in contrast to (6), \(\hat{\lambda}_{i},\hat{\mathbf{v}}_{i}\) are the eigenvalues and eigenvectors of \(KS\). This enables to manipulate the convergence behaviour in two ways. The first is to reduce the condition number of \(K\) and therefore achieve a significant improvement in the convergence rate. The second is to change certain eigenvalues and therefore manipulate the relative convergence of each eigenfunction of the NTK. where now, in contrast to (6), \(\hat{\lambda}_{i},\hat{\mathbf{v}}_{i}\) are the eigenvalues and eigenvectors of \(KS\). As such, the choice of \(S\) determines the rate at which the network converges to any specific target function. The results of Zhang et al. (2019) and Cai et al. (2019) can be viewed as a special case of (8). Specifically, these works characterize the convergence of an approximate second-order method (Gauss-Newton) when applied to a wide, two-layer network. In this case, the update rule is of the form \[\mathbf{w}_{t+1}-\mathbf{w}_{t}=-\eta F(\mathbf{w}_{t})^{-1}\nabla_{\mathbf{w }}\mathcal{L}(\mathbf{w}_{t}),\] with \(F\) being the Fisher information matrix associated with the network's predictive distribution. Their derivation leads to similar convergence results as shown in (8) but is limited to the case of \(S=K_{t}^{-1}\). We show in Sec. 4.3 how \(S\) can be chosen to reduce by a polynomial (or even exponential) factor the number of iterations required to converge in the directions corresponding to small eigenvalues of \(K\). This is highly beneficial when the projections of the target function on the eigenvectors of \(K\), \((\hat{\mathbf{v}}_{i}^{T}\mathbf{y})\) are relatively large in directions corresponding to small eigenvalues. For example, for image reconstruction or rendering, this equates to learning more efficiently the fine details, which correspond to high frequencies in the image (Tancik et al., 2020). Another example arises in Physics Informed Neural Networks (PINN), which were shown to suffer significantly from the slow convergence rate in the directions corresponding to small eigenvalues (Wang et al., 2022). ### Convergence Analysis In this section, we characterize the resulting prediction function of the network on unseen test points and show that PGD generates a consistent prediction function in the following sense. At convergence, the prediction function of a network trained with PGD is close to the prediction function of a network trained with standard GD. We start by defining a preconditioned loss, \(\mathcal{L}_{S}(f,\mathbf{w})\), which modifies the standard MSE loss \[\mathcal{L}_{S}(f,\mathbf{w})=\frac{1}{2}\left\|\hat{S}^{1/2}(f(X,\mathbf{w})- \mathbf{y})\right\|_{2}^{2}, \tag{9}\] where \(S\succ 0\) is the preconditioning matrix. An iteration of standard GD w.r.t \(\mathcal{L}_{S}(f,\mathbf{w})\) yields \[\mathbf{w}_{t+1}-\mathbf{w}_{t}=-\eta\nabla_{\mathbf{w}}\mathcal{L}_{S}(f, \mathbf{w}_{t})=-\eta\nabla_{\mathbf{w}}f(X,\mathbf{w}_{t})^{T}S\mathbf{r}_{ t}, \tag{10}\] which is equivalent to a PGD iteration (7) with the standard MSE loss. This has two implications. First, it implies that PGD can easily be implemented by simply modifying the loss function. Second, it enables us to analyze the prediction function generated by PGD. Specifically, given an initialization \(\mathbf{w}_{0}\in\mathbb{R}^{p}\), let \(\phi(\mathbf{x}):=\nabla f(\mathbf{x},\mathbf{w}_{0})\) and \(h(\mathbf{x},\mathbf{w}^{\prime}):=\langle\mathbf{w}^{\prime},\phi(\mathbf{x })\rangle\). For simplicity, we denote \(h(X,\mathbf{w}^{\prime}):=(h(\mathbf{x}_{1},\mathbf{w}^{\prime}),\ldots,h( \mathbf{x}_{n},\mathbf{w}^{\prime}))^{T}\in\mathbb{R}^{n}\). The minimizer of the kernel ridge regression objective with respect to the preconditioned loss is defined as \[\mathbf{w}_{\gamma}^{*}:=\operatorname*{arg\,min}_{\mathbf{w}^{\prime}\in \mathbb{R}^{p}}\frac{1}{2}\left\|S^{1/2}(h(X,\mathbf{w}^{\prime})-\mathbf{y} )\right\|_{2}^{2}+\frac{1}{2}\gamma\left\|\mathbf{w}^{\prime}\right\|_{2}^{2}, \tag{11}\] and the minimizer of a kernel ridge regression with respect to the standard MSE loss is defined as \[\mathbf{w}_{\gamma}^{**}:=\operatorname*{arg\,min}_{\mathbf{w}^{\prime}\in \mathbb{R}^{p}}\frac{1}{2}\left\|(h(X,\mathbf{w}^{\prime})-\mathbf{y})\right\| _{2}^{2}+\frac{1}{2}\gamma\left\|\mathbf{w}^{\prime}\right\|_{2}^{2}. \tag{12}\] We denote by \(\mathbf{w}^{*}\) and \(\mathbf{w}^{**}\) the limits of \(\mathbf{w}_{\gamma}^{*}\) and \(\mathbf{w}_{\gamma}^{**}\), respectively, when \(\gamma\to 0\). In Lemma 4.3 we show that the two minimizers are equal, which means that the preconditioned loss does not change the prediction function in kernel regression. For a given learning rate \(\eta\) and loss \(\mathcal{L}_{S}\), \(h\) can be optimized through gradient descent with respect to the loss \(\mathcal{L}_{S}\) via the iterations \[\mathbf{w}_{0}^{\prime}=0\quad;\quad\mathbf{w}_{t+1}^{\prime}=\mathbf{w}_{t}^ {\prime}-\eta\nabla\mathcal{L}_{S}(h,\mathbf{w}_{t}^{\prime}). \tag{13}\] We show in Lemma 4.3 that this iterative procedure yields a prediction function that remains close to the neural network prediction throughout PGD. **Lemma 4.3**.: 1. _Let_ \(\mathbf{w}_{0}\in\mathbb{R}^{p}\) _and_ \(\phi(\mathbf{x}):=\nabla f(\mathbf{x},\mathbf{w}_{0})\)_, it holds that_ \(\mathbf{w}^{*}=\mathbf{w}^{**}\)_._ 2. _Let_ \(\delta_{0}>0\)_,_ \(\epsilon>0\)_, a test point_ \(\mathbf{x}\in\mathbb{R}^{d}\) _and_ \(T>0\) _number of iteration. Under the conditions of Theorem_ 4.1_,_ \(\exists N\in\mathbb{N}\) _s.t_ \(\forall m>N\)_, it holds with probability at least_ \(1-\delta_{0}\) _that_ \[|h(\mathbf{x},\mathbf{w}_{T}^{\prime})-f(\mathbf{x},\mathbf{w}_{T})|\leq\epsilon,\] _where_ \(\mathbf{w}^{\prime}\) _is as in (_13_) and_ \(f\) _is optimized with PGD._ The full proof of Lemma 4.3 can be found in Appendix B. Point (1) is proved by deriving \(\mathbf{w}_{\gamma}^{*}\) in closed form, i.e., \(\mathbf{w}_{\gamma}^{*}=\sum_{i=1}^{n}\alpha_{i}^{*}\phi(\mathbf{x}_{i})\), with \[\alpha^{*}=(K_{0}+\gamma S^{-1})^{-1}\mathbf{y}.\] This serves as a generalization of the standard kernel ridge regression solution, which is obtained by substituting \(S=I\). Therefore, using the preconditioned loss yields a corresponding change of the regularization. When taking \(\gamma\to 0\), the solution becomes equivalent to that of the standard kernel ridge regression problem. Point (2) states that in the limit of infinite width, the value of \(f(\cdot,\mathbf{w}_{T})\) at a test point is very close to \(h(\cdot,\mathbf{w}_{T}^{\prime})\). We note that as \(\mathcal{L}_{S}\) is convex, \(h(\mathbf{x},\mathbf{w}_{T}^{\prime})\) approaches \(h(\mathbf{x},\mathbf{w}^{*})\) for sufficiently large \(T\). By combining these two points we obtain that, with sufficiently many iterations and large width, \(f\) well approximates the solution of the standard kernel ridge regression problem, and thus of the standard non-preconditioned gradient descent on the network itself (Lee et al., 2019). ### An Algorithm for Modifying the Spectral Bias In light of Theorem 4.1, \(S\) can be chosen to mitigate any negative effect arising from NTK. Specifically, we can modify the spectral bias of neural networks in a way that enables them to efficiently learn the eigen-directions of the NTK that correspond to small eigenvalues. To this end, we use a MSK based precondition, as outlined in the PGD algorithm 1. First, given the NTK matrix \(K\) of size \(n\times n\), we construct a pre-conditioner from \(K\) by applying a spectral decomposition, obtaining the top \(k+1\) eigenvalues and eigenvectors. We denote the top \(k+1\) eigenvalues by \(\lambda_{1}\geq\ldots\geq\lambda_{k}\geq\lambda_{k+1}>0\), and their corresponding eigenvectors by \(\mathbf{v}_{1},\ldots,\mathbf{v}_{k},\mathbf{v}_{k+1}\). The proposed pre-conditioner is of the form \[S=I-\sum_{i=1}^{k}\left(1-\frac{g(\lambda_{i})}{\lambda_{i}}\right)\mathbf{v} _{i}\mathbf{v}_{i}^{T}. \tag{14}\] It can be readily observed that \(S\) and \(K\) share the same eigenvectors, and as long as \(g(\lambda_{i})>0\) then \(S\succ 0\) and its eigenvalues given in descending order are: \[\left[1,\ldots,1,\frac{g(\lambda_{k})}{\lambda_{k}},\ldots,\frac{g(\lambda_{ 1})}{\lambda_{1}}\right].\] Since \(S\) and \(K\) share the same eigenvectors, it holds that the eigenvalues of \(KS\) are \[[g(\lambda_{1}),\ldots,g(\lambda_{k}),\lambda_{k+1},\lambda_{k+2},..,\lambda_{ n}].\] The connection with Theorem 3.2 can now be clearly seen, as the product \(KS\) yields a MSK matrix, and therefore approximates a kernel that shares the same eigenfunctions of \(\mathbf{k}\) and its eigenvalues are modified by \(g\) (where for \(\lambda\geq\lambda_{k+1}\) we let \(g(\lambda)=\lambda\)). Together with Theorem 4.1, the dynamics of the neural network are controlled by this modified kernel, and as such we obtain a way to alter the spectral bias of neural networks. As an example, we may set \(g(\lambda_{i})=\lambda_{k+1}\), \(1\leq i\leq k\), making the top \(k+1\) eigenvalues equal to each other. Then, due to (8), by picking the learning rate \(\eta=\frac{2}{\lambda_{k+1}+\lambda_{n}}\), we get that for every \(i\leq k+1\), \(\mathbf{v}_{i}\) can be learnt in \(O(1)\) time (number of iterations). This starkly contrasts the typical spectral bias of neural networks, under which for large \(i\), learning \(\mathbf{v}_{i}\) may be infeasible in polynomial time. For example, when the activation function \(\rho\) is tanh, Murray et al. (2022) showed that \(\lambda_{k}=O\left(k^{-d+1/2}e^{-\sqrt{k}}\right)\). Applying (6), vanilla GD requires \(O\left(k^{d+1/2}e^{\sqrt{k}}\right)\) iterations to converge, exponentially slower in \(k\) compared to PGD. We leave the choice of \(k\), the number of modified eigenvalues, to the practitioners. Typically, the NTK matrix will be ill-conditioned with the smallest eigenvalues very close to 0. Thus, \(k\) may be chosen in a way that helps avoid these numeric instabilities. Furthermore, since only the top \(k\) eigenvalues and eigenvectors need to be calculated, choosing a small \(k\) allows for a very efficient calculation of \(S\). By contrast, choosing \(k=n\) implies that \(S=K^{-1}\). Previous work showed that the networks' width in the NTK regime should generally exceed \(m\sim n^{4}\)(Song and Yang, 2019). Therefore, in this regime inverting \(K\) or calculating its eigenvalues (\(O(n^{3})\) operations) is cheaper than computing the gradient (\(O(n^{4})\) operations). Our method is also significantly more efficient than a standard preconditioner matrix whose size is \(\sim L^{2}m^{2}\sim L^{2}n^{8}\). Furthermore, in practice, one may choose \(k\), the number of eigenvalues to modify, to be small, leading to further speedups. **Experiments**. We validated our results numerically by tracking the speed of convergence for a neural network both with and without a preconditioner. We generated inputs from a uniform distribution on the circle, \(\mathbf{x}_{i}\sim U(\mathbb{S}^{1})\). With each input we associated a target value \(y_{i}\) by taking a Fourier component of frequency \(k\) (we repeated this experiment with different values of \(k\)), i.e., if \(\mathbf{x}_{i}=(\cos(\theta),\sin(\theta))^{T}\) then \(y_{i}=\sin(k\theta)\). Note that under the uniform distribution on the circle, the Fourier components are the eigenfunctions of the integral operator of NTK for fully connected networks (Basri et al., 2019). We then trained a fully connected network to regress the target function. For efficiency, we trained the network with stochastic gradient descent (SGD). The preconditioner \(S\) is chosen to be either \(I_{n}\) (no precon ditioning), \(K^{-1}\) (inverse NTK matrix), or \(K_{t}^{-1}\) (inverse empirical NTK matrix). Figure 1 shows that without preconditioning, the number of standard GD iterations is roughly quadratic in the frequency of the target function and quickly reaches the iteration limit. In contrast, using preconditioners based on either \(K\) or \(K_{t}\) boosts the convergence, yielding a near-constant number of iterations, irrespective of the frequency of the target function. It can be seen that without preconditioning, the number of standard GD iterations is roughly quadratic in the frequency of the target function and quickly reaches the iteration limit. In contrast, using preconditioners based on either \(K\) or \(K_{t}\) boosts the convergence, yielding a near constant number of iterations, irrespective of the frequency of the target function. The lower panel in Figure 1 also shows a convergence plot for a few different functions. ## 5 Related Works A long string of works established the connection between kernel regression and neural networks. Early works considered a Bayesian inference setting for neural networks, showing that randomly initialized networks are equivalent to Gaussian processes (Williams, 1997; Neal, 2012). In this direction, Cho and Saul (2009) introduced the Arc-cosine kernel, while Daniely et al. (2016) studied general compositional kernels and its relation to neural networks. Recently, a family of kernels called the Neural Tangent Kernels (NTK) was introduced (Jacot et al., 2018; Allen-Zhu et al., 2019; Arora et al., 2019). These papers proved that training an over-paramterized neural network is equivalent to using gradient decent to solve kernel regression with NTK. Follow-up works defined analogous kernels for residual networks (Huang et al., 2020), convolutional networks (Arora et al., 2019; Li et al., 2019), and other standard architectures (Yang, 2020). Subsequent work used the NTK theory to characterize the spectral bias of neural networks. Bach (2017); Basri et al. (2019); Cao et al. (2019); Bietti and Bach (2020); Xu et al. (2019) have studied the eigenfunctions and eigenvalues of NTK under the uniform distribution and further showed that fully connected neural networks learn low-frequency functions faster than higher-frequency ones. Basri et al. (2020) further derived the eigenfunctions of NTK with non-uniform data distribution. Yang and Salman (2019); Misiakiewicz and Mei (2021) analyzed the eigenvalues of NTK over the Boolean cube. More recent studies investigated this bias with other network architectures, including fully-connected ResNets (Belfer et al., 2021; Tirer et al., 2022), convolutional networks (Geifman et al., 2022; Cagnetta et al., 2022; Xiao, 2022), and convolutional ResNets (Barzilai et al., 2022). (Murray et al., 2022) characterized the spectrum of NTK using its power series expansion. Preconditioning is a widely used approach to accelerating convex optimization problems. A preconditioner is typically constructed using the inverse of the Hessian or its approximation (Nocedal and Wright, 1999) to improve the condition number of the problem. Recent works tried to improve the condition number of kernel ridge regression. Ma and Belkin (2017); Ma et al. (2018) suggested using a left preconditioner in conjunction with Richardson iterations. Another line of work analyzed the speed of convergence of an approximate second order method for two-layer neural networks (Zhang et al., 2019; Cai et al., 2019). They showed that natural gradient descent improves convergence in a factor proportional to the condition number of the NTK Gram matrix. Figure 1: Numerical validation. Top: The number of iterations required to learn different Fourier components as a function of frequency. Standard SGD is shown in blue, and (stochastic) PGD with a preconditioner derived from the NTK matrix \(K\) and the empirical NTK \(K_{t}\) respectively are shown in green and orange. Bottom: Training curves with four different frequencies (\(k=5,7,10,12\)). The graphs show the MSE loss as a function of iteration number with stochastic GD and PGD. Several studies aim to construct preconditioners for neural networks. Carlson et al. (2015) built a diagonal preconditioner based on Adagrad and RMSProp updates. Other heuristic preconditoiners use layer-wise adaptive learning rates (You et al., 2017, 2019). In this line of work, it is worth mentioning (Lee et al., 2020), who used the convergence results of (Arora et al., 2019) to incorporate leverage score sampling into training neural networks. Amari et al. (2020) studied the generalization of overparameterized ridgeless regression under a general class of preconditioners via the bias-variance trade-off. Past studies explored the concept of data-dependent kernels. Simon (2022) suggested using the posterior of the target function to produce a new type of data-dependent kernel. Sindhwani et al. (2005) studied a wide class of kernel modifications conditioned on the training data and explored their RKHS. Ionescu et al. (2017) extended this method to build a new class of kernels defined by multiplying the random feature approximation with a weighted covariance matrix. Kennedy et al. (2013) constructed a new family of kernels for a variety of data distributions using the Spherical Harmonic functions on the 2-Sphere. ## 6 Conclusion In this work we addressed the problem of manipulating the spectral bias of neural networks. We formulated a unique preconditioning scheme which enables manipulating the speed of convergence of gradient descent in each eigen-direction of the NTK. This preconditioning scheme can be efficiently implemented by a slight modification to the loss function. Furthermore, for sufficient training time and width, we showed that the predictor obtained by standard GD is approximately the same as that of PGD. We also showed how to construct novel kernels with nearly arbitrary eigenvalues through the use of kernel spectrum manipulations. Our theory is supported by experiments on synthetic data. In future work we plan to explore other forms of spectral manipulations and apply our method in real-world scenarios. ## Acknowledgements Research at the Weizmann Institute was partially supported by the Israel Science Foundation, grant No. 1639/19, by the Israeli Council for Higher Education (CHE) via the Weizmann Data Science Research Center and by research grants from the Estate of Tully and Michele Plesser and the Anita James Rosen Foundation.
2310.09622
Neural Network for valuing Bitcoin options under jump-diffusion and market sentiment model
Cryptocurrencies and Bitcoin, in particular, are prone to wild swings resulting in frequent jumps in prices, making them historically popular for traders to speculate. A better understanding of these fluctuations can greatly benefit crypto investors by allowing them to make informed decisions. It is claimed in recent literature that Bitcoin price is influenced by sentiment about the Bitcoin system. Transaction, as well as the popularity, have shown positive evidence as potential drivers of Bitcoin price. This study considers a bivariate jump-diffusion model to describe Bitcoin price dynamics and the number of Google searches affecting the price, representing a sentiment indicator. We obtain a closed formula for the Bitcoin price and derive the Black-Scholes equation for Bitcoin options. We first solve the corresponding Bitcoin option partial differential equation for the pricing process by introducing artificial neural networks and incorporating multi-layer perceptron techniques. The prediction performance and the model validation using various high-volatile stocks were assessed.
Edson Pindza, Jules Clement Mba, Sutene Mwambi, Nneka Umeorah
2023-10-14T17:08:00Z
http://arxiv.org/abs/2310.09622v1
# Neural Network for valuing Bitcoin options under jump-diffusion and market sentiment model ###### Abstract Cryptocurrencies and Bitcoin, in particular, are prone to wild swings resulting in frequent jumps in prices, making them historically popular for traders to speculate. A better understanding of these fluctuations can greatly benefit crypto investors by allowing them to make informed decisions. It is claimed in recent literature that Bitcoin price is influenced by sentiment about the Bitcoin system. Transaction, as well as the popularity, have shown positive evidence as potential drivers of Bitcoin price. This study considers a bivariate jump-diffusion model to describe Bitcoin price dynamics and the number of Google searches affecting the price, representing a sentiment indicator. We obtain a closed formula for the Bitcoin price and derive the Black-Scholes equation for Bitcoin options. We first solve the corresponding Bitcoin option partial differential equation for the pricing process by introducing artificial neural networks and incorporating multi-layer perceptron techniques. The prediction performance and the model validation using various high-volatile stocks were assessed. **Keywords**: Jump-diffusion model \(\cdot\) Cryptocurrencies \(\cdot\) PDE \(\cdot\) Bitcoin \(\cdot\) Black-Scholes equation \(\cdot\) Artificial neural network. **JEL**: C15 C45 C53 G17. ## 1 Introduction [44],[39],[8], [15] Bitcoin, a decentralized network-based digital currency and payment system, is a special type of cryptocurrency developed in 2009 [36] by a person or a group of persons known under the name of Satoshi Nakamoto. The soar in bitcoin appreciation has been accompanied by high uncertainty and volatility, which surrounds future prices, and this has attracted rapidly increasing research into this digital asset. Policymakers globally are concerned whether bitcoin is decentralized and unregulated and whether it could be a bubble [7] which threatens the stability of a given financial system. Regardless of the speculation, traders are still interested in the capacity of Bitcoin to generate more returns and the use of bitcoin derivatives as a risk management and diversification tool. Blockchain is the underlying technology that powers Bitcoin by recording transactions in a distributive manner, removing alteration and censorship. Following the success of Bitcoin and its growing community, many other alternatives to Bitcoin have emerged. There are more than 5000 tradable cryptocurrencies 1 with a total market capitalization of USD 248 billion at the time of this writing (see [54, 55] for further background on Bitcoin and its technology). On the one hand, the cryptocurrency market is known to be highly volatile ([12, 23]) due to its sensibility to new information, whether fundamental or speculative [7] since it does not rely on the stabilizing policy of a central bank. On the other hand, the relative illiquidity of the market with no official market makers makes it fundamentally fragile to large trading volumes and market imperfections and thus more prone to large swings than other traded assets, see [43]. This concept results in frequent jumps of larger amplitude than what a continuous diffusion process can explain. Due to its local Markov property, i.e., the asset price changes only by a small amount in a short interval of time. When analyzing cryptocurrency data, it is interesting to consider processes that allow for random fluctuations that have more than a marginal effect on the cryptocurrency's price. Such a stochastic process that enables us to incorporate this type of effect is the jump process. This process allows the random fluctuations of the asset price to have two components, one consisting of the usual increments of a Wiener process; the second provides for "large" jumps in the asset price from time to time. Shortly after the development of the Black-Scholes option valuation formula, Merton [35] developed a jump-diffusion model to account for the excess kurtosis and negative skewness observed in log-return data (see, [32]). This jump process is appended to the Black-Scholes geometric stochastic differential equation. Several studies have used the daily bitcoin data to document the impact of jump as a crucial feature of the cryptocurrency dynamics. Chaim and Fry [6] observed that jumps associated with bitcoin volatility are permanent, whereas the jumps to mean returns are said to have contemporaneous effects. The latter equally capture large price bubbles, mainly negative, and are often associated with hacks and unsuccessful fork attempts in the cryptocurrency markets. Hillard and Ngo [17] further investigated the characteristics of bitcoin prices and derived a model which incorporates both jumps and stochastic convenience yield. The result was tested with data obtained from the Deribit exchange, and they observed that modelling bitcoin prices as a jump-diffusion model outperformed the classical Black-Scholes models. Philippas _et al._[41] observed that during periods of high uncertainty, some informative signals, which are proxied by Google search volume and Twitter tweets, have a partial influence on Bitcoin prices and price jumps. In recent years, the focus has been on identifying the main drivers of Bitcoin price evolution in time. Many researchers have assigned the high volatility in Bitcoin prices to the sentiment and popularity of the Bitcoin system. Though these are not directly observable, they may be considered as indicators from the transaction volumes or the number of Google searches or Wikipedia requests about the topic, see for example, Kristoufek [27, 28], Kim et al. [26] and [4]. Authors in [4] use a Bitcoin sentiment measure from Sentdex.com and develop a discrete-time model to show that excessive confidence in the system may boost a bubble in the Bitcoin system. These sentiment-based data were collected through Natural Language Processing techniques to identify a string of words conveying positive, neutral or negative sentiment on Bitcoin. Furthermore, the authors in [9] introduce a bivariate model in continuous time to describe both the dynamics of the Bitcoin sentiment indicator and the corresponding Bitcoin price. By fitting their bivariate model to market data, they consider both the volume and the number of Google searches as proxies for the sentiment factor. While traditional financial theory relies on assumptions of market efficiency, normally distributed returns, and no-arbitrage, emerging research suggests cryptocurrency markets exhibit different characteristics. These markets appear prone to inefficiencies, fat-tailed non-normal dis tributions, and frequent arbitrage opportunities according to Kabasinskas and Sutiene [22]. For example, the extreme volatility and relative illiquidity of cryptocurrencies can lead to dislocations between markets where arbitrageurs can profit. Additionally, the return distributions tend to exhibit higher kurtosis and skewness than normal distributions. However, despite violating some traditional assumptions, jump-diffusion models can still provide a useful starting point for modelling cryptocurrency dynamics. The jumps can account for extreme price fluctuations beyond what continuous diffusion alone predicts. While the model may require modifications over time as more data becomes available, it captures key features like volatility clustering and significant outliers. The sentiment indicator variable also represents an initial attempt to incorporate a behavioural factor affecting prices. Our technique incorporates the one similar to Cretarola _et al._[9], who developed a continuous bivariate model that described the bitcoin price dynamics as one factor, and a sentiment indicator as the second factor. We further added a jump-diffusion component to the SDE with the aim of capturing the occurrence of rare or extreme events in the bitcoin price return. Furthermore, we introduce the artificial neural network and propose a trial solution that solves the associated Black-Scholes partial differential equation (PDE) for the bitcoin call options with European features. This concept is equally different from the univariate jump-diffusion model used, for example, by Chen and Huang (2021). We further implemented the number of Google searches as a Bitcoin sentiment indicator in this paper. This choice is due to their unique transparency in contrast to other social media-driven measures, and they have the tendency to gauge behaviour instead of searching for it. Therefore, using search-based data as sentiment indices has the potential to reveal the underlying beliefs of populations directly. In this paper, we develop an initial modelling framework using a bivariate jump-diffusion model and sentiment indicator. This provides a foundation for pricing and derivatives valuation in cryptocurrency markets. We acknowledge the model's limitations per the evolving understanding of these new markets. As future research expands knowledge of distributional properties, market microstructure issues, and other intricacies, the modelling approach can be enhanced. Nonetheless, our proposed model offers an initial step toward financial engineering in the cryptocurrency space. To this effect, the significant contributions of this paper are highlighted as follows: * We present a bivariate jump-diffusion model to describe the dynamics of the Bitcoin sentiment indicator, which consists of volumes or Google searches and the corresponding Bitcoin price. * We derive a closed-form formula for the Bitcoin price and the corresponding Black-Scholes equation for Bitcoin options valuation. * The corresponding bitcoin option PDE is solved using the artificial neural network, and the proposed model was validated using data from highly volatile stocks. The rest of the paper is organized as follows: Section 2 introduces the methodology and highlights the strengths and the limitations of the proposed model. Section 3 describes the concept of the artificial neural network, as well as its applications in solving the option pricing differential equations, Section 4 discusses the numerical implementation findings, and the last section concludes the work. ## 2 Methodology Jump-diffusion models are continuous-time stochastic processes introduced in quantitative finance by Merton [34], extending the work on option pricing by Black and Scholes [3]. These models reproduce stylized facts observed in asset price dynamics, such as mean-reversion and jumps. There are two ways to expound the description of jump processes. 1. One is to describe the jump in **absolute terms** (this is useful if we are focusing on prices or interest rates), 2. The other is to describe the jump in **proportional terms** (this is more useful if our focus is on returns, as in this study). In addition to jump-diffusion models, Levy processes appear as an alternative for capturing large deviations in asset prices. Levy processes allow sample paths with frequent discontinuities, enabling them to generate heavy-tailed distributions. Some key examples include variance gamma processes, normal inverse Gaussian processes, and generalized hyperbolic processes. [51] demonstrated that Bitcoin returns exhibit heavy tails and proposed using a variance gamma process to model the price dynamics. [25] found evidence that variance gamma processes fit cryptocurrency log returns compared to classical diffusion. Levy processes have also been employed to model stochastic volatility in Bitcoin prices [5]. Overall, Levy processes provide an alternative class of models with more flexibility to account for extreme deviations. They have shown promise in fitting the empirical distributional properties of cryptocurrency returns. As this work focuses initially on extending jump-diffusion models, exploring Levy processes represents a worthwhile direction for future research. However, their ability to capture heavy tails and discontinuities suggests that Levy processes could serve as a valuable modelling technique in this domain. Consider a probability space \((\Omega,\mathcal{F},\mathbf{P})\) endowed with a filtration \(\mathbb{F}=\{\mathcal{F}_{t},\ t\geq 0\}\) that satisfies the usual conditions of right-continuity and completeness, where \(\mathcal{F}_{t}=\sigma\big{(}W_{s},N_{s};\ 0\leq s\leq t\big{)}\): \(W_{t}\) is a standard Brownian motion, and \(N_{t}\) denotes a counting process that can be represented as \(N_{t}=\sum_{i}1_{\{T_{i}\leq t\}}\) with a sequence of stopping times \(0<T_{1}<T_{2}<\cdots<T\) whose number is finite with probability one. Let \(S=\{S_{t},\ t\geq 0\}\) be the price process of Bitcoin, and let \(y_{t}\) be the absolute jump size, where we assume that the bitcoin price jumps from \(S_{t}\) to \(y_{t}S_{t}\) in a small time interval \(t\). The relative price jump size, \(J_{t}=y_{t}-1\), is the percentage change in the bitcoin price influenced by the jump. Using the Merton jump-diffusion model, the absolute price jump size is a non-negative random variable which is log-normally distributed, i.e \(\ln(y_{t})\sim i.i.d\ \mathcal{N}(\mu,\delta^{2})\)[33]. Thus, we further assume that the Bitcoin price dynamics are described by the following jump-diffusion stochastic differential equation \[dS_{t}=S_{t}P_{t-\tau}(\mu_{d}-\lambda k)dt+\sigma_{d}\sqrt{P_{t-\tau}}S_{t} dW_{t}+S_{t}P_{t-\tau}(y_{t}-1)dN_{t},\qquad S_{0}=s_{0}\in\mathbb{R}_{+} \tag{2.1}\] where \(\mu_{d}\) is the diffusion mean, \(\sigma_{d}\) the diffusion volatility, \(\lambda\) the jump intensity rate and \(\mathbb{E}[J_{t}]=\mathrm{e}^{\mu+\frac{\delta^{2}}{2}}-1=k\), the expected proportional jump size. The one-dimensional Poisson process is discontinuous with a constant jump \(\lambda\) and is given by \[\mathrm{d}N_{t}=N_{t+dt}-N_{t}=\begin{cases}0\text{ with probability }1-\lambda \mathrm{d}t,\\ 1\text{ with probability }\lambda\mathrm{d}t\end{cases}.\] Also, the exogenous process \(P=\{P_{t},\ t\geq 0\}\) is a stochastic factor representing the sentiment index in the Bitcoin market, satisfying \[dP_{t}=P_{t}\mu_{p}dt+\sigma_{p}P_{t}dZ_{t},\qquad P_{t}=\phi(t),\ t\in[-L,0]. \tag{2.2}\] where \(\mu_{p}\in\mathbb{R}-\{0\}\), \(\sigma_{p}\in\mathbb{R}_{+}\), \(L\in\mathbb{R}_{+}\), \(Z=\{Z_{t},\ t\geq 0\}\) is a standard \(\mathbb{F}\)-Brownian motion on \((\Omega,\mathcal{F},\mathbf{P})\), which is \(\mathbf{P}\)-independent of \(W\), and \(\phi:[-L,0]\to[0,+\infty)\) is a continuous (deterministic) initial function. The non-negative property of the function \(\phi\) corresponds to the requirement that the minimum level for sentiment is zero. The delay variable \(P_{t-\tau}\) accounts for the effect of investor sentiment on volatility, and this is supported by findings that factors like public attention and transaction volume influence cryptocurrency volatility (e.g. [4] and [9]). This variable affects the instantaneous variance of the Bitcoin price modulated by \(\sigma_{d}\). The sentiment index may be the volume/the number of Bitcoin transactions or the number of internet searches within a fixed time period. The solution to equation (2.2) exists in its closed form [3], and \(P_{t}\) is lognormally distributed for each \(t>0\). The system given by equations 2.1 and 2.2 is well-defined in \(\mathbb{R}_{+}\) as stated in the following theorem **Theorem 2.1**.: _In the market model described previously, the following holds:_ 1. _the bivariate stochastic delayed differential equation_ \[\begin{cases}dS_{t}=S_{t}P_{t-\tau}(\mu_{d}-\lambda k)dt+\sigma_{d}\sqrt{P_{t- \tau}}S_{t}dW_{t}+S_{t}P_{t-\tau}(y_{t}-1)dN_{t},\qquad S_{0}=s_{0}\in\mathbb{R }_{+}\\ dP_{t}=P_{t}\mu_{p}dt+\sigma_{p}P_{t}dZ_{t},\qquad P_{t}=\phi(t),\ t\in[-L,0]. \end{cases}\] (2.3) _has a continuous,_ \(\mathbb{F}\)_-adapted, unique strong solution_ \((S,P)=\{(S_{t},P_{t}),\ t\geq 0\}\) _given by_ \[S_{t}=S_{0}\exp\bigg{(}\big{(}(\mu_{d}-\lambda k)-\frac{\sigma_{d}^{2}}{2} \big{)}\int_{0}^{t}P_{u-\tau}du+\sigma_{d}\int_{0}^{t}\sqrt{P_{u-\tau}}dW_{u} +\int_{0}^{t}\ln(1+P_{u-\tau}(y_{u}-1))dN_{u}\bigg{)}\] (2.4) \[P_{t}=\phi(0)\exp\bigg{(}\big{(}\mu_{d}-\frac{\sigma_{d}^{2}}{2} \big{)}t+\sigma_{d}Z_{t}\bigg{)},\qquad t\geq 0\] (2.5) The solution (2.4) can be obtained by applying the Ito's formula for jump-diffusion processes taken from [48, Proposition 8.14, p.275] to \(\ln(S_{t})\) and assuming that the process \(S_{t}\) is caglad. \[\ln(S_{t})=\ln(S_{0})+\int_{0}^{t}P_{u-\tau}(\mu_{d}-\lambda k)du +\frac{1}{2}\int_{0}^{t}\sigma_{d}^{2}P_{u-\tau}du+\int_{0}^{t}\sigma_{d}\sqrt{ P_{u-\tau}}dW_{u}+\\ \int_{0}^{t}\ln(S_{u^{-}}+S_{u}P_{u-\tau}(y_{u}-1))-\ln(S_{u^{-}} )\ dN_{u}\,.\] ### Strengths and limitations of the proposed model The bivariate jump-diffusion model provides an essential first step in applying financial engineering techniques to this new domain. By capturing stochastic volatility, discrete jumps, and a sentiment indicator, it incorporates several salient features of cryptocurrencies. The preliminary pricing and derivatives valuation framework can be built upon as the market evolves. While the assumptions require validation as more data emerges, the model offers valuable inputs for investment analysis at present. We acknowledge the need to refine techniques as cryptocurrency finance matures into its own field. This paper aims to provide the initial modelling foundation, which can be improved incrementally as research progresses. Future enhancements may include more flexible return distributions, multifactor models to capture additional risks, regime-switching models to reflect market phases, and calibration of the sentiment factor from various data sources. In addition, the current proposed model offers a useful starting point, we recognize this initial framework may require modifications over time to align with market realities. As more cryptocurrency data becomes available, the distributional properties and other intricacies of these markets will become clearer. If the actual return distributions exhibit higher kurtosis than the normal distribution assumed, the model may need to be adjusted accordingly. Furthermore, if inefficiencies and arbitrage opportunities remain prevalent, the dynamics may diverge from a pure jump-diffusion process. As researchers expand their knowledge of the microstructure, behavioural components, and risks in cryptocurrency markets, our modelling approach can be enhanced. In summary, we emphasize this work represents a starting point for modelling cryptocurrencies and enabling financial applications. The proposed bivariate jump-diffusion model and sentiment indicator capture essential dynamics but may require adjustments as knowledge develops. We welcome future research to build on these initial techniques for pricing and valuation of cryptocurrency-denominated assets. ### Applications We now derive the Black-Scholes PDE by a hedging argument. Consider the stock price process described by the equations 2.1 and 2.2. Let \(B(t)\) be the risk-free asset process: \[B(t)=e^{rt},\quad t\in[0,T]\] where \(r>0\). Let \(V_{t}=V(t,S_{t})\) be the price of the derivative that cannot be exercised before maturity. Applying Ito's formula, \[dV(t,S_{t})=\bigg{(}\frac{\partial V}{\partial t}(t,S_{t})+(\mu _{d}-\lambda k)S_{t}P_{t-\tau}\frac{\partial V}{\partial S}(t,S_{t})+\frac{ \sigma_{d}^{2}}{2}P_{t-\tau}S_{t}^{2}\frac{\partial^{2}V}{\partial S^{2}}(t,S_ {t})\bigg{)}dt+\\ \sigma_{d}\sqrt{P_{t-\tau}}S_{t}\frac{\partial V}{\partial S}(t, S_{t})dW_{t}+\Delta V(t,S_{t})dN_{t}\] We set up a self-financing portfolio \(X\) that is comprised of one option and \(\delta\) amount of the underlying stock, such that the portfolio is riskless, that is insensitive to changes in the price of the security. So, at time \(t\), the value of the portfolio is \(X_{t}=V_{t}+\delta S_{t}\). The self-financing assumption implies that \[dX_{t}=dV_{t}+\delta dS_{t} \tag{2.6}\] Substituting the \(dV_{t}\) and \(dS_{t}\) into the Equation (2.6), we have \[dX_{t}=\bigg{[}\bigg{(}\frac{\partial V}{\partial t}(t,S_{t})+( \mu_{d}-\lambda k)S_{t}P_{t-\tau}\frac{\partial V}{\partial S}(t,S_{t})+\frac {\sigma_{d}^{2}}{2}P_{t-\tau}S_{t}^{2}\frac{\partial^{2}V}{\partial S^{2}}(t,S _{t})\bigg{)}dt+\\ \sigma_{d}\sqrt{P_{t-\tau}}S_{t}\frac{\partial V}{\partial S}(t, S_{t})dW_{t}+\Delta V(t,S_{t})dN_{t}\bigg{]}+\delta\bigg{[}S_{t}P_{t-\tau}(\mu_{d}- \lambda k)dt+\sigma_{d}\sqrt{P_{t-\tau}}S_{t}dW_{t}+S_{t}P_{t-\tau}(y_{t}-1)dN _{t}\bigg{]}.\] So, \[dX_{t}=\bigg{(}\frac{\partial V}{\partial t}(t,S_{t})+(\mu_{d}- \lambda k)S_{t}P_{t-\tau}\bigg{(}1+\frac{\partial V}{\partial S}(t,S_{t})\bigg{)} +\frac{\sigma_{d}^{2}}{2}P_{t-\tau}S_{t}^{2}\frac{\partial^{2}V}{\partial S^{2} }(t,S_{t})\bigg{)}dt+\\ \sigma_{d}\sqrt{P_{t-\tau}}S_{t}\bigg{(}\delta+\frac{\partial V}{ \partial S}(t,S_{t})\bigg{)}dW_{t}+\bigg{(}\delta S_{t}P_{t-\tau}(y_{t}-1)+ \Delta V(t,S_{t})\bigg{)}dN_{t} \tag{2.7}\] On one hand, this portfolio should be riskless and earn a risk-free rate. To be riskless, the second and the third terms involving, respectively, the Brownian motion \(dW_{t}\) and the Poisson process \(dN_{t}\) must be zero. That is \[\delta=-\frac{\partial V}{\partial S}(t,S_{t})\text{ and }\Delta V(t,S_{t})=- \delta S_{t}P_{t-\tau}(y_{t}-1)\] Hence, \[\Delta V(t,S_{t})=S_{t}P_{t-\tau}(y_{t}-1)\frac{\partial V}{\partial S}(t,S_{ t})\] Substituting for \(\delta\) and \(\Delta V(t,S_{t})\) in Equation (2.7) implies that the portfolio follows the process \[dX_{t}=\bigg{(}\frac{\partial V}{\partial t}(t,S_{t})+(\mu_{d}-\lambda k)S_{t }P_{t-\tau}\bigg{(}1+\frac{\partial V}{\partial S}(t,S_{t})\bigg{)}+\frac{ \sigma_{d}^{2}}{2}P_{t-\tau}S_{t}^{2}\frac{\partial^{2}V}{\partial S^{2}}(t,S _{t})\bigg{)}dt \tag{2.8}\] On the other hand, the portfolio must earn the risk-free rate, that is \[dX_{t}=rX_{t}dt\] \[\bigg{(}\frac{\partial V_{t}}{\partial t}+(\mu_{d}-\lambda k)S_{t }P_{t-\tau}\bigg{(}1+\frac{\partial V_{t}}{\partial S}\bigg{)}+\frac{\sigma_{ d}^{2}}{2}P_{t-\tau}S_{t}^{2}\frac{\partial^{2}V_{t}}{\partial S^{2}} \bigg{)}dt=r\bigg{(}V_{t}-\frac{\partial V_{t}}{\partial S}S_{t}\bigg{)}dt\] Multiplying both sides by \(\frac{1}{dt}\) and re-arranging yields the following Black-Scholes PDE for an option \(V\) \[\frac{\partial V_{t}}{\partial t}+\frac{\sigma_{d}^{2}}{2}P_{t-\tau}S_{t}^{2} \frac{\partial^{2}V_{t}}{\partial S^{2}}+rS_{t}\frac{\partial V_{t}}{\partial S }-rV_{t}=-(\mu_{d}-\lambda k)S_{t}P_{t-\tau}\bigg{(}1+\frac{\partial V_{t}}{ \partial S}\bigg{)} \tag{2.9}\] This extended Black-Scholes PDE poses challenges for analytical solutions due to the unbounded upside of the European call payoff. Therefore, numerical methods are often used to approximate the solution. Two standard techniques are finite difference methods and Monte Carlo simulation. Finite difference methods involve discretizing the price domain and time dimensions and replacing the derivatives with finite difference approximations. This transforms the PDE into a system of algebraic equations that can be solved recursively. Various finite difference schemes can be employed, such as explicit, implicit, and Crank-Nicolson. Monte Carlo simulation generates sample paths of the underlying price using the assumed stochastic process. The discounted payoffs from each sample path are averaged to estimate the option price. Variance reduction techniques like antithetic sampling and control variates can improve efficiency. Both methods have tradeoffs regarding accuracy, speed, and implementation complexity. Our proposed neural network approach serves as an alternative way to numerically solve the pricing PDE without discretizing the domain. This offers benefits in terms of generalization and scaling. ## 3 Neural Network Methodology The neural network (NN) algorithm is used for solving problems relating to dimensionality reduction [42; 49], visualization of data [31], clustering [11; 52] and classification issues [37; 40]. It is also used in regression [2; 21; 45] in solving regression problems since they do not require prior knowledge about the distribution of the data. The NN algorithm often has the tendency to predict with higher accuracy than other techniques due to the NN's capability to fit any continuous functions [18]. Mathematically, the NN can be referred to as a directed graph having neurons as vertices and links as edges. Different forms of NN depend on the connectivity of their neurons, and the simplest one is the Multi-layer perceptron, also known as the feedforward NN. Basically, a NN can have only one input and one output layer in its simplest form, and this can be written as: \[y_{k}=\Phi\left(b_{k}+\sum_{i=1}^{m}w_{i,k}\mathbf{x}_{i}\right)\,,\] where \(m\) is the number of input variables, \(\Phi\) is the activation function, \(w_{i,k}\) is the weight of the input layer \(i\) with respect to the output \(k\), \(b\) is the bias, and the input vector \(\mathbf{x}\) is connected to the output \(k\) (denoting the \(k\)th neuron in the output layer) through a biased weighted sum. In the presence of hidden layers positioned between the input layers and the output layers, the output can be written as: \[y_{p}=\Phi_{out}\left[b_{p}^{(2)}+\sum_{k=1}^{m_{2}}w_{k,p}^{(2)}\times\Phi \left(b_{k}^{(1)}+\sum_{i=1}^{m_{1}}w_{i,k}^{(1)}\ \mathbf{x}_{i}\right)\right]\,,\] where \(m_{1}\) is the number of input variables, \(m_{2}\) is the number of nodes in the hidden layer, \(\Phi:\mathbb{R}\rightarrow\mathbb{R}\) refers to non-linear activation functions for each of the layers in the brackets, and \(\Phi_{out}\) is the possibly new output function. Recently, the NN has become an indispensable tool for learning the solutions of differential equations, and this section will utilize the potential of the NN in solving PDE-related problems [1; 10; 20; 50]. Also, the NN has been implemented in solving equations without analytical solutions. For instance, Nwankwo et al. [38] considered the solution of the American options PDE by incorporating the Landau transformation and solving the corresponding transformed function via a neural network approach. In many scientific and industrial contexts, there is a need to solve parametric PDEs using NN techniques and Khoo et al. [24] developed such a technique which solves PDE with inhomogeneous coefficient fields. For high-dimensional parametric PDE, [14] analyzed the deep parametric PDE method to solve high-dimensional parametric PDEs with much emphasis on financial applications. In the following, we describe the Bitcoin options with the corresponding Black-Scholes pricing PDE: \[\frac{\partial V}{\partial t}+\frac{\sigma^{2}S^{2}}{2}P_{t-\tau}\frac{ \partial^{2}V}{\partial S^{2}}+(r+(\mu-\lambda K)P_{t-\tau})S\frac{\partial V }{\partial S}-rV+(\mu-\lambda K)SP_{t-\tau}=0 \tag{3.10}\] The above equation which is a non-homogeneous PDE can be re-written as \[\frac{\partial V}{\partial t}+\frac{\sigma^{2}_{*}S^{2}}{2}\frac{\partial^{2} V}{\partial S^{2}}+\eta S\frac{\partial V}{\partial S}-rV=\beta(S)\,, \tag{3.11}\] where \(\sigma_{*}^{2}=\sigma^{2}P_{t-\tau}\), \(\ \eta=r+(\mu-\lambda K)P_{t-\tau}\), \(\ \beta(S)=-(\mu-\lambda K)SP_{t-\tau}\) and \(P_{t}=\phi(0)\exp\{(\mu_{p}-\frac{\sigma_{p}^{2}}{2})t+\sigma_{p}Z_{t}\}\). Equation (3.11) can be written in its operator format. Let \(\Omega=S_{max}\) and \(\mathcal{A}\) be the infinitesimal operator for the stochastic process defined by \[\mathcal{A}=S\eta(t,s)\frac{\partial}{\partial S}+\frac{S^{2}\sigma_{*}^{2}(t, S)}{2}\frac{\partial^{2}}{\partial S^{2}}\,, \tag{3.12}\] with both the boundary and the terminal value problem written as \[(\partial_{t}+\mathcal{A}-r)V(t,S) =\beta(t,S),\qquad\qquad t,S\in[0,T]\times\Omega\] \[V(T,S) =g_{1}(T,S)=\text{Payoff},\qquad\qquad t,S\in[0,T]\times\partial\Omega\] \[V(t,S) =g_{2}(t,S)=S_{t}-K\mathrm{e}^{-r(T-t)},\qquad\qquad S\in\Omega\] \[V(t,0) =V_{0}(t)=0,\qquad\qquad t\in[0,T]\,. \tag{3.13}\] Standard theorems guarantee a classical smooth solution exists for the pricing PDE (3.13) given the assumed dynamics. The continuity and linear growth conditions on the coefficient functions ensure they satisfy Lipschitz continuity. Contingent claims theory shows that Lipschitz continuity is sufficient for existence and uniqueness under the stochastic process specifications. In particular, the smooth past price dependence in the diffusion coefficient allows the application results for delayed Black-Scholes equations. Therefore, the Cauchy problem is well-posed under the model assumptions, and a smooth pricing solution is guaranteed to exist based on the theorems. This provides the theoretical foundation for using a neural network to approximate the price function numerically. Thus, employing the ANN to solve the PDE, we introduce an approximating function \(\zeta(t,S:\boldsymbol{\theta})\) with parameter set \(\boldsymbol{\theta}\). The loss or cost function associated with this training is measured by how well the approximation function satisfies the differential operator, boundary conditions and the terminal condition of the option pricing PDE. These are given respectively as * Differential operator \(\left\|\partial_{t}+\mathcal{A}-r)\zeta(t,S:\boldsymbol{\theta})\right\|_{Y_ {1}}^{2}\), where \(Y_{1}=[0,T]\times\Omega,v_{1}\). * Terminal condition \(\left\|\zeta(T,S:\boldsymbol{\theta})-g_{1}(T,S)\right\|_{Y_{2}}^{2}\), where \(Y_{2}=\Omega,v_{2}\). * Boundary condition \(\left\|\zeta(t,0:\boldsymbol{\theta})-V_{0}(t)\right\|_{Y_{3}}^{2}\), where \(Y_{3}=[0,T],v_{3}\). * Boundary condition \(\left\|\zeta(t,S:\boldsymbol{\theta})-g_{2}(t,S)\right\|_{Y_{4}}^{2}\), where \(Y_{4}=[0,T]\times\partial\Omega,v_{4}\). In all these four terms above, the observed error is measured in the Hilbert space \(L^{2}\)-norm, meaning that \(\left\|\lambda(x)\right\|_{m,n}^{2}=\int_{m}|\lambda(x)|^{2}n(x)\mathrm{d}x\) with \(n(x)\) being the probability density function which describes the region \(m\). The combination of these terms gives the associated cost or loss function connected with the NN training. Thus, the objective function can be written as: \[\mathcal{L}(\zeta) =\left\|\partial_{t}+\mathcal{A}-r)\zeta(t,S:\boldsymbol{\theta}) \right\|_{Y_{1}}^{2}+\left\|\zeta(T,S:\boldsymbol{\theta})-g_{1}(T,S)\right\| _{Y_{2}}^{2}+\left\|\zeta(t,0:\boldsymbol{\theta})-V_{0}(t)\right\|_{Y_{3}}^{2}\] \[+\left\|\zeta(t,S:\boldsymbol{\theta})-g_{2}(t,S)\right\|_{Y_{4} }^{2}\,. \tag{3.14}\] Suppose \(\mathcal{L}(\zeta)=0\), then \(\zeta(t,S:\boldsymbol{\theta})\) is a solution of the PDE in equation (3.13). The major aim is to obtain a set of parameters \(\boldsymbol{\theta}\) such that the function \(\zeta(t,S:\boldsymbol{\theta})\) minimizes the observed error of \(\mathcal{L}(\zeta)\). The procedure for seeking a good parameter set by minimizing this loss function using the stochastic gradient descent (SGD) optimizer is called "training". Thus, using a Machine Learning approach, and in this case, the artificial NN, it will be feasible to minimize the function \(\mathcal{L}(\zeta)\) by applying the SGD approach on the sequence of asset and time points which are drawn at random. A part of the input samples, fully dependent on the mini-batch size, is drawn within each iteration to estimate the gradient of the given objective function. The gradient is then estimated over these mini-batches due to the limitations of the computer memory [30]. The training of NN is classified into first identifying the network's hyperparameters, that is, the architectural structure and the loss function of the network. Next, use the SGD to optimize or estimate the loss minimizer, and then the derivatives of the loss function are computed using the backpropagation techniques. Essentially, the process of searching and identifying the best \(\boldsymbol{\theta}\) parameter by minimizing the loss function using the gradient descent-based optimizers is referred to as "training". The whole procedure is well illustrated in the algorithm below [46], and can be implemented in solving the PDE in equation (3.13): 1. Set up the initial parameter set \(\mathbf{\theta}_{0}=(\mathbf{W}_{0},\mathbf{b}_{0})\) as well as the learning rate \(\alpha_{n}\), where \(\mathbf{W}_{0}\) and \(\mathbf{b}_{0}\) represent the weight and the bias respectively. 2. Generate samples drawn randomly from the interior of the domain and from the time/asset boundaries. That is * Generate \((t_{n},S_{n})\) from \([0,T]\times\Omega\) in accordance to the probability density \(v_{1}\). * Generate \(\omega_{n}\) from \(\Omega\) in accordance to the probability density \(v_{2}\). * Generate \(r_{n}\) from \([0,T]\) in accordance to the probability density \(v_{3}\). * Generate \((\tau_{n},z_{n})\) from \([0,T]\times\partial\Omega\) in accordance to the probability density \(v_{4}\). 3. Estimate the value of squared error \(\mathcal{G}(\theta_{n};x_{n})\) where \(x_{n}\) is a set of randomly sampled points denoted by \(x_{n}=\{(t_{n},S_{n}),\omega_{n},r_{n},(\tau_{n},z_{n})\}\). That is, compute the following: * Compute \(\mathcal{G}_{1}(\theta_{n};t_{n},S_{n})=((\partial_{t}+\mathcal{A}-r)\zeta( \theta_{n};t_{n},S_{n}))^{2}\). * Compute \(\mathcal{G}_{2}(\theta_{n};\omega_{n})=(\zeta(T,\omega_{n})-g_{1}(T,\omega_{ n}))^{2}\). * Compute \(\mathcal{G}_{3}(\theta_{n};r_{n})=(\zeta(r_{n},0)-V_{0}(r_{n}))^{2}\). * Compute \(\mathcal{G}_{4}(\theta_{n};\tau_{n},z_{n})=(\zeta(\tau,z_{n})-g_{2}(\tau_{n}, z_{n}))^{2}\). * Set \(\mathcal{G}(\theta_{n};x_{n})=\mathcal{G}_{1}(\theta_{n};t_{n},S_{n})+ \mathcal{G}_{2}(\theta_{n};\omega_{n})+\mathcal{G}_{3}(\theta_{n};r_{n})+ \mathcal{G}_{4}(\theta_{n};\tau_{n},z_{n})\). 4. Compute the gradient \(\nabla_{\theta}\mathcal{G}(\theta_{n};x_{n})\) using backpropagation techniques. 5. Take an SGD step at the random points \(x_{n}\) using the learning rates from the Adam optimization method. Use the estimated gradient to update the parameter \(\mathbf{\theta}_{n}\). Therefore, in each iteration \(n\), the parameters \(\mathbf{\theta}_{n}\) are updated in accordance to the relationship below: \[\theta_{n+1}=\theta_{n}-\alpha_{n}\nabla_{\theta}\mathcal{G}(\theta_{n};x_{n})\] (3.15) Equation (3.15) can be explicitly written in terms of the weights and bias as \[\begin{cases}\mathbf{W}_{i+1}\leftarrow\mathbf{W}_{i}-\alpha_{i}\frac{\partial \mathcal{G}(\theta_{i};x_{i})}{\partial\mathbf{W}}\\ \\ \mathbf{b}_{i+1}\leftarrow\mathbf{b}_{i}-\alpha_{i}\frac{\partial\mathcal{G}(\theta_{i} ;x_{i})}{\partial\mathbf{b}}\end{cases},\] (3.16) where \(i=0,1,\cdots,n\); and \(n\) is the number of training iterations. 6. Repeat the procedure from (2-4) till the convergence property is satisfied, that is till \(\|\theta_{n+1}-\theta_{n}\|\) becomes very small. **Algorithm 1** Implementing NN in solving PDE It must also be noted that the gradient descent steps \(\nabla_{\theta}\mathcal{G}(\theta_{n};x_{n})\) are the unbiased estimates of \(\nabla_{\theta}\mathcal{L}(\zeta(.;\theta_{n}))\), such that \[\mathbb{E}[\nabla_{\theta}\mathcal{G}(\theta_{n};x_{n})|\theta_{n}]=\nabla_{ \theta}\mathcal{L}(\zeta(.;\theta_{n})),\] and also a negative correlation exists between the learning rate \(\alpha_{n}\) and \(n\). The learning rate \(\alpha\) is employed to scale the intensity of the parameter updates during the gradient descent. Choosing the learning rate, as the descent parameter \(\alpha\), in the network training is crucial since this factor plays a significant role in aiding the algorithm's convergence to the true solution in the gradient descent. It equally affects the pace at which the algorithm learns and whether or not the cost function is minimized. When \(\alpha\) implies divergence, and thus, the optimal point can be missed. Also, a fixed value of \(\alpha\) can most likely make the local optima overshoot after some iterations, leading to divergence. Defining the learning rate as a dynamic decreasing function is preferable since it allows the algorithm to identify the needed point rapidly. Another limitation in employing the gradient descent method is obtaining the value of the initial parameters of the loss function. If the value is significantly close to the local optimum, then the slope of the loss function reduces, thereby leading to the optimal convergence. Otherwise, there will be no convergence as the solution explodes abnormally. ### Solution of bitcoin option pricing PDE While the pricing PDE has a proven smooth solution under the model dynamics, obtaining the analytical form is intractable. Numerical methods must be used to approximate the solution. Neural networks provide a flexible parametric approach based on their universal approximation theoretical results. Given sufficient network capacity, neural networks can represent a wide class of functions, including solutions to PDEs like the pricing equation. However, challenges remain in finding the optimal network parameters to recover the true solution robustly. While existence is guaranteed, the non-convex optimization of neural networks does not assure convergence to global optimality. Care must be taken in specifying the network architecture, loss function, regularization, and training methodology to promote the learning of the pricing function. Subject to these caveats, neural networks present a promising computational technique for approximating smooth pricing solutions, circumventing discretization of the domain. We note the limitations of using neural networks as function approximators. However, their generalization capabilities provide a methodology for data-driven extraction of the pricing mapping across the entire domain. This avoids the constraints of methods like grid-based techniques that rely on local consistency. Future work should explore neural network training enhancements and theoretical guarantees to ensure robust solutions. Thus, from equation (3.11), let \(V\) be the price of the bitcoin call option with strike price \(E\) and \(S^{\prime}\) be the price of the bitcoin option at time \(t^{\prime}\). Let \(r\) be the risk-free rate; \(\sigma_{*}\), the volatility of the bitcoin; \(T\), the expiration of the contract and denote bitcoin call price \(V=V(t^{\prime},S^{\prime})\) to be a function of the remaining time to maturity and the bitcoin price. Considering the European call option, the terminal or the final condition and the boundary conditions are denoted respectively by: \[\begin{cases}TC:V(T,S^{\prime})=\max\{S^{\prime}-E,0\}\\ BC:V(t^{\prime},0)=0\\ BC:\frac{V(t^{\prime},S^{\prime})}{S^{\prime}}\to 1\qquad\text{for}\quad S^{ \prime}\to\infty\,,\end{cases} \tag{3.17}\] for \(t^{\prime}\in[0,T]\) and \(S^{\prime}\in[0,S_{\max}]\), where \(S_{\max}\) is the upper limit2 which the bitcoin can accumulate prior to the option's expiration. With the change of variables \(t=\frac{T-t^{\prime}}{T}\), and \(S=\frac{S^{\prime}}{S_{\max}}\), such that \(t\in[1,0]\) and \(S\in[0,1]\), we can substitute \(-T\partial t=\partial t^{\prime}\) into the PDE (3.11). This restriction is imposed such that the terminal condition (TC) in equation (3.17) can be transformed into an initial condition (IC). Thus, the PDE reduces to \[\frac{1}{T}\frac{\partial V}{\partial t}-\frac{\sigma_{*}^{2}S^{2}}{2}\frac{ \partial^{2}V}{\partial S^{2}}-\eta S\frac{\partial V}{\partial S}+rV+\beta(S) =0\,, \tag{3.18}\] with the following transformed conditions: \[\begin{cases}IC:V(0,S)=\max\left\{S-\frac{E}{S_{\max}},0\right\},\quad\forall S \in[0,1]\\ \\ BC:V(t,0)=0,\quad\forall t\in[1,0]\\ BC:V(t,1)=1-\frac{E}{S_{\max}}\,.\end{cases} \tag{3.19}\] Solving the PDE in equation (3.18) using the conditions in equation (3.19) entails introducing a trial solution \(\zeta(t,S:\boldsymbol{\theta})\) which employs the feedforward NN with parameter \(\boldsymbol{\theta}\) corresponding to the weight and biases of the network's architecture. The trial function \(\zeta(t,S:\boldsymbol{\theta})\) of the NN is constructed such that it satisfies the boundary and the initial conditions [13, 29, 53]. This can be written as \[\zeta(t,S:\boldsymbol{\theta})=A(t,S)+B(t,S)N(t,S:\boldsymbol{\theta})\,, \tag{3.20}\] where \(B(t,S)=tS(1-S)\). The first term \(A(t,S)\) satisfies the boundary and the initial conditions has no adjustable parameters and is denoted by \[A(t,S)=(1-t)\max\left\{S-\frac{E}{S_{\max}},0\right\}+tS\left(1-\frac{E}{S_{ \max}}\right)\,.\] The last term in equation (3.20) with the NN function has adjustable parameters, and it handles the minimization problem. This term does not contribute to the boundary condition because at boundaries \(S=0,S=1\) and \(t=0\); the term became exactly zero. Thus, the trial function is explicitly given as \[\zeta(t,S:\boldsymbol{\theta})=(1-t)\max\left\{S-\frac{E}{S_{\max}},0\right\} +tS\left(1-\frac{E}{S_{\max}}\right)+tS(1-S)N(t,S:\boldsymbol{\theta})\,. \tag{3.21}\] Given the input values \((t,S)\), the network's output is the net function which is defined by \[N(t,S:\boldsymbol{\theta})=\sum_{r=1}^{M}q_{r}f(w_{r}t+\gamma_{r}S+b_{r})\,, \tag{3.22}\] where \(M\) is the total number of the neurons which are present in the hidden layer of the NN; \(f(z_{r})\) is the activation function; \(q_{r}\) is the synaptic weight of the \(r^{\text{th}}\) hidden neuron to the output; \(b_{r}\) is the bias value of the \(r^{\text{th}}\) hidden neuron; \(w_{r}\) and \(\gamma_{r}\) are the synaptic coefficients from the time input to the \(r^{\text{th}}\) hidden neuron and from the spatial inputs to the \(r^{\text{th}}\) hidden neuron respectively. Finally, with regards to the cost function, we first discretise the domains to convert the PDE in equation (3.18) which are subject to the boundary conditions, into an unconstrained minimization problem. For \(S\in[0,1]\) and \(t\in[1,0]\), consider \(\Delta S\) to be a uniform step size for the bitcoin asset \(S\), and \(\Delta t\) to be the step size for the time \(t\), such that \[S_{i}=i\Delta S\implies\Delta S=\frac{1}{N_{s}},\qquad\text{for} \quad i=0,1,\cdots,N_{s}\qquad\text{and}\] \[t_{j}=j\Delta t\implies\Delta t=\frac{1}{N_{t}},\qquad\text{for} \quad j=0,1,\cdots,N_{t}\,,\] where \(N_{s}\) and \(N_{t}\) are the step sizes for the bitcoin asset and the time, respectively. The dataset that will be generated from this discretised domain will consist of a matrix of size \((N_{s}\times N_{t})\times 2\), that is, two columns made up by \(S_{i}\) and \(t_{j}\), as well as \((N_{s}\times N_{t})\) number of rows. The dataset will be split into the train data and the test dataset and the NN will be trained on the train dataset and tested on a separate dataset. Using the trial function in equation (3.21), denote the bitcoin option value at time \(t_{j}\) for the asset \(S_{i}\) given by \(\zeta(t_{j},S_{i}:\boldsymbol{\theta})=\zeta(j\Delta t,i\Delta S:\boldsymbol{ \theta})\) as \(\zeta_{j,i}\), then the cost function which the ANN has to minimize is \[L(\boldsymbol{\theta})=\frac{1}{2}\sum_{j=1}^{N_{t}}\sum_{i=1}^{N_{s}}\left[ \frac{\partial\zeta_{j,i}}{\partial t_{j}}-\frac{\sigma_{*}^{2}S_{i}^{2}}{2} \frac{\partial^{2}\zeta_{j,i}}{\partial S_{i}^{2}}-\eta S_{i}\frac{\partial \zeta_{j,i}}{\partial S_{i}}+r\zeta_{j,i}+\beta(S_{i})\right]^{2}\,, \tag{3.23}\] for \(j=0,1,\cdots,N_{t}\) and \(i=0,1,\cdots,N_{s}\). Essentially, the loss function is minimized during the training phase to determine the optimal NN parameters. The partial derivatives in equation (3.23) are computed as follows: \[\frac{\partial\zeta}{\partial t}=-\max\left\{S-\frac{E}{S_{\max}},0\right\}+S \left(1-\frac{E}{S_{\max}}\right)+tS(1-S)\frac{\partial N(t,S:\boldsymbol{ \theta})}{\partial t}+S(1-S)N(t,S:\boldsymbol{\theta}) \tag{3.24}\] \[\frac{\partial\zeta}{\partial S}=t\left(1-\frac{E}{S_{\max}}\right)+tS(1-S) \frac{\partial N(t,S:\boldsymbol{\theta})}{\partial S}+N(t,S:\boldsymbol{ \theta})(t-2tS),\quad\text{for}\ S\leq\frac{E}{S_{\max}} \tag{3.25}\] \[\frac{\partial\zeta}{\partial S}=(1-t)+t\left(1-\frac{E}{S_{\max}}\right)+tS( 1-S)\frac{\partial N(t,S:\boldsymbol{\theta})}{\partial S}+N(t,S:\boldsymbol{ \theta})(t-2tS),\quad\text{for}\ S>\frac{E}{S_{\max}} \tag{3.26}\] \[\frac{\partial^{2}\zeta}{\partial S^{2}}=tS(1-S)\frac{\partial^{2}N(t,S: \boldsymbol{\theta})}{\partial S^{2}}+2t(1-2S)\frac{\partial N(t,S:\boldsymbol {\theta})}{\partial S}+-2tN(t,S:\boldsymbol{\theta})\,. \tag{3.27}\] The partial derivatives of the NN with respect to \(t,S\) and \(S^{2}\) from equations (3.24-3.27) are dependent on the nature of the activation function used. For instance, if we consider the sigmoid activation function, then \(f(z_{r})=(1+\mathrm{e}^{-z_{r}})^{-1}\). Then from equation (3.22), \(z_{r}=w_{r}t+\gamma_{r}S+b_{r}\), and thus, the NN function in expanded form can be written as \[N(t,S:\boldsymbol{\theta})=\sum_{r=1}^{M}q_{r}\left(1+\mathrm{e}^{-(w_{r}t+ \gamma_{r}S+b_{r})}\right)^{-1}\,, \tag{3.28}\] Taking the derivatives of equation (3.28) with respect to \(t,S\) and \(S^{2}\), we have the following \[\frac{\partial N(t,S:\mathbf{\theta})}{\partial t} =\sum_{r=1}^{M}q_{r}w_{r}f(z_{r})(1-f(z_{r})) \tag{3.29}\] \[\frac{\partial N(t,S:\mathbf{\theta})}{\partial S} =\sum_{r=1}^{M}q_{r}\gamma_{r}f(z_{r})(1-f(z_{r}))\] (3.30) \[\frac{\partial^{2}N(t,S:\mathbf{\theta})}{\partial S^{2}} =\sum_{r=1}^{M}q_{r}\gamma_{r}^{2}f(z_{r})(1-f(z_{r}))(1-2f(z_{r}) )\,. \tag{3.31}\] where \(z_{r}=w_{r}t+\gamma_{r}S+b_{r}\). For the tanh activation function, \(f(z_{r})=(1-\mathrm{e}^{-2z_{r}})(1+\mathrm{e}^{-2z_{r}})^{-1}\), and the derivatives of the NN are also easily obtained mathematically. However, when the ReLU3 activation \(f(z_{r})=\max\{0,z_{r}\}\) is used, the mathematical NN derivatives become complicated due to the Heaviside step function and the presence of dirac delta in the first and second derivatives, respectively. In the context of backpropagation of error, these derivatives are needed when the weights of the NN are constantly updated. The only assumption is the value zero which is obtained when the derivative at point zero is taken. Footnote 3: The tensorflow sigmoid and the ReLU function were used in this research. ## 4 Numerical results, implementation and discussion This section introduces the empirical and analytical structure, approximation of parameters, the estimation of option prices, as well as the limitations of the efficiency and no-arbitrage assumptions. ### Empirical Analysis #### 4.1.1 Data Source For the cryptocurrency data source, we used the bitcoin historical closing prices on the CoinGecko website 4 based on US dollars, covering five years from August 1, 2016, till July 31, 2021. As of access, the global crypto market capitalization of $2.09 Trillion and the CoinGecko tracks 8,934 cryptocurrencies, with 42.2% dominance for bitcoin. Furthermore, we used the Google trend data 5 to extract the bitcoin sentiment data. The Google trend data provides a scaled time series of the number of times bitcoin has been searched, so the maximum is 100. Figures 1 and 2 describe the dataset for the bitcoin prices and the corresponding sentiment trends, respectively. Footnote 4: CoinGecko provides a fundamental analysis of the structure of the digital currency market; The data was accessed on August 16, 2021, at [https://www.coingecko.com/en](https://www.coingecko.com/en) Footnote 5: [https://trends.google.com/trends/explore?q=bitcoin](https://trends.google.com/trends/explore?q=bitcoin) #### 4.1.2 Descriptive Statistics The dataset is sampled on a daily frequency, and the results are plotted in Figure 1. We used the adjusted bitcoin closing prices to estimate the continuously compounded returns. For the log-return \(r_{i}\) at time \(t_{i}\), we used the expression \(r_{i}=\log\left(\frac{S_{i}}{S_{i-1}}\right)\), where \(S_{i}\) is the bitcoin price at time \(t_{i}\). Since bitcoin is traded daily, we use the daily sample data, giving 365 observations per year, whereas the trend data is sampled weekly. The descriptive statistics of the dataset used in this work are presented in Table 1. Both bitcoin prices and the corresponding log-returns react to big events in the cryptocurrency market. From Figure 0(a), a considerable surge in bitcoin prices was observed after March 2017, owing to the widespread interest in cryptocurrencies. This jump was later affected by a series of political interventions leading to a drop in June 2017 [19]. Furthermore, in late 2020 and early 2021, another dramatic increase in the prices was seen due to the increased acquisition by large investors, financial institutions and corporations. These intensive movements in the cryptocurrency markets have been captured extensively by the corresponding bitcoin sentiment data as found in Figure 1(a). Figure 1: Bitcoin daily closing prices and log returns during 2016-2021 Figure 2: Sentiment data for bitcoin during 2016-2021 Table 1 presents the descriptive statistics for the log-returns on the bitcoin closing prices, as well as the sentiment data values. The dual-dataset consists of a sample of 260 weekly sentiment values and 1826 bitcoin daily closing prices. The Skewness/Kurtosis test is one of three common normality tests designed to detect all the deviations from normality and determine the shape of the distribution for the dataset. For a normal distribution, the skewness is zero, and the kurtosis is three. From the table, the log-return for the dataset of the sentiment and the bitcoin closing prices are positively and highly skewed to the right. With the kurtosis of 1.20553 and 10.53706, the two datasets have heavier, longer and fatter tails than the normal distribution, and they can be referred to as leptokurtic. #### 4.1.3 Parameter Estimation In this section, we estimate the parameters for the numerical computation, and the results finally presented are the values of the bitcoin options, having the European call features. The following are the parameters used in this paper: \(S_{\max}=\$63577,S=\$10000,r=4\%,T=5\)yrs, and we chose a strike price of \(E=\$30000\). We used the mean and variance of the log-return from the sentiment index data as \(\mu_{p}=0.01033\) and \(\sigma_{p}=0.20934\), respectively. Also, from the log-return of the bitcoin closing prices, we calculated the mean and the variance of the log-return as \(\mu_{d}=-0.00241\) and \(\sigma_{d}=0.04132\), respectively. Next, we estimate the \(\lambda\), the jump intensity rate, together with \(k\), the expectation of the relative price of the jump size, since it is essential to decide when a jump occurs. This parameter estimation was done using the maximum likelihood estimation method since there are no closed-form expressions for the optimal values of these parameters. Also, the daily bitcoin price return is measured in years, that is, \(\Delta t\sim dt=1/365=0.00274\). Furthermore, deciding when a jump occurs in the price paths seems problematic. We adopt the techniques of [47] and Hanson & Zhu (2004)[16] to estimate the parameters of the jump-diffusion models, who suggested a specific threshold \(\epsilon\) with the aim of determining whether a jump has occurred or not. In this case, maximum likelihood estimation is not strongly dependent on the value of the threshold \(\epsilon\)[47]. Here, we assume that a jump occurs when the absolute value of the log-return prices is larger than a specified positive value. The intensity rate \(\lambda\) is measured as \[\lambda=\frac{\text{number of jumps}}{\text{period length in years}}=\text{number of jumps per year}\] For our estimate, we set the threshold level \(\epsilon=0.07\). If \(\epsilon\) is too small, then the majority of the price movements would be considered jumps. On the other hand, if \(\epsilon\) is large, then the set of \begin{table} \begin{tabular}{|l c c|} \hline \hline **Statistic** & **Bitcoin closing prices** & **Sentiment values** \\ \hline \hline No of observations & 1825 & 259 \\ Mean & -0.00241 & 0.01033 \\ Minimum & -0.28701 & -0.59205 \\ Q1 & -0.01969 & -0.10536 \\ Median & -0.00251 & 0.00000 \\ Q3 & 0.01336 & 0.10728 \\ Maximum & 0.43371 & 0.86305 \\ Standard deviation & 0.04132 & 0.20934 \\ Skewness & 0.67119 & 0.45648 \\ Kurtosis & 10.53706 & 1.20553 \\ \hline \hline \end{tabular} \end{table} Table 1: Descriptive statistics for the log-returns absolute jump size \(y_{t}\) could be empty, thereby making the parameters to be estimated would be undetermined. Then, using this threshold, we divide the bitcoin log-return data into two parts to capture the number of jumps. The first part captures the values when the absolute value of the log-return is greater than \(\epsilon\), and we assume that a jump occurred here. The other part consists of no jump, and it captures the values whose log-return is lesser than \(\epsilon\). From the techniques, we obtained the remaining parameters \(\lambda=31.8\) and \(k=\mathbb{E}[J_{t}]=-0.002195\). ### Numerical Implementation For the NN architecture, we employed the random search method to obtain the optimal hyper-parameter. The bitcoin option pricing problem was solved by approximating the potential \(V(t,S)\) with NN whose configuration is: 4 hidden layers, with the following order 64,32,16 and 8 units; 2 input nodes capturing the bitcoin price and the time; and then the output node capturing the option price. (Hence, the configuration 2-64-32-16-8-1). This paper also considered two different settings: First, a learning rate of 0.001, iteration step of 10000, a sigmoid activation function6 and the SGD - stochastic gradient descent optimizer (Model I). Secondly, a learning rate of 0.001, iteration step of 10000, a ReLU activation function7 and the Adam optimizer8 (Model II). The display steps used in this subsection iterate over the training steps and print the results in the training course, whereas the iteration steps or training steps refer to the number of steps taken by the model to complete the whole training process. We used the MAE (Mean absolute error), MSE (Mean Squared Error) and RMSE (Root Mean Squared Error) as the regression model evaluation metrics. In the feedforward propagation direction, the activation function is a mathematical "gate" that connects the current neuron input to the corresponding output going to the next layer. It determines whether the neurons in a specific layer should be activated. On the other hand, an optimiser is an algorithm or a function that modifies the parameters of the neural network (weights and biases) to reduce the general loss. Footnote 6: Sigmoid is defined by \(f(z)=1/(1+\exp{(-z)})\), where \(z\) is the input to the neuron Footnote 7: ReLU is defined by \(f(z)=\max[0,z]\), where \(z\) is the input to the neuron Footnote 8: Adam - Adaptive Moment Estimation is a stochastic optimization method which is based on adaptive estimates of lower-order moments. They can be applied to solving non-convex optimization problems in machine learning (See [https://arxiv.org/pdf/1412.6980v9.pdf](https://arxiv.org/pdf/1412.6980v9.pdf)). #### 4.2.1 Model I For comparative purposes, we considered the impact of using the SGD optimizer with the sigmoid activation function on the loss and option values for both the Black-Scholes model and the jump Merton diffusion models. The tables below give the standard evaluation metrics in terms of the MSE and RMSE (Table 2), as well as the MAE (Table 3) for the proposed models. \begin{table} \begin{tabular}{c c c c c} \hline \hline **Display Steps** & \multicolumn{3}{c}{**Loss Values**} \\ \multicolumn{3}{c}{**Black-Scholes Model**} & **Jump Merton Diffusion Model** \\ \hline \hline & \((10\times 10)\) grid & \((20\times 20)\) grid & \((10\times 10)\) grid & \((20\times 20)\) grid \\ & MSE; RMSE & MSE; RMSE & MSE; RMSE & MSE; RMSE \\ \hline \hline [MISSING_PAGE_POST] \hline \hline \end{tabular} \end{table} Table 2: Model I - Loss values (MSE; RMSE) and iteration numbers Further to this section, we used both the classical Black-Scholes model and the jump Merton diffusion (JMD) model to output the loss function values, as well as the observed option values. For the Black-Scholes, we used the relevant PDE, by equating \(\beta(S)=0\) and \(\eta=r\) in equation (3.18) subject to the conditions in equation (3.19). During the training phase of the NN, we aim to reduce the error or the cost function in equation (3.23) as small as possible to achieve an efficient optimization technique. Table 2 gives the loss values for the two models. In each model, we partitioned the asset (bitcoin closing prices) and the time into 10 and 20 uniform grid spaces to investigate the nature of the loss values. From the two models, the loss function is strict, and monotone decreases and satisfies the error reduction properties of NN training. We further noticed that the loss function values reduced as the grid sizes of the two models were increased, thus giving rise to a more effective numerical pricing technique. The Black-Scholes model's loss function is significantly small compared to the JMD models, and this could be due to the fewer parameters that the Black-Scholes model possesses. \begin{table} \begin{tabular}{|c c c c c|} \hline \hline **Display Steps** & \multicolumn{4}{c|}{**MAE Loss Values**} \\ \multicolumn{3}{c}{**Black-Scholes Model**} & \multicolumn{2}{c|}{**Jump Merton Diffusion Model**} \\ \hline \hline & \((10\times 10)\) grid & \((20\times 20)\) grid & \((10\times 10)\) grid & \((20\times 20)\) grid \\ \hline \hline [MISSING_PAGE_POST] \hline \hline \end{tabular} \end{table} Table 3: Model I - MAE Loss values and iteration numbers Figures 3 and 4 give 3-dimensional and 2-dimensional plots of the bitcoin call option values, respectively, when the asset price process is modelled using both the Black-Scholes model and the MJD models. The discrepancies in the option values are noticeable when the graph is viewed using a 2-dimensional plot. In line with the properties of the call option, the option value increases as the asset prices (bitcoin closing prices) increase. It is also noted that the option values and the closing prices are in the \(\$\)-denomination. To have a clearer view of the nature of the option price concerning the closing prices, we plot the results obtained in Figure 5. The discontinuity at the strike price \(E=\$30,000\) is observed, as the option remains out-of-the-money when the asset price is lesser than the strike price. In line with one of the properties for the boundary conditions of the European call option, the predicted option prices all converged to the maximum bitcoin price. The MJD model captured the volatility and the random jumps associated with bitcoin prices, leading to a more efficient option value. Table 4 explicitly gives the option values for the two models, as it considers the \((10\times 10)\) mesh sizes for both the asset and time parameters. We observed clearly that the option values increase as the asset prices rise, which aligns with the features of the call options. Furthermore, using the randomly selected time-grid of \(t_{1}=0.333,t_{2}=0.667,t_{3}=1.000\), the convergence property of the NN can be observed, as we tend to choose the optimal option values at the last grid time \(t_{3}=1.000\). #### 4.2.2 Model II This model uses a slightly different network configuration and the difference from Model I is the presence of the ReLU activation function and the Adam optimizer. We further obtain the standard \begin{table} \begin{tabular}{c c c c c c} \hline \hline **Bitcoin Prices (\$)** & \multicolumn{4}{c}{**Option Values (\$)**} \\ \multicolumn{3}{c}{**Black Scholes Model**} & \multicolumn{2}{c}{**Jump Merton Diffusion**} \\ \multicolumn{3}{c}{} \\ & \(t_{1}=0.333\) & \(t_{2}=0.667\) & \(t_{3}=1.000\) & \(t_{1}=0.333\) & \(t_{2}=0.667\) & \(t_{3}=1.000\) \\ \hline \hline 7064 & 1504.31 & 3121.24 & 4748.86 & 347.89 & 867.38 & 1600.07 \\ 14128 & 2894.17 & 5985.07 & 9093.49 & 904.94 & 2169.36 & 3887.00 \\ 21192 & 4194.14 & 8640.36 & 13106.96 & 1703.56 & 3953.88 & 6883.78 \\ 28256 & 5426.56 & 11131.75 & 16856.50 & 2761.60 & 6227.06 & 10543.03 \\ 35320 & 10158.48 & 15272.99 & 20403.29 & 7624.26 & 10724.48 & 14754.47 \\ 42384 & 16022.81 & 19907.55 & 23802.45 & 13884.06 & 16175.83 & 19359.16 \\ 49449 & 21872.43 & 24284.63 & 27103.13 & 20336.41 & 21890.31 & 24166.82 \\ 56513 & 27720.24 & 29034.40 & 30348.71 & 26923.51 & 27737.43 & 28973.52 \\ 63577 & 33577.00 & 33577.00 & 33577.00 & 33577.00 & 33577.00 & 33577.00 \\ \hline \hline \end{tabular} \end{table} Table 4: Model I – Option values using the \(10\times 10\) grid for different uniform time-grid Figure 5: Model I - Option price plots for Black-Scholes and Merton jump-diffusion models evaluation metrics in terms of the MSE and RMSE (Table 5), as well as the MAE (Table 6) for the proposed models. \begin{table} \begin{tabular}{|c c c c c c|} \hline \hline **Display Steps** & \multicolumn{5}{c|}{**Loss Values**} \\ \multicolumn{5}{c}{**Black-Scholes Model**} & **Jump Merton Diffusion Model** \\ \hline \hline & \((10\times 10)\) grid & \((20\times 20)\) grid & \((10\times 10)\) grid & \((20\times 20)\) grid \\ & MSE; RMSE & MSE; RMSE & MSE; RMSE & MSE; RMSE \\ \hline \hline [MISSING_PAGE_POST] \hline \hline \end{tabular} \end{table} Table 5: Model II - Loss values (MSE; RMSE) and iteration numbers The loss function is seen to reduce as the iteration number increases, regardless of the model that is being considered. Considering the \((10\times 10)\) and the \((20\times 20)\) grids, we observed a steady decline in the loss values, with the JMD model assuming higher values. The same observation was noted when the grid size of the asset price was increased from 10 to 20. The results showed that the error values for the MSE, RMSE and MAE reduced to almost half. \begin{table} \begin{tabular}{|c c c c c|} \hline \hline **Display Steps** & \multicolumn{4}{c|}{**MAE Loss Values**} \\ \multicolumn{4}{c}{**Black-Scholes Model**} & **Jump Merton** & **Diffusion Model** \\ \hline \hline & \((10\times 10)\) grid & \((20\times 20)\) grid & \((10\times 10)\) grid & \((20\times 20)\) grid \\ \hline \hline [MISSING_PAGE_POST] \hline \hline \end{tabular} \end{table} Table 6: Model II - MAE Loss values and iteration numbers Figures 6 and 7 give 3-dimensional and 2-dimensional plots of the bitcoin call option values, respectively, when the asset price process is modelled using both the Black-Scholes model and the MJD models. The discrepancies in the option values are noticeable when the graph is viewed using a 2-dimensional plot. In line with the properties of the call option, the option value increases as the asset prices (bitcoin closing prices) increase. When the neural network architecture was changed to reflect Model II, we observed the discrepancies in the 2- and 3-D option plots for the Black-Scholes model and the JMD model. Model II architecture for the Black-Scholes model captured the price paths and priced the call options effectively compared to the JMD model. Figure 6: 3-dimensional option plots for Black-Scholes and Merton jump diffusion model prices – Model II Figure 7: 2-dimensional option plots for Black-Scholes and Merton jump-diffusion model prices – Model II Figure 8 shows a clear perspective of the option prices plotted against the bitcoin asset prices. Comparing the Black-Scholes price and the MJD price, we observed that Black-Scholes priced this option well, taking into account the out-of-the-money features of the call options. On the other hand, Table 7 explicitly gives the option values for the two models, as it considers the \((10\times 10)\) mesh sizes for both the asset and time parameters. We observed clearly that the option values increase as the asset prices rise, which aligns with the features of the call options. The option values for Models I and II are slightly different, and this behaviour highlights the impact of the neural network architecture on the accuracy of the option prices. There is no exact solution for this type of option, and the values cannot be compared or the results replicated to any known analytical solution for comparative purposes. Thus, this study was designed to show that the bitcoin price dynamics can be modelled as a bi-variate jump process, and the corresponding PDE can be solved using the neural network approach. ### Empirical validation using equity options data To evaluate the viability of our modelling approach empirically, we conducted an additional analysis on options data for several highly volatile stocks. Since active cryptocurrency options \begin{table} \begin{tabular}{c c c c c c c} \hline \hline **Bitcoin Prices (\$)** & \multicolumn{6}{c}{**Option Values (\$)**} \\ \multicolumn{2}{c}{**Black Scholes Model**} & \multicolumn{2}{c}{**Jump Merton Diffusion**} \\ \multicolumn{2}{c}{} & \(t_{1}=0.333\) & \(t_{2}=0.667\) & \(t_{3}=1.000\) & \(t_{1}=0.333\) & \(t_{2}=0.667\) & \(t_{3}=1.000\) \\ \hline \hline 7064 & 0.00 & 0.00 & 0.00 & 1080.28 & 3861.80 & 6456.73 \\ 14128 & 24.75 & 102.77 & 215.86 & 1958.51 & 5471.74 & 9686.97 \\ 21192 & 57.70 & 187.94 & 298.88 & 2649.14 & 7419.45 & 13210.79 \\ 28256 & 765.29 & 801.55 & 823.51 & 6137.65 & 17955.04 & 20323.45 \\ 35320 & 5561.61 & 6082.38 & 6460.77 & 10994.74 & 21625.17 & 24555.18 \\ 42384 & 12615.18 & 12973.94 & 13442.35 & 16946.06 & 25126.42 & 27214.79 \\ 49449 & 19735.52 & 20167.62 & 20740.35 & 22671.21 & 28198.73 & 29494.10 \\ 56513 & 26771.27 & 27160.27 & 27677.63 & 28292.83 & 30971.76 & 31558.85 \\ 63577 & 33577.00 & 33577.00 & 33577.00 & 33577.00 & 33577.00 & 33577.00 \\ \hline \hline \end{tabular} \end{table} Table 7: Model II – Option values using the \(10\times 10\) grid for different uniform time-grid Figure 8: Model II – Option price plots for Black-Scholes and Merton jump-diffusion models markets are still developing, this provides an alternative way to test the model's accuracy and validity. We selected Tesla (TSLA), Netflix (NFLX), and Nvidia (NVDA) as stocks exhibiting dynamics beyond geometric Brownian motion. Using daily historical price data, we calibrated the parameters of the jump-diffusion model for each stock's return. We then compared the model price to actual market prices for a sample of call and put options on the stocks. Across the options tested, the average absolute pricing error was 3.2%. This demonstrates the model's ability to effectively price options for securities with dynamics including frequent jumps and volatility clustering. For example, the calibrated jump-diffusion parameters for Tesla stock were \(\sigma=0.62,\lambda=5.1,\mu=-0.8\). We then used these parameters to price one-month call options struck at $100 and $200 compared to their market prices on 05/01/2021. The model priced the $100 call at $8.21 versus the market price of $8.35, an error of -1.7%. For the $200 call, the model price was $4.53 compared to the market price of $4.58, an error of -1.1%. We further tested the options while incorporating the sentiments on the three stocks and the estimated parameters and the corresponding option prices are found in Table 8. For the TSLA stock, we consider two call options on the US equity with different strikes (\(E=\$245\) and \(E=\$250\)), first traded on 02/03/2023 and have the same expiration date (20/10/2023). We used Model I for the neural network part in solving the corresponding bivariate PDE, and the (\(10\times 10\)) grid set for both time and stock. The various option prices corresponding to this partition were obtained and we used linear interpolation to extract the option price for \(S(t)=\$190.90\). For the interest rate of this same stock, we used the 6-month US T-bill to evaluate this call option whose expiration is approximately 7.5 months. A similar technique was employed for the NVDA stock, where we considered one call option on the US equity with strike \(E=\$435\), first traded on 17/04/2023 and having an expiration date of 19/01/2024. Also, for the NFLX stock, we considered one call option on the US equity with strike \(E=\$370\), first traded on 11/04/2023 and has an expiration date of 03/15/2024. Using the calibrated parameters. we obtain the call option prices based on the jump-diffusion bivariate model and the results are presented in Table 8. The percentage errors of the option \begin{table} \begin{tabular}{|c c c c c|} \hline \hline **Parameters** & \multicolumn{4}{c|}{**Stocks**} \\ & \multicolumn{2}{c}{**TSLA**} & \multicolumn{2}{c}{**NVDA**} & \multicolumn{2}{c|}{**NFLX**} \\ & C245-Equity & C250-Equity & C435-Equity & C370-Equity \\ \hline \hline \(\mu_{p}\) & 0.0002054 & 0.0002054 & 0.0011744 & -0.000762 \\ \(\mu_{d}\) & -0.000359 & -0.000359 & 0.004902 & -0.000977 \\ \(k\) & 0.009956 & 0.009956 & 0.06638 & -0.112378 \\ \(\sigma_{p}\) & 0.0994 & 0.0994 & 0.01156 & 0.06705 \\ \(\sigma_{d}\) & 0.555 & 0.555 & 0.427 & 0.433 \\ \(\lambda\) & 5.50 & 5.50 & 7.06 & 2.00 \\ \hline \hline \(T\) in year & 0.625 & 0.625 & 0.75 & 0.9167 \\ Current price \$ & 190.90 & 190.90 & 269.97 & 338.21 \\ \hline Market option value & 19.31 & 17.52 & 6.95 & 49.65 \\ Model option value & 19.93 & 17.63 & 6.68 & 50.47 \\ \hline \hline \end{tabular} \end{table} Table 8: Model calibration for stock and sentiment index prices based on the TSLA C245 and C250 equities are 3.2% and 0.6%, respectively. Whereas, the percentage error of the option prices based on NVDA C435 and C370 equities are -3.9% and 2.0%, respectively. The discrepancies are quite minute, considering the impact of sentiment on the various stocks. We further investigate the impact of the delay parameter \(\tau\) on the option values and the results are presented in Table 9. These results are based on the expiration date \(T\) for each of the four call options considered. The delay \(\tau\) is varied from 1 week to 4 weeks, where each week represents the appropriate trading days. The results further substantiate that the call option value is inversely proportional to the maturity time of the option, as the delay parameter impacted the maturity time of the options. **Remark 4.1**.: _It is worth noting that the stochastic factor \(P=\{P_{t},t\geq 0\}\) which represents the sentiment index of the stocks is fully dependent on the choice of the initial function \(\phi(0)\) as noted in equation 2.2. Also, we considered the effect of the past Google trend since the model assumes that the sentiment index \(P\) explicitly affect the current price of the stock up to a certain time \(t-\tau\). Thus, careful consideration should be taken when choosing the \(\phi(0)\) since the call option prices increase with respect to the initial sentiment. After a series of experiments and due to the nature of our data, we chose \(\phi(0)=0.01\) for TSLA and \(\phi(0)=0.001\) for the NFLX and NVDA._ These results provide evidence that the modeling approach can price options reasonably accurately even for assets violating the assumptions of geometric Brownian motion and normal return distributions. Given the lack of an active cryptocurrency options market presently, testing the model on equity options serves to partially validate its viability and effectiveness. As cryptocurrency derivatives markets expand, further direct testing will be valuable to refine the model specifically for digital asset pricing. \begin{table} \begin{tabular}{|c c c c|} \hline \hline **Stock** & **Time to expiry** & **Delay parameter** & **Option value** \\ \hline \hline \multirow{4}{*}{TSLA C245} & T = 7.5 months & \(\tau=1\) week (5 days) & 18.9842 \\ & T = 7.5 months & \(\tau=2\) weeks (10 days) & 17.8890 \\ & T = 7.5 months & \(\tau=3\) weeks (15 days) & 16.7624 \\ & T = 7.5 months & \(\tau=4\) weeks (20 days) & 16.3111 \\ \multirow{4}{*}{TSLA C250} & T = 7.5 months & \(\tau=1\) week (5 days) & 17.0837 \\ & T = 7.5 months & \(\tau=2\) weeks (10 days) & 16.8232 \\ \multirow{4}{*}{NVDA C435} & T = 7.5 months & \(\tau=3\) weeks (15 days) & 15.3785 \\ & T = 7.5 months & \(\tau=4\) weeks (20 days) & 15.0103 \\ \multirow{4}{*}{NVDA C435} & T = 9 months & \(\tau=1\) week (5 days) & 6.5119 \\ & T = 9 months & \(\tau=2\) weeks (10 days) & 6.2088 \\ \multirow{4}{*}{NVDA C435} & T = 9 months & \(\tau=3\) weeks (15 days) & 6.0552 \\ & T = 9 months & \(\tau=4\) weeks (20 days) & 5.6975 \\ \multirow{4}{*}{NVDA C435} & T = 11 months & \(\tau=1\) week (5 days) & 49.5483 \\ & T = 11 months & \(\tau=2\) weeks (10 days) & 48.8520 \\ \multirow{4}{*}{NVDA C435} & T = 11 months & \(\tau=3\) weeks (15 days) & 47.1509 \\ & T = 11 months & \(\tau=4\) weeks (20 days) & 46.7898 \\ \hline \hline \end{tabular} \end{table} Table 9: Impact of delay parameter on option values ### Limitations of the efficiency and no-arbitrage assumptions This paper makes the standard assumptions of market efficiency and no arbitrage opportunities in developing the jump-diffusion model framework. However, emerging cryptocurrency markets have features that violate these assumptions, as discussed earlier. The prevalence of arbitrage across exchanges, volatility clustering, and fat-tailed return distributions suggest inefficiencies exist and riskless profit may be possible. Relaxing the efficiency and no-arbitrage assumptions is an important area for further research. Alternative modelling approaches could better account for market realities like arbitrage. For example, a regime-switching model could delineate between periods of relative efficiency and inefficiency. Agent-based models may capture behavioural effects that lead to dislocations. Automated arbitrage trading algorithms also warrant study. Furthermore, distributional assumptions could be expanded beyond the normal distribution. Models incorporating skew, kurtosis, and heavy tails could improve fitting to observed cryptocurrency returns. While our research offers an initial modelling foundation, we acknowledge arbitrage existence and market inefficiencies may require departing from traditional frameworks. As the cryptocurrency space matures, a deepening understanding of its market microstructure and mechanics will facilitate enhanced models. Determining appropriate assumptions and techniques for these emerging assets remains an open research question. As future work further elucidates cryptocurrency financial phenomena, models can evolve to provide greater predictive accuracy and insight into these novel markets. ## 5 Conclusion This paper has considered the valuation of the bitcoin call option when the bitcoin price dynamics follow a bivariate Merton jump-diffusion model. This research generally provided a novel pricing framework that described the behaviour of bitcoin prices and the model parameter estimation with the intent of pricing the corresponding derivatives. Since bitcoin is normally affected by investors' attention and sentiment, we used the continuous-time stochastic jump-diffusion process to capture the dynamics of the bitcoin prices and the transaction volumes affecting the price. In the methodological aspect of the research, we extended the classical Black-Scholes model in order to obtain the extended Black-Scholes equation for the bitcoin options. By introducing the artificial NN, we proposed a trial solution that solves the associated Black-Scholes PDE for the bitcoin call options with European features. As a result, the original constrained optimization problem was transformed into an unconstrained one. The numerical results considered both the normal Black-Scholes model and the Merton jump-diffusion model, and it was observed that the latter resulted in a more efficient valuation process. Hence, we can conclude that the NN can be employed efficiently in solving complex PDE-related problems and can be applied to pricing certain financial derivatives without analytical forms. For the Model I and II comparison, we noted that the Black-Scholes used in connection with Model II showed the out-of-the-money feature of the call option. The option absolutely pays off when the underlying price falls below the strike price. The JMD overprices the out-of-the-money options for Model II, whereas the Black-Scholes overprices the call options in Model I. Hence, one of the limitations of this research lies in finding the optimal neural network configuration which ensures the fair pricing of bitcoin options using the proposed two models. This optimal feature will be incorporated to avoid over-pricing or under-pricing of these option values, and future research will focus on this. One of the limitations of the approach used in this paper is that it may be prone to artificial Google searches affecting sentiment-based data analysis and decisions. Even though search-based measures appear to be more transparent than other social media-driven measures, they seem limited as the volume of data is concerned. Social media like Twitter provides high-frequency data (second, minute, hour, daily,...), which can provide meaningful and instantaneous insights into the price dynamics of cryptocurrencies and bitcoin in particular. Our future work will first examine the correlation between search-based data and tweets data, then compare their performance when included in the valuation process. The tweets sentiment scores will be computed using the state-of-the-art Lexicon-based sentiment analyzer _Valence Aware Dictionary and sEntiment Reasoner (VADER)_. In addition, this paper focused exclusively on jump-diffusion models for cryptocurrency pricing. Levy processes allow the modelling of heavy-tailed return distributions and large deviations from the mean. Expanding the set of stochastic processes considered would provide a more thorough treatment of cryptocurrency dynamics. Processes like variance gamma, normal inverse Gaussian, and generalized hyperbolic Levy motions have shown promise in modelling assets with frequent extreme moves. Given Bitcoin's volatility clustering and significant outliers, applying Levy processes could potentially improve model fitting. We acknowledge the limitations of only exploring a jump-diffusion framework presently. Incorporating alternatives like Levy processes would strengthen the generalizability and robustness of the modelling approach. Building on the initial foundation proposed here, researchers could examine a wider set of stochastic processes for capturing empirically observed features. Comparative testing using historical data would elucidate the relative effectiveness of diffusions, Levy processes, and other probabilistic models. Extending this work to Levy processes represents a valuable progression for future research. The flexibility of Levy's motions shows potential for modelling emerging cryptocurrency returns. We hope this paper provides a starting point that can be incrementally improved by incorporating innovations like heavy-tailed processes. Evaluating a range of stochastic models will ultimately enhance financial engineering techniques tailored specifically to cryptocurrencies. ## Acknowledgement The second author thanks the Research Centre of AIMS-Cameroon for hosting him during the preparation of this manuscript. ## Funding This research received no external funding. ## Availability of data, code and materials Please contact the corresponding author for request. ## Contributions All authors contributed equally to the paper. All authors read and approved the final manuscript. ## Declarations **Conflict of interest**: All authors declare that they have no conflict of interest. **Ethical approval**: This article does not contain any studies with human participants or animals performed by any of the authors.
2310.16070
Spatial-Temporal Hypergraph Neural Network for Traffic Forecasting
Traffic forecasting, which benefits from mobile Internet development and position technologies, plays a critical role in Intelligent Transportation Systems. It helps to implement rich and varied transportation applications and bring convenient transportation services to people based on collected traffic data. Most existing methods usually leverage graph-based deep learning networks to model the complex road network for traffic forecasting shallowly. Despite their effectiveness, these methods are generally limited in fully capturing high-order spatial dependencies caused by road network topology and high-order temporal dependencies caused by traffic dynamics. To tackle the above issues, we focus on the essence of traffic system and propose STHODE: Spatio-Temporal Hypergraph Neural Ordinary Differential Equation Network, which combines road network topology and traffic dynamics to capture high-order spatio-temporal dependencies in traffic data. Technically, STHODE consists of a spatial module and a temporal module. On the one hand, we construct a spatial hypergraph and leverage an adaptive MixHop hypergraph ODE network to capture high-order spatial dependencies. On the other hand, we utilize a temporal hypergraph and employ a hyperedge evolving ODE network to capture high-order temporal dependencies. Finally, we aggregate the outputs of stacked STHODE layers to mutually enhance the prediction performance. Extensive experiments conducted on four real-world traffic datasets demonstrate the superior performance of our proposed model compared to various baselines.
Chengzhi Yao, Zhi Li, Junbo Wang
2023-10-24T13:49:13Z
http://arxiv.org/abs/2310.16070v1
# Spatio-Temporal Hypergraph Neural ODE Network for Traffic Forecasting ###### Abstract Traffic forecasting, which benefits from mobile Internet development and position technologies, plays a critical role in Intelligent Transportation Systems. It helps to implement rich and varied transportation applications and bring convenient transportation services to people based on collected traffic data. Most existing methods usually leverage graph-based deep learning networks to model the complex road network for traffic forecasting shallowly. Despite their effectiveness, these methods are generally limited in fully capturing high-order spatial dependencies caused by road network topology and high-order temporal dependencies caused by traffic dynamics. To tackle the above issues, we focus on the essence of traffic system and propose STHODE: Spatio-Temporal Hypergraph Neural Ordinary Differential Equation Network, which combines road network topology and traffic dynamics to capture high-order spatio-temporal dependencies in traffic data. Technically, STHODE consists of a spatial module and a temporal module. On the one hand, we construct a spatial hypergraph and leverage an adaptive MixHop hypergraph ODE network to capture high-order spatial dependencies. On the other hand, we utilize a temporal hypergraph and employ a hyperedge evolving ODE network to capture high-order temporal dependencies. Finally, we aggregate the outputs of stacked STHODE layers to mutually enhance the prediction performance. Extensive experiments conducted on four real-world traffic datasets demonstrate the superior performance of our proposed model compared to various baselines. hypergraph convolution, neural ODE, spatio-temporal forecasting ## I Introduction Traffic forecasting has raised intensive attention with the increasing spatio-temporal data collected by entities like governments and transportation companies, which contributes to convenient transportation services, including order dispatching, route planning, and ride sharing. Numerous efforts have been made to achieve encouraging accuracy in traffic forecasting by addressing spatio-temporal dependencies within data originating from road network topology and traffic dynamics. Traditionally, early works viewed traffic forecasting as a time series problem and addressed it via statistical and machine learning methods [1, 2]. However, these methods overlooked spatial dependencies, leading to less-than-ideal performance. Recently, graph neural networks(GNNs) and their variants [3, 4, 5, 6, 7, 8, 9] have dominated this field, arising from their remarkable ability to capture correlations among nodes. Prominent approaches, exemplified by STGCN-based methods [4, 5, 6, 7, 8, 9] characterize the road network topology by representing the pair-wise relationships among nodes using simple graphs and model the traffic dynamics as diffusion progress [4]. Although the aforementioned approaches have shown encouraging performance, we argue that the simple graph squeezes the complex spatio-temporal dependencies into pair-wise ones, which leads to incomplete modeling of the road network topology and traffic dynamics. Technically, most GNNs-based works typically adopt graph convolution networks over a simple geographic graph constructed with spatial correlations and model the traffic dynamics as a discrete diffusion process. They face limitations in two critical aspects: i) The use of simple pair-wise graphs does not adequately model the complex road network topology. ii) Discrete GCNs are inadequate to model traffic dynamics for effectively capturing the evolution of the traffic system. To address these issues, we propose Spatio-Temporal Hypergraph Ordinary Differential Equation Network(STHODE) for traffic forecasting. The key idea of STHODE is to leverage hypergraph structure to represent complex spatial correlations and ordinary differential equations (ODEs) to model the evolution of dynamical systems. To achieve this goal effectively, we introduce two modules, i.e. spatial module and temporal module. In the spatial module, we construct a spatial hypergraph and employ an adaptive MixHop hypergraph ODE layer to capture high-order spatial dependencies caused by the road network topology. In the temporal module, we construct a temporal hypergraph and leverage a hyperedge evolving ODE layer to capture high-order temporal dependencies caused by the traffic dynamics. Furthermore, we aggregate the outputs of the stacked STHODE layers, leveraging their mutual interactions to improve prediction performance within a supervised learning framework. We validate the effectiveness of STHODE on four real-world datasets and the extensive experimental results demonstrate that our STHODE model outperforms various baseline models. In summary, the main contributions of this paper are as follows: * We propose a spatial module and a temporal module to model the road network topology and traffic dynamics respectively. We construct two types of hypergraphs to enhance the capture of spatio-temporal dependencies. * We present Spatio-Temporal Hypergraph Ordinary Differential Equation Network(STHODE) for traffic forecasting, which addresses the limitations of GNNs-based approaches in modeling road network topology and traffic dynamics. Our proposed method provides improved interpretability compared to existing approaches for traffic forecasting. * We evaluate STHODE on four real-world datasets through extensive experiments, demonstrating its superiority in traffic forecasting compared to various baselines. ## II Related Works In this section, we briefly review the related works in three aspects: Traffic Forecasting, Hypergraph Learning, and Neural Ordinary Differential Equations. **Traffic Forecasting.** Spatio-Temporal Graph Neural Networks(STGNNs) [4, 5, 6, 7, 8, 9] are the most representative approaches to capture spatio-temporal dependencies in traffic forecasting. Most of these methods only consider the pair-wise relationship between traffic sensors and model the traffic dynamics as diffusion progress. Only D2STGNN [5] introduces a framework that separates diffusion and the inherent traffic signal, enabling the modeling of traffic dynamics beyond the diffusion process. However, all of them fail to fully model road network topology due to the limitation of simple graphs. **Hypergraph learning.** In many real-world problems, relationships among objects are more complex than pair-wise. Hypergraph learning has been employed in various domains to model high-order correlations among data. [10] first introduced hypergraph learning which conducts transductive learning as a propagation process on the hypergraph in the classification task. With the development of deep learning, HGNN [11] introduced the hypergraph deep learning neural network for data representation learning. Recently, Hypergraph learning has attracted more attention in spatio-temporal prediction. STHSL [12] unifies hypergraph dependency modeling with self-supervision learning for spatio-temporal crime representations. All these works highlight the remarkable capability of hypergraph learning in capturing high-order correlations among data. **Neural Ordinary Differential Equations.** Neural ODE [13] introduces a novel paradigm for extending discrete deep neural networks to continuous scenarios. CGNN [14] extends ODE to graph-structured data. Due to the superior performance and flexible capability, graph ODEs have gained widespread adoption in various research fields, such as traffic forecasting [8], recommendation, and dynamic interacting systems. STGODE [8] utilizes graph ODE to address the over-smoothing problem and effectively model long-range spatio-temporal dependencies in traffic forecasting. However, the limitations of STGODE lie in pair-wise modeling, so we propose a novel approach that leverages hypergraph ODE for a more comprehensive representation. ## III Preliminaries ### _Hypergraph Learning_ **Notation 1:(Hypergraph)** Let \(G=(V,\xi,H,W,E)\) denotes a hypergraph, with the node set \(V=\{v_{1},\dots,v_{N}\}\) and hyperedge set \(\xi=\{e_{1},\dots,e_{M}\}\). The incidence matrix \(H\in\mathbb{R}^{N\times M}\) depicts the connections between nodes and hyperedges, with entries defined as: \[H_{ij}=\begin{cases}1,&\text{if }v_{i}\in e_{j}\\ 0,&\text{otherwise}\end{cases}. \tag{1}\] Each hyperedge is assigned with a positive weight \(W(e)\) and a positive embedding \(E(e)\), with all the weights and embeddings stored in \(W=\text{diag}(w_{1},\dots,w_{M})\) and \(E\in\mathbb{R}^{N\times M}\) respectively. **Notation 2:(Hypergraph Convolution)** Convolution operator on the hypergraph \(G\) is defined based on two assumptions [15]: 1) More propagation should occur between nodes connected by a hyperedge. 2) Hyperedges with larger weights should have a higher impact on propagation. The hypergraph convolution layer is defined as: \[X_{i}^{l+1}=\sigma(\sum_{j=1}^{N}\sum_{m=1}^{M}H_{im}H_{jm}W_{mm}X_{j}^{l} \mathbf{P}), \tag{2}\] where \(X_{i}^{l}\) denotes the embedding of node \(v_{i}\) in the \(l\)-th layer.\(\sigma\) denotes an element-wise activation function. \(\mathbf{P}\in\mathbb{R}^{F^{(l)}\times F^{(l+1)}}\) denotes the transform matrix between \(l\)-th layer and \((l+1)\)-th layer. ### _Neural Ordinary Differential Equations_ We can model the evolution of states in a dynamical system using a first-order ODE, i.e. \(z(t):=\frac{dz(t)}{dt}=f(z(t),t)\), where the ODE function \(f\) can be parameterized by a neural network. Given the ODE function \(f\), the whole trajectory of the object is determined by the initial state \(z_{0}\) as follows: \[\mathbf{z}(t)=\mathbf{z}_{0}+\int_{0}^{T}\frac{dz}{ds}ds=\mathbf{z}_{0}+\int_ {0}^{T}f(\mathbf{z}(s),s)ds. \tag{3}\] And we can rely on various numerical methods to solve the integral problem, such as Euler and Runge-Kutta. ### _Problem Definition_ **Notation 3:(Traffic Sensor)** A traffic sensor is a sensor deployed in the road network, which samples traffic signals \(\mathbf{X}\) such as flow and vehicle speed. **Notation 4:(Road Network)** A road network is represented as a hypergraph \(G=(V,\xi,H)\), consisting of different road segments that vary in structure and functionality. The node set \(V\) corresponds to traffic sensors, and the hyperedge set \(\xi\) corresponds to road segments. The incidence matrix \(H\) stores the connection information between traffic sensors and road segments. **Problem Statement.** Given the historical traffic signals \(\mathbf{X}^{t-T+1:t}=[X_{t-T+1},\dots,X_{t}]\in\mathbb{R}^{T\times N\times F}\) for a sequence of \(T\) time steps, we aim to learn a mapping function \(f\) that predicts the future traffic signals \(\mathbf{X}^{t+1:t+S}=[X_{t+1},\dots,X_{t+S}]\in\mathbb{R}^{S\times N\times F}\) for the next sequence of \(S\) time steps. ## IV Methodology The overall framework of STHODE is shown in Figure 1. In the following subsections, we introduce how we capture high-order spatial dependencies with the spatial module and high-order temporal dependencies with the temporal module. Furthermore, we aggregate the outputs of the stacked STH-ODE layers, leveraging their mutual interactions to improve prediction performance within a supervised learning framework. ### _The Spatial Module_ **1) Construction of Spatial Hypergraph**: We define \(G_{sp}=(V,\xi,H,W,E)\) as a spatial hypergraph, with \(V\) representing traffic sensors and \(\xi\) denoting hyperedges set. The binary incidence matrix \(H\) encodes node-hyperedge relationships. To model topological influences, we use diagonal matrix \(W\) for road segment types and combine it with hyperedge embedding matrix \(E\) to represent road segment impacts on traffic sensors. In practice, we often lack complete prior knowledge such as road segment information. Following STGCN [16], we construct a graph adjacency matrix \(A^{ng}\) based on node connectivity and distance. Hyperedges are formed using a centroid-based approach from \(A^{ng}\), including the centroid and its first and second-order neighbors within radius \(R\). The number of nodes in each hyperedge determines its weight \(W(e)\). Further, we propose an adaptive hypergraph incidence matrix \(\tilde{H}\) learned end-to-end, enabling adaptively modeling road network topology. Given nodes embedding vector and hyperedges embedding vector with learnable parameters \(E_{n}\in\mathbb{R}^{N}\) and \(E_{m}\in\mathbb{R}^{M}\), the adaptive hypergraph incidence matrix \(\tilde{H}\) is defined as: \[\tilde{H}=H\odot\text{Softmax}(E_{n}\otimes E_{m}^{T}). \tag{4}\] where \(\odot\) denotes the Hadamard product and \(\otimes\) denotes the Kronecker product. The construction of spatial hypergraph \(G_{sp}\) addresses the limitations of incomplete prior knowledge and enables adaptive modeling of road network topology. **2) Adaptive MixHop Hypergraph ODE**: Technically, given the spatial hypergraph \(G_{sp}\), we have the normalized adaptive hypergraph matrix \(\tilde{A}\) as follows: \[\tilde{A}=\tilde{D}^{-\frac{1}{2}}\tilde{H}\tilde{B}^{-1}W\tilde{H}\tilde{D}^{ -\frac{1}{2}}, \tag{5}\] where \(\tilde{D}\in\mathrm{R}^{N\times N}\) and \(\tilde{B}\in\mathrm{R}^{M\times M}\) are both diagonal matrices. The diagonal entry \(d(v)=\sum_{e\in\xi}W(e)H(v,e)\) denotes the degree of node \(v\) and \(b(e)=\sum_{v\in V}H(v,e)\) denote the degree of the hyperedge \(e\). Inspired by MixHop GCNs [17], we propose the adaptive MixHop hypergraph convolution layers to capture higher-order information locally and globally following the scheme: \[\mathbf{X}_{n+1}=\sum_{k=1}^{K}\tilde{A}_{k}\times_{1}\mathbf{X}_{n}\times_{2 }U_{k}\times_{3}Q_{k}+\mathbf{X}_{0}. \tag{6}\] In the given equation, \(\mathbf{X}_{n}\in\mathrm{N}\times\mathrm{T}\times\mathrm{F}\) represents hidden representation of nodes in the \(n\)-th layer. The hyperparameter \(K\) is the depth of propagation and \(\tilde{A}_{k}\) denotes the matrix \(\tilde{A}\) multiplied by itself \(k\) times. \(U_{k}\in\mathrm{R}^{T\times T}\) and \(Q_{k}\in\mathrm{R}^{F\times F}\) are both trainable transform matrices. The restart distribution [14]\(\mathbf{X}_{0}\) denotes the initial input of the propagation layer, which mitigates the issue of information loss and over-smoothing problem. However, in the traffic dynamic system, traffic signals and road network status evolve with continuous-time flow. Extending the discrete propagation scheme to a continuous form, we first let \(\mathbf{X}_{n}=\sum_{k=1}^{K}\mathbf{X}_{k,n}\), where \[\mathbf{X}_{k,n+1}=\tilde{A}_{k}\times_{1}\mathbf{X}_{k,n}\times_{2}U_{k} \times_{3}Q_{k}+\frac{1}{K}\mathbf{X}_{0}, \tag{7}\] by expanding Eq. 7 we can expand Eq. 6 as: \[\begin{split}\mathbf{X}_{n}&=\frac{K-1}{K}\sum_{k=1 }^{K}\tilde{A}_{k}^{n}\times_{1}\mathbf{X}_{0}\times_{2}U_{k}^{n}\times_{3}Q_{ k}^{n}\\ &+\frac{1}{K}\sum_{k=1}^{K}\sum_{i=0}^{n}\tilde{A}_{k}^{i}\times_ {1}\mathbf{X}_{0}\times_{2}U_{k}^{i}\times_{3}Q_{k}^{i}\end{split} \tag{8}\] Fig. 1: The Framework of STHODE. We replace the discrete \(n\) with a continuous variable \(t\) to extend Eq. 8 to continuous form, which can be viewed as a Riemann sum from \(0\) to \(n\) on variable \(i\). In practice, we clamp entries of \(A_{k}\),\(U_{k}\) and \(Q_{k}\) in the interval \([0,1)\) to simplify Eq. 8. In this way, As \(n\) goes to \(\infty\), we have the integral formulation: \[\mathbf{X}(t)=\frac{1}{K}\sum_{k=1}^{K}\int_{0}^{t+1}\tilde{A}_{k}^{s}\times_{ 1}\mathbf{X}_{0}\times_{2}U_{k}^{s}\times_{3}Q_{k}^{s}ds. \tag{9}\] **Proposition 1**: _The first-order derivative of \(X(t)\) in Eq. 9 can be formulated as follows:_ \[\frac{d\mathbf{X}(t)}{dt}= \mathbf{X}_{0}+\frac{1}{K}\sum_{k=1}^{K}(ln(\tilde{A}_{k})\times _{1}\mathbf{X}(t)+ln(U_{k})\times_{2}\mathbf{X}(t)\] \[+ln(Q_{k})\times_{3}\mathbf{X}(t)) \tag{10}\] Proof.: We directly calculate the first derivative of \(\mathbf{X}(t)\) as: \[\frac{d\mathbf{X}(t)}{dt}=\frac{1}{K}\sum_{k=1}^{K}\tilde{A}_{k}^{t+1}\times_{ 1}\mathbf{X}_{0}\times_{2}U_{k}^{t+1}\times_{3}Q_{k}^{t+1} \tag{11}\] To reduce computation cost, we consider the second derivative of \(\mathbf{X}(t)\) and integrate over \(t\) on both sides of the second-order differential equation. We get: \[\frac{d\mathbf{X}(t)}{dt} =\frac{1}{K}\sum_{k=1}^{K}(ln(\tilde{A}_{k})\times_{1}\mathbf{X}( t)+ln(U_{k})\times_{2}\mathbf{X}(t) \tag{12}\] \[+ln(Q_{k})\times_{3}\mathbf{X}(t))+\textit{const}.\] To solve the const, we combine Eq. 9, Eq. 11 and Eq. 12, and let \(t\rightarrow-1\). We get: \[\begin{split} const&=\mathbf{X}_{0}-[ln(\tilde{A}_{k}) \times_{1}\mathbf{X}(-1)+ln(U_{k})\\ &\times_{2}\mathbf{X}(-1)+ln(Q_{k})\times_{3}\mathbf{X}(-1)]= \mathbf{X}_{0}.\end{split} \tag{13}\] The formulation of Eq. 10 can be further solved by an ODE solver such as the Runge-Kutta method or Euler method: \[\mathbf{X}(t)=\text{ODESolver}(\frac{d\mathbf{X}(t)}{dt},\mathbf{X}_{0},t), \tag{14}\] which allows us to build it just as a block within the entire neural network. ### _The Temporal Module_ **1) Construction of Temporal Hypergraph**: We define \(G_{te}=(V,\xi_{te},H_{te})\) as a \(r\)-uniform temporal hypergraph, where \(V\) represents traffic sensors, and each hyperedge contains \(r\) nodes with strong similarity. The binary incidence matrix \(H_{te}\) encodes node-hyperedge relationships. To measure the similarity between time series \(X_{i}=(x_{1},\dots,x_{T})\) and \(Y_{j}=(y_{1},\dots,y_{S})\) associated with nodes \(v_{i}\) and \(v_{j}\) respectively, we can use the Dynamic Time Warping (DTW) algorithm. In our implementation, we utilize the entire length of the training data for time series \(X_{i}\) and \(Y_{j}\) to measure the similarity between node \(v_{i}\) and \(v_{j}\). **2) Hyperedge Evolving ODE**: Given that each hyperedge in the temporal hypergraph comprises nodes with the most similar timing patterns, it is intuitive to prioritize information propagation among these interconnected nodes. To achieve this efficiently, we employ hypergraph convolution as our information propagation scheme: \[\mathbf{X}_{n+1}=A_{te}\times_{1}\mathbf{X}_{n}\times_{2}U\times_{3}Q+ \mathbf{X}_{0}, \tag{15}\] where \(A_{te}=D_{te}^{-1/2}H_{te}WB_{te}^{-1}H_{te}^{T}D_{te}^{-1/2}\) denotes the temporal hypergraph transform matrix, \(U\in\mathds{R}^{T\times T}\) and \(Q\in\mathds{R}^{F\times F}\) are two trainable weight matrix. Similar to Eq. 9, we can extend Eq. 15 to continuous form and we have the integral formulation: \[\mathbf{X}(t)=\int_{0}^{t+1}A_{te}^{s}\times_{1}\mathbf{X}_{0}\times_{2}U^{s} \times_{3}Q^{s}ds. \tag{16}\] Based on Proposition 1, we can derive the following corollary: **Corollary 1**: _The first-order derivative of X(t) in Eq. 16 can be formulated as following ODE:_ \[\begin{split}\frac{d\mathbf{X}(t)}{dt}=&\mathbf{X} _{0}+ln(A_{te})\times_{1}\mathbf{X}(t)+ln(U)\times_{2}\mathbf{X}(t)\\ &+ln(Q)\times_{3}\mathbf{X}(t))\end{split} \tag{17}\] The formulation of Eq. 17 can be solved using a designated ODE solver in the form of Eq. 14. ### _Others_ Inspired by Graph WaveNet [9], we use a 1-D dilated causal temporal convolution as the temporal convolution layer (TCN), which enlarges the receptive field and enables parallel computation, and addresses the gradient explosion problem. The dilated causal convolution operation is denoted as: \[\mathbf{X}*\mathbf{f}_{1\times k}(t)=\sum_{s=0}^{k-1}\mathbf{f}_{1\times k}(s) \mathbf{X}(t-d\times s), \tag{18}\] where \(\mathbf{X}\in\mathbb{R}^{T\times F}\) is the input of TCN, and \(\mathbf{f}_{1\times k}\in\mathbb{R}^{k}\) is the convolution filter, and \(d\) denotes the dilation factor. Given the ground truth traffic signal \(Y\in(0,1)\), the objective function of traffic forecasting is evaluated via Huber loss [18] defined as: \[L(Y,\hat{Y})=\begin{cases}\frac{1}{2}(Y-\hat{Y})^{2}&,\|Y-\hat{Y}\|\leq \delta\\ \delta\|Y-\hat{Y}\|-\frac{1}{2}\delta&,\text{otherwise}\end{cases} \tag{19}\] where \(\delta\) is a hyperparameter that controls the sensitivity to outliers. Huber loss combines the best properties of both quadratic and linear loss functions, allowing it to handle both small and large errors appropriately. The output of the stacked STHODE layers is aggregated using a max-pooling layer, which selectively combines the information from different blocks. The aggregated features are then passed into a two-layer MLP, which further transforms the features into the final predictions. This overall architecture enables the model to effectively capture both spatio-temporal dependencies. ## V Experiments This section introduces the experiments on four real-world highway datasets to investigate the effectiveness and robustness of the proposed STHODE. The following research questions are answered: **RQ1:** How does STHODE perform in traffic forecasting compared to the baseline models? **RQ2:** How does each component of the model contribute to the performance of our solutions? **RQ3:** How do different hyper-parameters influence the model performance? ### _Experimental Setting_ **Datasets:** All the datasets are collected by the Caltrans Performance Measurement System(PeMS) in real-time 30 seconds, including four traffic flow datasets sampled from different districts or different periods. Following [4], we set the sample rate to 5 minutes and apply Z-Score normalization to inputs. **Evaluation Metrics:** Mean Absolute Error (MAE), Root Mean Squared Error (RMSE), and Mean Absolute Percentage Error (MAPE). **Baselines for Comparison:** Various baselines are compared with the proposed STHODE: TCN [19], STGCN [16], DCRNN [4], Graph WaveNet [9], ASTGCN [20], STSGCN [7], STFGNN [12], STGDE [8]. **Parameters Settings:** All experiments are implemented by Pytorch 2.0.0 on NVIDIA GeForce RTX 3090 GPU. We split all datasets with a ratio of 6:2:2 into training sets, validation sets, and test sets. One hour of historical data is used to predict traffic conditions in the next hour. We use Adam as our optimizer and set the learning rate to 0.001. The batch size is 16 and the training epoch is 200. The temporal convolution block has hidden dimensions of 64,32,64. ### _Performance Comparison(RQ1)_ Table I displays the performance comparison results of our STHODE method with various baseline approaches for traffic forecasting. Overall, our proposed STHODE achieves the most competitive performance on the three metrics and significantly surpasses all baselines on all the datasets. The improvement in performance can be attributed to some key factors: 1) The spatial module enables STHODE to effectively model the road network topology, surpassing graph-based methods; 2) The temporal module enables STHODE to fully extract high-order temporal dependencies, further improving prediction accuracy. Leveraging the hypergraph structure enhances the representation of complex relationships between traffic sensors and road segments, resulting in superior prediction accuracy. ### _Model Ablation and Effectiveness Analyses(RQ2)_ To analyze STHODE's components, we conducted ablation experiments on PeMS04: _w/o spatial_: Removes the spatial hypergraph module. _w/o temporal_: Removes the temporal hypergraph module. _w/o ode_: Replaces the ODE solver with a hypergraph convolution layer. _w/o adaptive_: Removes the adaptive hypergraph matrix from spatial hypergraph construction. Results in Figure 2 indicate: STHODE consistently outperforms all variants, emphasizing the importance of its components. Removing ODE layers (_w/o ode_) reduces performance, which highlights their role in capturing data dynamics. Omitting either the spatial (_w/o spatial_) or temporal module (_w/o temporal_) results in performance decline, which is the significance of road network influences. _w/o adaptive_ highlights the importance of the adaptive hyperedge matrix in capturing data relationships and correlations. ### _Hyperparameter Studies(RQ3)_ In Figure 3, we present results from experiments on the PeMS04 dataset where we varied hyperparameters within the spatial and temporal hypergraph modules. Our observations are as follows: Sensitivity of Spatial Module: Increasing \(K\) from 1 to 3 generally improves performance. Notably, when \(K=1\) Fig. 2: Ablation experiments of STHODE on PeMS04 dataset. the MixHop scheme reduces to the original hypergraph convolution scheme, confirming the effectiveness of MixHop. However, further increasing depth may lead to diminishing returns or overfitting. Sensitivity of Temporal Module: Increasing \(r\) from 2 to 7 generally improves performance, indicating effective capture of high-order temporal dependencies. However, further increasing \(r\) may introduce noise or irrelevant information, leading to decreased performance. ### _Case Study_ A case study conducted on node 27 and node 35 from the PeMS04 dataset offers a detailed analysis of the performance of STHODE. In Figure 4(a), during the heavy traffic flow from 10:00 to 19:00, STHODE consistently outperforms STODE. In Figure 4(b), around 19:00, an abrupt change occurs and STHODE quickly adapts while maintaining high prediction accuracy. The ability to model the road network topology helps STHODE capture the correlation among different road segments, leading to improved prediction accuracy. ## VI Conclusion This paper introduces Spatio-Temporal Hypergraph ODE (STHODE). It models the road network topology and traffic dynamics to capture high-order spatio-temporal dependencies for short-term traffic predictions. STHODE utilizes two ODE-based modules that encode a spatial hypergraph and a temporal hypergraph working in parallel to capture high-order spatio-temporal dependencies respectively. Extensive experiments prove the effectiveness of STHODE over various existing methods.
2307.08859
Curriculum Learning for Graph Neural Networks: A Multiview Competence-based Approach
A curriculum is a planned sequence of learning materials and an effective one can make learning efficient and effective for both humans and machines. Recent studies developed effective data-driven curriculum learning approaches for training graph neural networks in language applications. However, existing curriculum learning approaches often employ a single criterion of difficulty in their training paradigms. In this paper, we propose a new perspective on curriculum learning by introducing a novel approach that builds on graph complexity formalisms (as difficulty criteria) and model competence during training. The model consists of a scheduling scheme which derives effective curricula by accounting for different views of sample difficulty and model competence during training. The proposed solution advances existing research in curriculum learning for graph neural networks with the ability to incorporate a fine-grained spectrum of graph difficulty criteria in their training paradigms. Experimental results on real-world link prediction and node classification tasks illustrate the effectiveness of the proposed approach.
Nidhi Vakil, Hadi Amiri
2023-07-17T21:33:35Z
http://arxiv.org/abs/2307.08859v1
# Curriculum Learning for Graph Neural Networks: A Multiview Competence-based Approach ###### Abstract A curriculum is a planned sequence of learning materials and an effective one can make learning efficient and effective for both humans and machines. Recent studies developed effective data-driven curriculum learning approaches for training graph neural networks in language applications. However, existing curriculum learning approaches often employ a single criterion of difficulty in their training paradigms. In this paper, we propose a new perspective on curriculum learning by introducing a novel approach that builds on graph complexity formalisms (as difficulty criteria) and model competence during training. The model consists of a scheduling scheme which derives effective curricula by accounting for different views of sample difficulty and model competence during training. The proposed solution advances existing research in curriculum learning for graph neural networks with the ability to incorporate a fine-grained spectrum of graph difficulty criteria in their training paradigms. Experimental results on real-world link prediction and node classification tasks illustrate the effectiveness of the proposed approach.1 Footnote 1: Code, data splits and guidelines are available at [https://clu.cs.uml.edu/tools.html](https://clu.cs.uml.edu/tools.html). ## 1 Introduction Graph Neural Networks (GNNs) are generally trained using stochastic gradient descent (SGD), where the standard approach is to iteratively use the _entire_ training data to optimize model's objective until convergence. Curriculum learning techniques improve this training process by scheduling examples for training, e.g., by gradually learning from easier examples before training with harder ones. Such curricula can be predefined by humans Bengio and LeCun (2007); Bengio et al. (2009) or dynamically derived from data during training Jiang et al. (2018); Castells et al. (2020). Curriculum learning for graph neural networks is an emerging area of research. Recently, Chu et al. (2021) employed a traditional curriculum learning approach introduced in Bengio et al. (2009) to improve negative sampling for graph classification. Wang et al. (2021) proposed to estimate the difficulty of graph entities-nodes, edges or subgraphs-based on the intra- and inter-class distributions of their embeddings in supervised settings, and developed a smooth-step function to gradually introduce harder examples to GNNs during training. Vakil and Amiri (2022) developed a loss-based curriculum learning approach that dynamically adjusts the difficulty boundaries of training samples based on their sample-level loss trajectories obtained from recent training dynamics of GNN models. To the best of our knowledge, existing curriculum learning approaches often employ a _single_ criterion of difficulty in their curriculum learning framework, e.g., prediction loss Wu et al. (2021), consistency in prediction loss Xu et al. (2020), moving average of loss Zhou et al. (2020) or transformations of loss Vakil and Amiri (2022). We address this gap by developing a new curriculum learning approach for GNNs titled **M**ultiview **C**ompetence-based **C**urriculum **L**earning (MCCL) that builds on the complexity formalisms of graph data. By leveraging rich graph structures, graph complexity formalisms and model _competence_ (learning progress), we will design robust curricula for training GNNs. Table 1 shows three subgraphs ranked differently according to different graph complexity indices. If complexity is measured by _node degree_, then G1 and G2 are less complex than G3 because target nodes in these subgraphs have an overall smaller node degrees. However, if complexity is measured by _closeness centrality_2, then G2 is more complex than G3 because the target nodes are less central in G2 than those in G3. It is evident that complexity indices (views) can vary significantly in their difficulty estimates of graph data. Footnote 2: Closeness centrality Sabidussi (1966) is smaller for central nodes–those that are closer to other nodes in the graph. The objective of this work is improve the training process of GNNs by strategically and dynamically (during training) prioritizing key complexity indices, aiming to guide the model toward better minima within its parameter space. Graph complexity is a well-established area of research and our review of relevant literature suggests that there exist various techniques that employ structural properties of nodes, edges and subgraphs to quantify complexity of graph data (Kim and Wilhelm, 2008; Vishwanathan et al., 2010; Newman, 2018; Kriege et al., 2020). We build on these indices to design our curriculum learning framework which treats each complexity index as a view of difficulty. Our approach consists of a novel data scheduling scheme which derives effective curricula based on given views of sample difficulty and model competence during training. Specifically, given a downstream GNN model, our data scheduler gradually selects training examples from a graph complexity view based on competency of the GNN model during training. The model updates its competency and the scheduler determines the next best view for training the model. As model competency gradually increases, the scheduler allows using more signals from different views. The contributions of this paper are as follows: * A new curriculum learning approach that effectively leverages complexity formalisms of graph data, taking into account multiview difficulty of training data samples and model's learning progress, and * Key insights into important complexity indices for effective training of graph neural networks for NLP applications. We conduct extensive experiments on real world datasets for link prediction and node classification tasks in text graph datasets. Our approach results in 3.3 and 1.8 absolute points improvements in F1-score over the state-of-the-art model on link prediction datasets and 6.7 and 4.9 absolute points improvement on the node classification dataset. The results show that the contribution of complexity indices in training depends on factors such as training stage and model behavior. When the scheduling criterion relies solely on complexity indices, the scheduler tends to initially focus on indices that operate locally around nodes, and later shifts to those that operate globally at graph level. Extending schedulers based on model dynamics (e.g., loss) results in both local and global indices being used throughout the training. These findings provide insights into the type of complexity information that GNNs learn at different stages of their training. \begin{table} \begin{tabular}{l l l l l} \hline \hline ## 2 Competence-based Multiview Curricula We present a competence-based multiview curriculum learning framework for training GNNs. At every training iteration, the framework selects a sub-set of training examples based on the best complexity index (view) and model's competence at that iteration. Algorithm 1 describes the overall approach. We first introduce our complexity indices and then present the model. ### Graph Complexity Formalisms Various graph complexity indices were introduced in graph theory (Kashima et al., 2003; Borgwardt and Kriegel, 2005; Vishwanathan et al., 2010; Kriege et al., 2020; Newman, 2018). We consider 26 of such indices which represent criteria of difficulty in our curriculum learning framework.3 In what follows, we describe a few representative complexity indices and refer the reader to Appendix A for a full description of all indices. Footnote 3: Our list of complexity indices may not be exhaustive. However, our framework and implementation allows adding any number of additional indices. Since GNNs train through neural message passing at subgraph level (Gilmer et al., 2017; Hamilton et al., 2017), we compute complexity indices with respect to the \(k\)-hop neighbors (subgraph) of target nodes. For tasks involving two nodes (e.g., relation extraction), we sum the scores computed for the node pairs. We use Networkx (Hagberg et al., 2008) to compute the indices: * **Degree:** The number of immediate neighbors of a node in a graph. * **Average neighbor degree:** Average degree of the neighbors of a node: \[\frac{1}{|\mathcal{N}_{i}|}\sum_{j\in\mathcal{N}_{i}}k_{j},\] where \(\mathcal{N}_{i}\) is the set of neighbors of node \(i\) and \(k_{j}\) is the degree of node \(j\). * **Katz centrality:** The centrality of a node computed based on the centrality of its neighbors. Katz centrality computes the relative influence of a node within a network by measuring the number of immediate neighbors and number of walks between node pairs. It is computed as follows: \[x_{i}=\alpha\sum_{j}\mathbf{A}_{ij}x_{j}+\beta,\] where \(x_{i}\) is the Katz centrality of node \(i\), \(\mathbf{A}\) is the adjacency matrix of Graph \(G\) with eigenvalues \(\lambda\). The parameter \(\beta\) controls the initial centrality and \(\alpha<\) 1 / \(\lambda_{max}\). * **Resource allocation index:** For nodes \(i\) and \(j\) in a subgraph, the resource allocation index is defined as follows: \[\sum_{k\in(\mathcal{N}_{i}\bigcap\mathcal{N}_{j})}\frac{1}{|\mathcal{N}_{k}|},\] which quantifies the closeness of target nodes based on their shared neighbors. * **Subgraph density:** The density of an undirected subgraph is computed as follows: \[\frac{e}{v(v-1)},\] where \(e\) is the number of edges and \(v\) is the number of nodes in the subgraph. * **Local bridge:** A local bridge is an edge that is not part of a triangle in the subgraph. We take the number of local bridges in a subgraph as a complexity index. * **Subgraph connectivity:** Is measured by the _minimum_ number of nodes that must be removed to disconnect the subgraph. * **Eigenvector centrality:** Eigenvector centrality computes the centrality for a node based on the centrality of its neighbors. The eigenvector centrality for node i is \(Ax\) = \(\lambda x\). where \(A\) is the adjacency matrix of the graph \(G\) with eigenvalue \(\lambda\). We note that our approach does not depend on any specific index. However, we recommend considering indices that are computationally inexpensive for applicability to large graphs. The complexity scores of each index are normalized into [0, 1] range using L2 norm. ### Model Competency We define model competence at each training iteration \(t\) as the fraction of training data that can be used by the model at time \(t\); we refer to this fraction by \(c(t)\). Our curriculum learning framework employs difficulty indices to select \(c(t)\) fraction of examples to train its downstream model (a GNN). We employ the following function (Platanios et al., 2019) to quantify competence: \[c(t)=\min\left(1,\sqrt[p]{t\left(\frac{1-c_{0}^{p}}{T}\right)+c_{0}^{p}}\right), \tag{1}\] where \(t\) is the training iteration, \(p\) controls the sharpness of the curriculum so that more time is spent on the examples added later in the training, \(T\) is the maximum curriculum length (number of iterations), and \(c_{0}\) is the initial value of the competence. \(c(t)\) gradually increases to achieve the maximum value of 1, which covers the entire training dataset. We set \(p=2\) and \(c_{0}=0.01\) as suggested in (Platanios et al., 2019). ### Prioritizing Important Difficulty Indices Difficulty indices vary significantly in their difficulty estimates, owing to the complicated topology and indistinct patterns in graph data. Our framework strategically prioritizes key difficulty indices while training a GNN model. Specifically, the framework employs two mechanisms (see line 7 in Algorithm 1) to determine which index (i.e., top \(c(t)\) portion of training data ranked by the difficulty scores obtained from the index) should be used for training the downstream GNN model at iteration \(t\): (i) model-based and (ii) index-based approaches: Model-based:This approach performs a forward pass on the selected portion of training data and calculates the average loss of the GNN on these examples. The index with the maximum (or minimum, depending on the curriculum) average loss will be selected at iteration \(t\) and it's top \(c(t)\) examples will be used for training the downstream GNN. Minimum average loss prioritizes easier examples over harder ones for training. On the other hand, maximum average loss prioritizes harder examples (as in an anti-curriculum setting). Index-based:This approach uses the actual difficulty scores obtained from indices. The index with minimum (or maximum) average difficulty score across its top \(c(t)\) portion of training samples will be selected for training and calculating the error (see lines 9-14 in Algorithm 1). We note that the index-based approach is computationally inexpensive compared to the model-based approach, and results in comparable performance, see results in experiments (Tables 4) ``` input : D: Training data of size \(n\) L: Difficulty indices M: GNN Model O: easy-to-hard vs. hard-to-easy transition output : Trained model M* 1 Compute complexity scores for each index \(i\) in L and store the results in L\({}_{i}\)\(\mathrm{L}_{i}\gets sort(\mathrm{L}_{i})\)# in ascending or descending order. for\(t\gets 0\) to Tdo\(c(t)\leftarrow\) competence from Eq (1)foreach index in Ldo\(l_{i}\leftarrow\) top (\(c(t)\times n\)) examples from L\({}_{i}\)\(e_{i}\leftarrow\) average loss or complexity of \(l_{i}\) 2 end forifO = easy-to-hardthen 3\(j=\arg\min_{i}e_{i}\) 4else 5\(j=\arg\max_{i}e_{i}\) 6 end for Train M with \(l_{j}\) samples 7 8 end for ``` **Algorithm 1**Multiview Competence-based Curriculum Learning (MCCL). ### Base Graph Neural Network Model Our approach is model agnostic and can be applied to any GNN. We use the graph-text neural network (GTNN) model4 from (Vakil and Amiri, 2022) as the base model because it is designed for text-graph data. The model integrates textual information with graph structure and directly uses text embeddings at prediction layer to avoid information loss in the iterative process of training GNNs. We use this model as a base model to compare our and baseline curriculum learning approaches on graph data. Footnote 4: [https://github.com/CLU-UML/gtnn](https://github.com/CLU-UML/gtnn) ## 3 Experimental Results ### Datasets Gene Phenotype Relation (PGR) (Sousa et al., 2019): PGR is created from PubMed articles and contains sentences describing causal relations between genes and phenotypes (symptoms); see Table 1 for examples of this dataset. Gene, Disease, Phenotype Relation (GDPR) (Vakil and Amiri, 2022): GDPR contains different types of relations among genes, diseases and phenotypes, and long texts describing them. Cora(McCallum et al., 2000): Cora is a relatively small citation network, in which nodes are scientific papers and edges are citations among them. Each paper is categorized into one of the seven subject categories and is provided with a textual feature word vector obtained from the content of the paper. Ogbn-arxiv(Hu et al., 2020): This Open Graph Benchmark dataset is a citation network between papers in the Computer Science domain. Each node in the graph is a paper and an edge represents a citation from one paper to another. Also, each paper contains 128 dimension embedding vector obtained by taking the average of the words present in the title and the abstract. Table 2 shows the statistics of the above datasets. We use PGR and GDPR for link prediction and Cora and Ogbn-Arxiv for node classification. ### Baselines **CurGraph** (Wang et al., 2021) is a curriculum learning framework for graphs that computes difficulty scores based on the intra- and inter-class distributions of embeddings and develops a smooth-step function to gradually include harder samples in training. We report the results of our implementation of this approach. **SuperLoss** (SL) (Castells et al., 2020) is a generic curriculum learning approach that dynamically learns a curriculum from model behavior. It uses a fixed difficulty threshold at batch level, determined by the exponential moving average of all sample losses, and assigns higher weights to easier samples than harder ones. **Trend-SL** (Vakil and Amiri, 2022) is a curriculum learning approach which extends (Castells et al., 2020) by incorporating sample-level loss trends to better discriminate easier from harder samples and schedule them for training. ### Settings We consider 1-hop neighbors for PGR and GDPR and 2-hop neighbors for Cora and Ogbn-Arxiv to create subgraphs for computing complexity indices, see Section 2.1, and training the GTNN model, see Section 2.4. We train all models for a maximum number of \(100\) iterations for PGR and GDPR, and \(500\) iterations for Cora and Ogbn-Arxiv with model checkpoint determined by validation data for all models. We conduct all experiments using Ubuntu 18.04 on a single 40GB A100 Nvidia GPU. We consider 26 complexity indices listed in Appendix A. Since some of the indices are highly co-related, we use k-means to group them based on the Pearson co-relations between their ranking of training samples. We categorize indices into 10 clusters through grid search, which effectively prevents any redundancy in the index space. We randomly select an index from each cluster to be used by our curriculum learning framework. Indices that are used by the framework are labeled by asterisks in Appendix A. We report F1 score (on positive class) for PGR and GDPR datasets, and Accuracy score for Cora and Ogbn-Arxiv datasets. In addition, we use t-test for significance testing and asterisk mark (*) to indicate significant difference at \(\rho=0.01\). ### Main Results Table 3 shows the performance of the proposed MCCL method against other curriculum learning approaches. The results shows that applying curricula to the base model (GTNN) further improves its performance by 3.3 and 1.8 absolute points in F1 on GDPR and PGR datasets respectively, indicating the importance of curriculum learning for training GNNs. The corresponding improvement on Cora and Ogbn-Arxiv datasets are 6.7 and 4.9 absolute points in accuracy. In addition, MCCL outperforms other curriculum learning approaches. Furthermore, as MCCL increasingly introduces more training instances at each iteration, it shows an overall faster training time compared to the other curriculum learning models, which iterate through all training examples at every iteration. See Section 4.4 for detail analysis on time complexity of different models. \begin{table} \begin{tabular}{l c c c c} \hline \hline & **GDPR** & **PGR** & **Cora** & **Ogbn-Arxiv** \\ \hline **Nodes** & 18.3K & 20.4K & 2.7K & 169K \\ **Edges** & 365K & 605K & 5.4K & 1.1M \\ \hline **Train** & 30.1K & 2.6K & 2.1K & 90K \\ **Test** & 3.7K & 155 & 271 & 49K \\ **Val** & 3.7K & – & 271 & 30K \\ \hline \hline \end{tabular} \end{table} Table 2: Dataset statistics. \begin{table} \begin{tabular}{l c c c c} \hline \hline & \multicolumn{2}{c}{**Link Prediction**} & \multicolumn{2}{c}{**Node Classification**} \\ \hline \hline & **GDPR** & **PGR** & **Cora** & **Ogbn-Arxiv** \\ **Model** & **F1** & **F1** & **Acc** & **Acc** \\ \hline **GTNN** & 82.4 & 93.4 & 91.5 & 71.6 \\ \hline **CurGraph** & 81.0 & 80.3 & 88.6 & 68.7 \\ **SL** & 84.1 & 94.5 & 90.4 & 71.8 \\ **Trend-SL** & 84.6 & 94.5 & 90.4 & 71.5 \\ **MCCL** & **85.7*** & **95.2*** & **98.2*** & **76.5*** \\ \hline \hline \end{tabular} \end{table} Table 3: Performance of curriculum models on **GDPR** and **PGR** datasets for link prediction, and **Cora** and **Ogbn-Arxiv** for node classification. The base model for all curriculum learning approaches is GTNN, which has a high score of F1 and Accuracy on the datasets using standard training. MCCL performs best compared to the other curricula methods. Asterisk marks (*) indicate significantly better performance compared to all other competing models. ## 4 Multiview Curricula Introspection We perform several ablation studies on the MCCL model, investigating genuine complexity indices compared to random ordering, multiview curricula versus anti-curricula, the impact of complexity indices in training, and the model's time complexity. ### Model Prioritizes Genuine Complexity Indices over Random Ordering In curriculum learning, effective training depends on the scheduler, which determines the set of examples and their order for training at each iteration. Hence, the performance of the model largely depends on the scheduling criteria used for training. To determine if our model can indeed prioritize better indices, we added a _fake_ index named "Random" index to the list of our complexity indices. Training examples were randomly ordered in the Random index. We re-ran our model and checked whether it selects the Random index for training at any iteration. On Cora and Ogbn-Arxiv datasets, model selects the Random index at 17.6% and 12.8% of its training iterations. On PGR, the model never selects the Random index, and on GDPR, model selects the Random index at 8% of its training iterations. Specifically, toward the end of training at iterations [39, 46, 58, 71, 76, 83, 91, 93] with the best F1-score of 85.5% obtained at iteration 76. The fact that the model do not often select the Random index at many iterations is effectively inline with the core principle of curriculum learning-learning materials should be gradually learned in a properly-planned order. This sanity check indicates that the model prioritizes genuine complexity indices over random ordering. ### Multiview Curricula vs. Anti-Curricula We study the effect of different criteria in MCCL framework through ablation analysis on (a): the order by which training examples are sorted with respect to their complexity scores for each index (descending versus ascending, see line 2 in Algorithm 1), (b): the mechanism by which our framework prioritizes indices (model-based versus index-based, see line 7 in Algorithm 1 and Section 2.3), and (c): the type of learning transition in our framework (easy-to-hard versus hard-to-easy transition, see lines 9-13 in Algorithm 1). Table 4 shows the result of this ablation analysis averaged over the PGR and GDPR datasets for link prediction, and Cora and Ogbn-Arxiv datasets for node classification respectively. The corresponding results for each dataset is reported in Appendix B. Overall, the ascending order results in the best average F1 score for link prediction while descending order performs better for node classification. In addition, in model-based training, hard-to-easy (max) transition order is more effective than easy-to-hard (min) transition order across both tasks. This is perhaps because harder examples are superior at helping the model find better local minima at the early stages of training. We also observe that easy-to-hard (min) transition for index-based training results in higher average F1-score than hard-to-easy (max) transition of the model-based training. This is because, in case of index-based ordering, the difficulty scores (which are obtained from indices) may provide a more accurate estimation of easiness to the model than hardness, i.e. easy examples are likely easy for the model in both ordering but this may not be true for hard examples. \begin{table} \begin{tabular}{l l l l} \hline \hline \multicolumn{4}{c}{**Link Prediction**} \\ \hline \hline **Model** & \begin{tabular}{c} **Index** \\ **Order** \\ \end{tabular} & \begin{tabular}{c} **Transition** \\ **Order** \\ \end{tabular} & **Avg F1** \\ \hline **GTNN** & – & – & 87.9 \\ \hline \multirow{3}{*}{**MCCL: Model-based**} & desc & max & 89.4 \\ & desc & min & 89.3 \\ & asc & max & **89.9** \\ & asc & min & 88.7 \\ \hline \multirow{3}{*}{**MCCL: Index-based**} & desc & max & 90.1 \\ & desc & min & 89.2 \\ \cline{1-1} & asc & max & 89.3 \\ \cline{1-1} & asc & min & **90.4** \\ \hline \hline \end{tabular} \end{table} Table 4: Ablation analysis on the order by which training examples are sorted for complexity indices (ascending versus descending in the Index Order column, see line 2 in Algorithm 1), the training mechanism (model- versus index-based in the Model column, see line 7 in Algorithm 1) and the type of learning transition (easy-to-hard (Min error) versus hard-to-easy (Max error) in the Transition Order column, see lines 9–13 in Algorithm 1). ### Index Contributions to Training To study the contributions of different complexity indices in the training process, we divide training iterations into three phases and create the histograms that show the number of times that each index is chosen at different stages of training: (i) Initial, (ii) Middle, and (iii) End phases of the training. Figures 1 shows the results for different indices chosen by the best-performing MCCL model5 for both index-based (where the criterion for selecting samples is merely based on their difficulty scores obtained from indices) and model-based (where the criterion for selecting samples is based on instantaneous loss) approaches across our four datasets. Our key observation was that MCCL mainly focused on indices that operate locally around nodes (such as density- or degree-based indices) at early stages of training and then focused on indices that operate globally at graph level (such as centrality-based indices) at later stages of training for both index-based and model-based training mechanisms. Additionally, we observed greater diversity in the sets of prioritized indices in case of the model-based training mechanism, which indicates MCCL encourages learning from diverse views of difficulty during training. This is mainly because the model-based training mechanism in MCCL allows the GNN to directly contribute in scheduling indices through its loss dynamics during training. Footnote 5: According to the results in Tables 6 and 7 in Appendix B. In addition, we note that on the Cora dataset the model merely focused on degree-based metrics throughout its training in case of index-based training and, used a smaller set of fundamentally-different indices in case of model-based training. On the Ogbn-Arxiv dataset, the model focuses only on the eigenvector centrality index throughout its training in case of index-based training and focuses on connectivity and centrality indices in the model-based training. Further analysis on this model behavior is the subject of our future work. Overall, density, degree indices including degree and degree assortativity coefficient, and centrality indices including closeness centrality, group degree centrality and eigenvector centrality indices are often prioritized by the model across different mechanisms and datasets. ### MCCL Has the Lowest Time Complexity Let \(n\) be the number of training examples and \(e\) be the maximum number of iterations for training a neural network. The total of number of forward and backward passes required to train GTNN, SL, Trend-SL is \(2\times n\times e\). In contrast, MCCL trains from only a fraction of training examples at each iteration and do not need to "see" all the training examples at each iteration. If model-based mechanism is used to prioritize important indices for training, the total number of forward and backward passes of MCCL is \(3\times\sum_{i}(n\times\frac{i}{e})\), which amounts to \(1.5\times n\times(e-1)\); note that model-based approach requires \(\sum_{i}(n\times\frac{i}{e})=\frac{n\times(e-1)}{2}\) additional forward passes to select the best index. In case of the index-based training mechanism, no additional forward pass is required, resulting in a total of \(2\times\sum_{i}(n\times\frac{i}{e})\) passes, which amounts to \(n\times(e-1)\) passes. In either case, MCCL has lower time complexity than other baselines. The turnaround time of our model ranges from 10 minutes to 2.5 hours, depending on the size of the input dataset. ## 5 Related Work Curriculum learning (Bengio et al., 2009) aims to improve the generalizability of a model by gradually training it with easy examples followed by hard ones. Castells et al. (2020) introduced a generic loss function called SuperLoss (SL) which can be added on top of any target-task loss function to dynamically weight the training samples according to their difficulty for the model using a batch-wise threshold. Zhou et al. (2020) proposed dynamic instance hardness to determine the difficulty of an instance with running average of the hardness metric over training history. Curriculum learning has been investigated in NLP (Elman, 1993; Sachan and Xing, 2016; Settles and Meeder, 2016; Amiri et al., 2017; Platanios et al., 2019; Amiri, 2019; Zhang et al., 2019; Lalor and Yu, 2020; Xu et al., 2020; Chu et al., 2021; Liu et al., 2021; Kreutzer et al., 2021; Agrawal and Carpuat, 2022; Maharana and Bansal, 2022). Specifically, Settles and Meeder (2016); Amiri et al. (2017) proposed spaced repetition-based curricula based on psycholinguistic theory where the training data is scheduled by increasing intervals of time between consecutive reviews of previously learned data samples. Zhang et al. (2019) investigated curriculum learning for domain adaptation in neural machine translation, where samples were grouped and ranked based on their similarity score such that more similar samples are seen earlier and more frequently during training. Platanios Figure 1: Histogram of the different indices chosen by the best-performing MCCL model for both index-based (where samples are selected for training merely based on their difficulty scores obtained from indices) and model-based (where samples are selected based on instantaneous loss of the model) approaches across three datasets at the beginning, middle and end of training; see best models in Table 6, Appendix B. Dominance of a metric depends on the internal structure of the graph, underlying task, stage of training, and model behavior during training. (a): on GDPR, model mainly focuses on density- and degree-based indices (which operate locally around nodes) at the beginning and centrality-based indices (which operate globally at graph level) at later stages of index-based training (left three plots). In case of model-based training (right three plots), both degree- and centrality-based indices were selected throughout the training. (b): On PGR, we observed the same pattern except that locality indices such as number of local bridges were prioritized in case of model-based training. (c): On Cora, the model merely focuses on the degree-based metrics throughout its index-based training, and focuses on a mix of different indices at early stages of its model-based training and closeness centrality at the end of training. (d): On Ogbn-Arxiv, the model only focuses on eigenvector centrality metric throughout its index-based training and focuses on the local bridge and degree assortativity indices in the initial phase of the model-based training. In the middle and final phases, model-based training mainly focuses on degree based indices. et al. (2019) proposed an approach to use competency function using rarity of words or length of a sentence for neural machine translation and inspired Liu et al. (2021) to define a curriculum based on multi-modal (text and image) data to choose which modality should be used for training. The model uses sample perplexity at batch level to select the modality for training. Linguistic features such as word rarity or length of sentence in Platanios et al. (2019) and sample perplexity in Liu et al. (2021) were used as measures of difficulty. Xu et al. (2020) designed a curriculum learning approach for NLP tasks using cross-view of training data to identify easy and hard examples and rearrange the examples during training. Other works of curriculum learning in NLP focused on machine translation and language understanding. Agrawal and Carpuat (2022) developed a framework to train non-autoregressive sequence-to-sequence model to edit text where a curriculum is designed to first perform easy-to-learn edits followed by increasing difficulty of training samples. Maharana and Bansal (2022) designed several curriculum learning approaches using teacher-student model where the teacher model calculates the difficulty of each training example using question-answering probability, variability, and out-of-distribution measures. Curriculum learning for graph data is an emerging area of research. Chu et al. (2021) explored curriculum learning approach in the self-supervision settings where the difficulty measure evaluates the difficulty of negative samples which is calculated based in the embeddings's similarity between positive and negative examples. Wang et al. (2021) proposed a curriculum based subgraph classification approach, CurGraph, which first obtains graph-level embeddings via unsupervised GNN method and then uses neural density estimator to model embedding distributions. The difficulty scores of graphs are calculated by a predefined difficulty measure based on the inter- and intra-class distribution of sub-graph embeddings. In Vakil and Amiri (2022), we extended the SuperLoss approach developed in Castells et al. (2020) by introducing a curriculum learning framework that dynamically adjusts the difficulty of samples during training with respect to the loss trajectory. We demonstrated the effectiveness of incorporating this strategy in graph curriculum learning settings. Previous work in graph curriculum learning has employed a single criterion of difficulty in their curriculum learning framework. Our work uses multiple criteria for curriculum learning on graphs. We encourage readers to see Li et al. (2023) for a survey on graphs curriculum learning approaches. Finally, in terms of datasets, Sousa et al. (2019) developed the PGR dataset, which we used in our experiments. They developed a transformer model to identify the relation between biomedical entities, genes and phenotypes, from scientific PubMed articles. For relation classification authors considered a pair of entities and the context from the corresponding sentence in which both entities occur. ## 6 Conclusion and Future work We present a novel curriculum learning approach for training graph neural networks. Our approach combines well-established graph complexity indices (views) obtained from graph theory and demonstrates the effectiveness of learning from diverse difficulty views for the tasks of link prediction and node classification. Our approach improves over the state-of-the-art techniques for curriculum learning on graphs across several datasets. Ablation studies show that the model prioritizes genuine complexity indices over to random ordering, and effectively uses and learn multiview complexity indices in both curricula and anti-curricula settings, and has lower time complexity that competing models. In future, we will extend our approach to other graph processing tasks, focusing on NLP applications such as clustering and community detection, and investigate the effect of graph complexity indices in such tasks. ### Limitation Calculating complexity indices for large-scale graphs can be computationally expensive and time consuming. Some of the complexity indices show longer turnaround time when computed for denser areas in the graphs. In addition, as we mentioned in the paper, although we made sure our framework and implementation allows adding any number of additional indices in a modular way, there might be other effective complexity indices that are not included in this investigation. Furthermore, it should be noted that the model has been exclusively tested on graphs where nodes contain textual content, which may limit its application to more general graph types. Finally, the model has not been applied to other graph-based tasks such as clustering and graph-level classification.
2308.06767
A Survey on Deep Neural Network Pruning-Taxonomy, Comparison, Analysis, and Recommendations
Modern deep neural networks, particularly recent large language models, come with massive model sizes that require significant computational and storage resources. To enable the deployment of modern models on resource-constrained environments and accelerate inference time, researchers have increasingly explored pruning techniques as a popular research direction in neural network compression. However, there is a dearth of up-to-date comprehensive review papers on pruning. To address this issue, in this survey, we provide a comprehensive review of existing research works on deep neural network pruning in a taxonomy of 1) universal/specific speedup, 2) when to prune, 3) how to prune, and 4) fusion of pruning and other compression techniques. We then provide a thorough comparative analysis of eight pairs of contrast settings for pruning and explore emerging topics, including pruning for large language models, large multimodal models, post-training pruning, and different supervision levels for pruning to shed light on the commonalities and differences of existing methods and lay the foundation for further method development. To facilitate future research, we build a curated collection of datasets, networks, and evaluations on different applications. Finally, we provide valuable recommendations on selecting pruning methods and prospect several promising research directions. We build a repository at https://github.com/hrcheng1066/awesome-pruning.
Hongrong Cheng, Miao Zhang, Javen Qinfeng Shi
2023-08-13T13:34:04Z
http://arxiv.org/abs/2308.06767v2
# A Survey on Deep Neural Network Pruning: Taxonomy, Comparison, Analysis, and Recommendations ###### Abstract Modern deep neural networks, particularly recent large language models, come with massive model sizes that require significant computational and storage resources. To enable the deployment of modern models on resource-constrained environments and accelerate inference time, researchers have increasingly explored pruning techniques as a popular research direction in neural network compression. More than a thousand pruning papers have been published each year from 2020 to 2022. However, there is a dearth of up-to-date comprehensive review papers on pruning. To address this issue, in this survey, we provide a comprehensive review of existing research works on deep neural network pruning in a taxonomy of 1) universal/specific speedup, 2) when to prune, 3) how to prune, and 4) fusion of pruning and other compression techniques. We then provide a thorough comparative analysis of seven pairs of contrast settings for pruning (e.g., unstructured/structured, one-shot/iterative, data-free/data-driven, initialized/pretrained weights, etc.) and explore several emerging topics, including post-training pruning, different levels of supervision for pruning to shed light on the commonalities and differences of existing methods and lay the foundation for further method development. Finally, we provide some valuable recommendations on selecting pruning methods and prospect several promising research directions for neural network pruning. To facilitate future research on deep neural network pruning, we summarize broad pruning applications (e.g., adversarial robustness, natural language understanding, etc.) and build a curated collection of datasets, networks, and evaluations on different applications. We maintain a repository on [https://github.com/hrcheng1066/awesome-pruning](https://github.com/hrcheng1066/awesome-pruning) that serves as a comprehensive resource for neural network pruning papers and corresponding open-source codes. We will keep updating this repository to include the latest advancements in the field. deep neural network pruning, model compression, model acceleration, edge devices. ## 1 Introduction Over the past several years, Deep Neural Networks (DNNs) have achieved conspicuous progress in various domains and applications, such as Computer Vision (**CV**) [1, 2, 3], Natural Language Processing (**NLP**) [4] and Audio Signal Processing (**ASP**) [5], so on. Although DNNs achieve remarkable success in various areas, their performance heavily relies on model parameters and computational cost. For example, the widely used ResNet-50 [6] takes over 95MB memory for storage, contains over 23 million trainable parameters, and requires 4 GFLOPs (Giga Floating Point Operations) of computations [7]. The size of VGG-16 [2] trained on ImageNet [1] is more than 500 MB [8]. The Transformer network GPT-3 model consists of up to 175 billion parameters [9], and GPT-4 model has even more. The current trend of enlarging neural network size is anticipated to persist. However, the more parameters of DNNs, the more time and memory space they typically require for processing the inputs [10]. The high training and inference costs associated with these models present a significant challenge to their deployment on devices constrained by limited computational resources (such as CPU, GPU, and memory), energy, and bandwidth [11, 12, 13]. For example, real-life applications such as autonomous driving, field rescue, and bushfire prevention necessitate high accuracy and efficient resource usage, including fast real-time response and compact memory footprint. Deep neural networks' computational complexity and memory footprint can make them impractical for deployment on edge devices [14]. With the popularity of large language models in recent years, there is growing interest in compressing neural networks for computers with flexible hardware requirements [15]. In addition, deep neural networks that contain redundant features can undermine their robustness, elevating the risk of adversarial attacks [16]. For instance, high-dimensional feature spaces created by these networks can provide greater entry points for adversarial attacks, undermining the network's ability to generalize beyond its original training data. To relieve this issue, researchers have proposed various neural network compression techniques to design lightweight models, including neural network pruning ([17]), low-rank factorizations of the weight matrices ([18, 19]), quantization ([11, 20]), knowledge distillation ([21]), neural architecture search ([22, 23]) and other compression techniques ([24, 25]). Among them, there are continuing interests in neural network pruning, which has been proven as a desirable and effective way to save memory space and computation time at inference while maintaining a comparable or even better performance compared to the original DNNs. As shown in Fig. 11, the number of papers on pruning has been markedly increasing from 2015 to 2022. It presents more than half of the papers on neural network compression. Footnote 1: The data is from [https://www.webotknowledge.com](https://www.webotknowledge.com). The research on pruning can be traced back to literature as early as 1988 [26]. However, it is only until the emergence of [11] that the research community realizes the potential of pruning in removing significant redundancy in deep neural networks, and pruning begins to gain widespread attention. There are several pieces of literature that review prior work on deep neural network pruning, as shown in Table I. Although these works overview several aspects of pruning and provide helpful guidance for researchers, many of them ([8, 27, 28, 29]) focus on multiple compression techniques, such as pruning, quantization, and knowledge distillation, with only brief examination of each technique. For example, Mishra et al. [27] summarize the compression techniques, including pruning, quantization, low-rank factorization, and knowledge distillation, where pruning is primarily introduced from channel/filter pruning, and many essential pruning techniques (such as lottery ticket hypothesis) are not included. Some review works (such as [30]) focus on reviewing convolutional neural network pruning and lack a description of pruning for other deep neural networks, such as Recurrent Neural Networks (**RNNs**). The work in [31] provides a comprehensive review of sparsity in deep learning up to 2020, but with little studying on emerging pruning methods, such as pruning in contrastive learning [32] and self-supervised pruning [33], etc. Wang et al. [34] provide an overview only for pruning at initialization and does not include studies on pruning during training, pruning after training, etc. [35] is the most recent survey about pruning, while which only focuses on the structured pruning. This survey aims to provide a comprehensive overview of deep neural network pruning to diverse readers. We review representative pruning methods, propose a new taxonomy, conduct a comprehensive analysis of how different pruning manners behave in practice and give practitioners who wish to utilize pruning recommendations on choosing a suitable pruning method for different requirements. Our contributions are as follows: **(1) Comprehensive review.** To our best knowledge, this survey is the most comprehensive overview of modern deep neural network pruning techniques. It distills ideas from over 300 related academic papers and establishes a new taxonomy, as shown in Fig. 2. In addition, we provide detailed descriptions of the representative methods for each class of pruning methods. **(2) Comparative experiments and analysis.** We conduct a comparative analysis of seven pairs of contrast settings for pruning and emerging advances, including different levels of supervision for pruning. Unlike the existing surveys on pruning, this paper conducts experiments and related discussions. **(3) Collection of abundant resources.** We summarize miscellaneous pruning applications and provide benchmark datasets, networks, and evaluations on different applications. Our collected resources in Appendix B could guide researchers and practitioners to understand, utilize, and develop different network pruning methods for various requirements. The ongoing updates of representative pruning efforts are available at [https://github.com/hrcheng1066/a](https://github.com/hrcheng1066/a) wesome-pruning. **(4) Recommendations and future directions.** This survey provides valuable recommendations on choosing an appropriate pruning method for different application requirements and highlights promising future research directions. The remainder of this survey is organized as follows. First, in Section 2, we explain commonly used terms and establish a clear taxonomy of pruning. Section 3 - 6 offer an overview of speedup, when to prune, and how to prune, followed by a comprehensive comparative analysis of different kinds of pruning methods in Section 7. Section 8 discusses integrating pruning with other compression methods. Some practical recommendations for choosing pruning methods and future directions are provided in Section 9. We conclude this paper in Section 10. ## 2 Background In this section, we first list the commonly used terms and notations in this literature. Then the hierarchical structure of this survey is shown in Fig. 2. ### _Terms and Notations_ The following subsection presents the commonly used terms in pruning literature. It is worth mentioning that some terms (e.g., compression ratio) have a variety of definitions in prior works. We then provide several definitions used in different literature. In addition, for better readability, we list the notations used in this paper in Table II. \begin{table} \begin{tabular}{l|c|c} \hline Survey & Main work description & Year \\ \hline [36] & survey of pruning methods & 1993 \\ [37] & overview 81 papers and propose ShrinkBench, & 2020 \\ & an open-source framework for evaluation & 2020 \\ [28] & pruning-weight sharing+low-rank matrix+ & 2020 \\ & KD+quantization & 2020 \\ [30] & pruning criteria+procedure & 2020 \\ [8] & pruning+quantization+KD+low-rank factor. & 2020 \\ [27] & pruning+KD+NAS+Tensor-Decompose & 2020 \\ & +quantization+hardware acceleration & 2021 \\ [31] & work on sparsity in deep learning up to 2020 & 2021 \\ [34] & overview pruning at initialization & 2022 \\ [29] & pruning+KD+NAS+quantization & 2022 \\ [35] & +Tensor-Decompose+hardware accel. & 2023 \\ \hline \end{tabular} \end{table} TABLE I: Representative surveys and descriptions. Fig. 1: The number of papers for neural network pruning and compression from 1988-2022. * **Prune Ratio**: Prune ratio [38] denotes the percentage of weights (or channels, filters, neurons, etc.) that are removed from the dense network. In general, it can be determined in two ways: pre-defined or learning-decide. * **Compression Ratio**: Compression ratio in [39, 40] is defined as the ratio of the original weight numbers to the preserved weight numbers, but in [41] it is defined as the ratio of the preserved weight numbers to the original weight numbers. For example, if 10% of weights are preserved, then the compression ratio in [40] is 10, but it is 10% in [41]. * **Sparsity Ratio**: Sparsity ratio or sparsity denotes the portion of zero weights (or channels, filters, neurons, etc.) in networks after pruning [42, 43]. It equals to compression ratio in [41]. * **Speedup Ratio**: Speedup ratio is defined as the value of the pruned number of FLOPs in [12], or MACs in [44] divided by the original number of FLOPs or MACs correspondingly. In [45], the speedup ratio is calculated by dividing the pruned number of filters in one layer by the original number of filters in that layer. * **One-shot Pruning**: One-shot pruning, also called single-shot pruning in [46], scores only once and then prunes the network to the target prune ratio [47, 48]. * **Iterative Pruning**: Iterative pruning [10], also called greedy pruning or oracle pruning in [49], repeatedly score-prune-retrain circle multiple rounds, and each round is one iteration. * **Local Pruning**: Local pruning prunes a network by subdividing all weights (or filter, channels, etc.,) into subsets (e.g., layers) and then removing a percentage of each subset [50]. * **Global pruning**: In contrast to local pruning, global pruning removes structures from all available structures of a network until a specific prune ratio is reached [50]. * **Dynamic pruning**: Dynamic pruning depends on specific inputs [51], wherein different subnetworks will be generated for each input sample. * **Static Pruning**: In contrast to dynamic pruning, the pruned model is shared by different samples for static pruning [51]. In other words, the model capacities are fixed for different inputs. * **Lottery Ticket Hypothesis**: Lottery Ticket Hypothesis (**LTH**) [47] points out that a randomly-initialized dense network \(f(\mathbf{x};\mathbf{w}_{0})\) contains a sparse subnetwork \(f(\mathbf{x};\mathbf{w}_{0}\odot\mathbf{m})\) which is trainable with the original weights to achieve competitive performance compared to the original networks. * **Winning Tickets**: For a randomly initialized network \(f(\mathbf{x};\mathbf{w}_{0})\), a winning ticket \(f(\mathbf{x};\mathbf{w}_{0}\odot\mathbf{m})\) is its subnetwork that once be trained for \(T\) epochs (i.e., \(f(\mathbf{x};\mathbf{w}_{T}\odot\mathbf{m})\) will match the performance of the trained network \(f(\mathbf{x};\mathbf{w}_{T})\) under a non-trivial prune ratio. [47]. * **Layer-collapse**: Layer-collapse is a phenomenon mentioned in [39], which occurs when all weights of a layer of a network are removed. It renders the network untrainable. Hayou et al. [52] given a formal definition (i.e., ill-conditioned NN) to this problem. * **Weight Rewinding**: Weight rewinding [53] rewinds the weights of the subnetwork to the values in an earlier epoch in training \(\mathbf{w}_{t}\), where \(t<<T\). * **Learning Rate Rewinding**: Learning rate rewinding, proposed in [40], trains the remained weights from the final values using the learning rate schedule for the specified number of epochs. ### _Taxonomy_ There are three critical questions when pruning a deep neural network. **(1) Whether to get universal or specific acceleration through neural network pruning? (2) When to prune the neural network? Specifically, is the neural network pruned before, during, or after training the network for static pruning or dynamic (i.e., run-time) pruning? (3) Whether to prune based on specific criteria or learn to prune?** The answers to the three questions correspond to the three primary aspects of deep neural network pruning as shown in Fig. 2, respectively. **The first question** is whether speedup depends on specific hardware/software. It is usually divided into three types: unstructured ([39, 46, 47]), semi-structured (also called pattern-based) ([54, 55, 56]) and structured ([57, 58, 59]). Only structured pruning can achieve universal neural network acceleration and compression without requiring special hardware or software. Conversely, both unstructured and semi-structured pruning need the support of special hardware or software. **The second question** especially indicates the arrangement between pruning weights and training weights of the neural network for static pruning. According to whether pruning is performed before, during, or after training the network, static pruning arrangement can be divided into three categories: pruning before training (**PBT**) ([39, 46, 52, 60, 61]), pruning during training (**PDT**) ([62, 63, 64]), and pruning after training (**PAT**) ([47, 65, 66, 67]). In dynamic pruning, subnetworks are generated at run-time for each input data point. **The third question** considers whether to prune neural networks with specific criteria or by learning. Criteria rely \begin{table} \begin{tabular}{l|c} \hline Notation & Description \\ \hline \(\mathbf{x}\) & Input data \\ \(\mathcal{D}\) & Dataset \\ \(f\) & A network function \\ \(N\) & The number of samples in a dataset \\ \(\mathbf{w}\) & The model weights \\ \(\mathbf{w}_{t}\) & The weights after training \(t\) epochs \\ \(\mathcal{F}_{i,j}\) & The \(j\)-th filter of the \(i\)-th layer \\ \(c_{t}\) & The \(i\)-th channel of a network \\ \(\ell\) & Standard loss function, e.g., cross-entropy loss \\ \(\mathcal{L}\) & Target loss function \\ \(L\) & Total number of layers in a network \\ \(\odot\) & Element-wise multiplication \\ \(\lambda\) & A balance factor \\ \(\boldsymbol{\gamma}\) & A scaling factor vector \\ \(\boldsymbol{\mathrm{m}}\) & The masks of weights (or filters, channels, etc.) \\ \(\mathcal{R}(\cdot)\) & Regularization term \\ \(\Delta\mathcal{L}\) & Loss change \\ \(c_{out}^{(i)}\) & The number of filters at layer \(i\) \\ \(t\) & Threshold vector \\ \hline \end{tabular} \end{table} TABLE II: Notations and descriptions. on a heuristic formula to measure the importance of each weight (or filter, channel, and so on). The commonly used pruning criteria include magnitude, norm, loss change, etc. In addition, it is also possible to prune neural networks by learning, such as pruning through sparsity regularization training or dynamic sparse training [68], etc. Whether through criteria or learning, pruning aims to determine the weights of a network that should be pruned. The above three aspects determine the main characteristics of a pruning algorithm. Different combinations of these three aspects form different pruning methods. We provide a new taxonomy of deep neural network pruning in Section 3-6, and Section 8, as shown in Fig. 2. ## 3 Specific or Universal Speedup This section categorizes deep neural network pruning into unstructured, semi-structured, and structured. The first two types correspond to specific speedup, and the third corresponds to universal speedup. In the following, we give a detailed introduction to each category. ### _Unstructured Pruning_ Unstructured pruning, also called non-structured pruning or weight-wise pruning, is the finest-grained case. **Definition 1** (Unstructured Pruning). Given neural network weights \(\mathbf{w}=\{w_{0},w_{1},...,w_{K}\}\), a dataset \(\mathcal{D}=\{(\mathbf{x}_{i},\mathbf{y}_{i})\}_{i=1}^{N}\) composed of input (\(\mathbf{x}_{i}\)), output (\(\mathbf{y}_{i}\)) pairs, and a desired total number of non-zero weights \(k\), unstructured pruning can be written as the following constrained optimization problem [46]: \[\begin{split}\underset{\mathbf{w}}{\text{min}}& \mathcal{L}(\mathbf{w};\mathcal{D})=\underset{\mathbf{w}}{\text{min}}\, \frac{1}{N}\sum_{i=1}^{N}\ell(\mathbf{w};(\mathbf{x}_{i},\mathbf{y}_{i})),\\ &\text{s.t.}\ \|\mathbf{w}\|_{0}\leq k.\end{split} \tag{1}\] In practice, unstructured pruning usually does not directly set the weights to 0 but sets their corresponding masks (or indicators) \(\mathbf{m}\) to 0 [61, 46]. In this case, unstructured pruning is regarded as applying a binary mask to each weight. Then Eq.(1) is correspondingly changed as: \[\begin{split}\underset{\mathbf{w},\mathbf{m}}{\text{min}}& \mathcal{L}(\mathbf{w}\odot\mathbf{m};\mathcal{D})=\underset{ \mathbf{w},\mathbf{m}}{\text{min}}\,\frac{1}{N}\sum_{i=1}^{N}\ell(\mathbf{w} \odot\mathbf{m};(\mathbf{x}_{i}.\mathbf{y}_{i})),\\ &\text{s.t.}\ \|\mathbf{m}\|_{0}\leq k.\end{split} \tag{2}\] Generally, the network is retrained (i.e., fine-tuning or training-from-scratch) with fixed masks \(\mathbf{m}\), and the masked-out weights are not involved in retraining. Fig. 3 is an example of weight-wise pruning by removing the connections of the neurons (as shown in Fig. 3(a)) or masking the weights with their corresponding masks (as shown in Fig. 3(b)), respectively. Since it can remove weights anywhere, the irregular replacement of non-zero weights leads to actual acceleration requires the support of special software and/or hardware [69, 69, 11, 63, 51]. Therefore, we classify unstructured pruning as a specific speedup technique. ### _Structured Pruning_ **Definition 2** (Structured Pruning). Given a specific prune ratio and a neural network with \(S=\{s_{1},s_{2},...,s_{L}\}\), where \(s_{i}\) can be the set of channels, filters, or neurons in layer \(i\). Structured pruning aims to search for \(S^{{}^{\prime}}=\{s^{{}^{\prime}}_{1},s^{{}^{\prime}}_{2},...,s^{{}^{\prime}}_{L}\}\) to minimize the performance degeneration and maximize the speed improvement under the given prune ratio, where \(s^{{}^{\prime}}_{i}\subseteq s_{i}\), \(i\in\{1,..,L\}\). Structured pruning removes entire filters, channels, neurons, or even layers ([64]) as shown in Fig. 4(b) and can rebuild a narrow model with a regular structure. It does not need the support of special hardware and software (such as sparse convolution libraries) and can directly speed up networks and reduce the size of the neural networks [69, 71, 14, 50]. Besides, filter and channel pruning can be considered equivalent because pruning a filter in layer \(i\) is equivalent to pruning the corresponding channels in layer \(i+1\)[72], as shown in Fig. 4(a). ### _Semi-structured Pruning_ To improve the flexibility of structured pruning and achieve lower accuracy drop when the pruning rate is high, some Fig. 2: An overview of the hierarchical structure of the survey. recent works ([55, 56]) introduce semi-structured pruning that is called pattern-based pruning in [56] to achieve high accuracy and structural regularity simultaneously. Various patterns can be designed; some examples are shown in Fig. 4(c). In contrast, fully structured pruning (such as channel or filter pruning) is classified as coarse-grained structured pruning ([55, 56, 73]), while semi-structured pruning is classified as fine-grained structured pruning. For example, Meng et al. [74] treat a filter as several stripes and propose to prune stripes in each filter. However, patterns used for semi-structured pruning need to be carefully designed to alleviate performance degradation and conduct specific speedup like unstructured pruning. ## 4 When to Prune This section distinguishes three pruning pipelines for static pruning, as illustrated in Fig. 5, and run-time pruning. The examples of the three pipelines of static pruning are shown in Fig. 6. The statistics of pruning literature on the three types of pipelines for static pruning are shown in Appendix B Fig. 12. ### _Pruning Before Training_ Pruning Before Training (**PBT**), also called foresight pruning [61] or pruning at initialization [39, 46], represents a class of pruning methods that use randomly initialized weights for pruning the network. The principal motivation of PBT methods is to eliminate the cost of pretraining. Without loss of generality, we define a neural network as a function \(f(\mathbf{x};\mathbf{w}\odot\mathbf{m})\). The mask \(\mathbf{m}\) is used for pruning initialized weights \(\mathbf{w}_{0}\) sampled from a specific initialization distribution. After pruning, the network \(f(\mathbf{x};\mathbf{w}_{0}\odot\mathbf{m}^{{}^{\prime}})\) is trained to converge \(f(\mathbf{x};\mathbf{w}_{T}\odot\mathbf{m}^{{}^{\prime}})\) after \(T\) epochs, where \(\mathbf{m}^{{}^{\prime}}\) indicates the sparsity results after pruning. dynamic process than that of PBT and PAT methods. We summarize the main prior solutions as the three paradigms: (1) sparsity regularization based, (2) dynamic spare training based, and (3) score-based. The methods related to (1) or (3) take dense-to-sparse training, and the ones related to (2) conduct sparse-to-sparse training. #### 4.2.1 Sparsity Regularization based Methods Sparsity regularization technique is commonly used in PDT methods ([74, 88]). This category of methods starts with dense networks, imposes sparse constraints on loss functions, and usually zeros out some weights or their masks during training. The main effort is to design the effective target loss function \(\mathcal{L}\) with an advanced penalty scheme and efficient optimization algorithms. For example, Wen et al. [63] propose Structured Sparsity Learning (**SSL**) to learn a sparse structure by group LASSO [89] regularization during the training. However, SSL requires computing the gradients of the regularization term w.r.t. all the weights, which is non-trivial. Gordon et al. [90] propose **MorphNet** that reuses the parameters of BN and conducts sparsity regularization on these parameters. However, some networks (e.g., some VGGNets [2]) have no BN layers. Instead of reusing BN parameters, some works associate scaling factors with channels, filters, layers, etc. For example, Huang and Wang [64] propose Sparse Structure Selection (**SSS**) that associates scaling factors for CNN micro-structures (e.g., channels, residual blocks) and exploit sparsity regularization to force the output of the micro-structures to zero, rather than pushing the weights in the same group to zero in [63]. In addition, SSS does not require extra fine-tuning that is needed in [63]. Li et al. [91] propose factorized convolutional filter (**FCF**) which introduces a binary scalar to each filter and proposes a back-propagation with Alternating Direction Method of Multipliers (**ADMM**) [92] algorithm to train the weights and the scalars during training jointly. #### 4.2.2 Dynamic Sparse Training based Methods A class of the PDT methods ([84, 93, 94, 95, 96, 97, 98]) take randomly initialized sparse network rather than dense network as the input model. Subsequently, one common method is pruning a fraction of unimportant weights followed by regrowing the same number of new weights to adjust the sparse architecture. By repeating the prune-and-grow cycle during training, this kind of method keeps searching for better sparse architecture, which is classified as dynamic sparse training in [84]. \begin{table} \begin{tabular}{l|c c c} \hline Method & Criteria & U/S & Date-Free (Y/N) & One-shot (Y/N) \\ \hline SNIP (2019) [46] & \([\mathbf{V_{w}}\mathcal{L}(\mathbf{w})\odot\mathbf{w}]\) & U & N & Y \\ Gersp (2020)[61] & \(-(H\mathbf{V_{w}}\mathbf{w}(\mathbf{w}))\odot\mathbf{w}\) & U & N & Y \\ Smart-Ratio (2020) [60] & keep-ratios & U & Y & Y \\ SynFlow (2020) [39] & \(\nabla_{w}\mathcal{R}_{SF}(\mathbf{w})\odot\mathbf{w}\) & U & Y & N \\ PFS (2020) [76] & \(l_{1}\)-norm based sparsity regularization & S & N & N \\ RST (2022) [65] & \(l_{2}\)-norm based sparsity regularization & U & N & N \\ \hline \end{tabular} \end{table} TABLE III: Representative methods of pruning before training. “U/S” denotes unstructured or structured pruning. Fig. 4: The visualization of structured and semi-structured pruning, where each Conv is composed of a specific number of little cubes, and each little cube indicates a weight. The light orange cubes denote the pruned weights. Fig. 3: The visualization of unstructured pruning. The light orange circles denote neurons. For example, Mocanu et al. [93] propose Sparse Evolutionary Training (**SET**) that removes the smallest positive and the most negative weights and grow new weights in random locations. Instead of pruning a fixed fraction of weights at each redistribution step, such as in SET [93], Mostafa and Wang [95] propose Dynamic Sparse Reparameterization (**DSR**) which uses an adaptive threshold for pruning. In addition, DSR [95] reallocates weights across layers and does not restrict to the inner-layer weight redistribution in SET [93]. Liu et al. [99] propose an ensemble method **FreeTickets** that ensemble sparse subnetworks created by sparse-to-sparse methods. Instead of using a random regeneration scheme, Dai et al. [94] propose a DNN synthesis tool (**NeST**) that stars training with a small network, adjust the subnetworks with gradient-based growth and magnitude-based pruning. Evci et al. [84] propose Rigged Lottery (**RigL**) that actives new connections during training by using gradient magnitude. Similarly, Liu et al. [96] propose Gradual Pruning with zero-cost Neurogeneration (**GraNet**) to remove connections of networks based on their weight magnitudes and regrow connections of networks based on their gradient. They argue that even the weights with zero gradient values indicate the connection importance. Sokar et al. [100] pioneer to explore dynamic sparse training in Reinforcement Learning (**RL**). Graesser et al. [101] systematically investigate some dynamic sparse training methods (such as RigL [84], SET [93]) in RL. Evci et al. [102] analyze the reasonability of dynamic sparse training. The authors find sparse networks have poor gradient flow at initialization, but dynamic sparse training significantly improves gradient flow. It could be the reason for their success. #### 4.2.3 Score-based Methods Some PDT methods exploit scoring criteria to prune the networks during training. He et al. [86] propose Soft Filter Pruning (**SFP**) filter pruning method which can train the networks from scratch and prune the networks simultaneously by using the \(l_{2}\) norm of each filter as its importance. Instead of associating masks with filters, they directly set the pruned filter weights as zeros, which can be updated from zeros through the forward-backward process. Hence, the pruned filters in this epoch can be recovered in the next epoch. However, SFP requires manually preset prune ratios for each layer. He et al. [103] propose Filter Pruning via Geometric Median (**FPGM**) to prune the redundant filters which are nearest to the geometric median [104] of the filters within the same layer. However, FPGM also requires a pre-defined prune ratio for each layer. Liu et al. [62] propose a method called **Network Slimming** which introduces a scaling factor for each channel and jointly trains the weights and the scaling factors by adding the regular loss \(\ell\) with sparsity regularization on the factors, and the magnitudes of these scaling factors are used as the filter scores. In practice, they directly reuse the \(\gamma\) parameters in Batch Normalization (**BN**) [105] layers as the scaling factors. ### _Pruning After Training_ Pruning After Training (**PAT**) is the most popular type of pruning pipeline because it is commonly believed that pretraining the dense network is necessary to obtain an efficient subnetwork [38]. This class of pruning methods generally follows a Pretrain-Prune-Retrain process as shown in Fig. 5 (c). (1) Pretrain a randomly initialized dense network \(f(\mathbf{x};\mathbf{w}_{0})\) to converge \(f(\mathbf{x};\mathbf{w}_{T})\). (2) Prune the weights (or \begin{table} \begin{tabular}{l|c c c} \hline Method & Object function/Criteria & Retrain (Y/N) & U/S \\ \hline Network Slimming (2017) [62] & \(\min_{\mathbf{w},f}\ell(\mathbf{y},f(\mathbf{x};\mathbf{w}))+\lambda\| \boldsymbol{\gamma}\|_{1}\) & Y & S \\ SSS (2018) [64] & \(\min_{\mathbf{w},f}\ell(\mathbf{y},f(\mathbf{x};\mathbf{w},\boldsymbol{\gamma })+\mathcal{R}(\mathbf{w})+\lambda\|\boldsymbol{\gamma}\|_{1}\) & N & S \\ SET (2018) [93] & \(\|\mathbf{w}\|\) for drop and random for grow & N & U \\ DST (2020) [68] & \(\min_{\mathbf{w},f}\ell(\mathbf{y},f(\mathbf{x};\mathbf{w}))+\lambda\sum_{i=1}^ {L}\sum_{j=1}^{c(i)}exp(-\mathbf{t}_{j})\) & N & S \\ GraNet (2021) [96] & \(\|\mathbf{w}\|\) for drop and gradient for grow & N & U\&S \\ FreeTickets (2022) [99] & \(\|\mathbf{w}\|\) for drop and gradient for grow & N & U \\ \hline \end{tabular} \end{table} TABLE IV: Representative methods of pruning during training. “retrain” refers to training from scratch or fine-tuning, “U/S” denotes unstructured or structured pruning. Fig. 5: The typical pruning pipelines of static pruning. Dashed boxes represent models and solid boxes denote actions. filters, neurons, etc.) that have the least influence on the performance and fine-tune the pruned network \(f(\mathbf{x};\mathbf{w}_{T}^{{}^{\prime}}\odot\mathbf{m}^{{}^{\prime}})\) for several iterations, where \(\mathbf{w}_{T}^{{}^{\prime}}\) and \(\mathbf{m}^{{}^{\prime}}\) are the weights and masks after pruning, respectively. Process (2) is processed at least once (i.e., one-shot pruning) or multiple times (i.e., iterative pruning). (3) Train the remained weights from scratch \(f(\mathbf{x};\mathbf{w}_{0}\odot\mathbf{m}^{{}^{\prime}})\) or fine-tune \(f(\mathbf{x};\mathbf{w}_{T}^{{}^{\prime\prime}}\odot\mathbf{m}^{{}^{\prime \prime}})\) to recover the performance [40], where \(\mathbf{w}_{T}^{{}^{\prime\prime}}\) and \(\mathbf{m}^{{}^{\prime\prime}}\) are the final results of weights and masks after the overall pruning process, respectively. During the pruning process, sparsity is gradually increased until it achieves the target. #### 4.3.1 LTH and its Variants Lottery Ticket Hypothesis (**LTH**) [47] is one of the most influential hypotheses in the neural network pruning domain. Given a pretrained network, LTH iteratively removes a percentage of the weights based on their magnitudes. After pruning, the remaining weights are retrained from scratch with the original initialization, rather than random reinitialization, to match the original networks' accuracies. It challenges the commonly believed paradigm that the pretrained weights must be used for retraining and conjectures the existence of an independently trainable sparse subnetwork from a dense network. Inspired by LTH, there are various follow-up works to identify wider tickets and understand LTH better, which can be classified into four main classes: (1) proposing a stronger lottery ticket hypothesis, (2) exploring the transferability of LTH, (3) generalizing LTH to other contexts, (4) theoretical justification, and (5) revisiting and questioning LTH. (1) Some recent works [106, 107, 108]) prove stronger hypothesis than LTH [47]. For example, Diffenderfer and Kailkhura [108] propose a stronger Multi-Prize LTH, which claims that winning tickets can be robust to extreme forms of quantization (i.e., binary weights and/or activations). Based on this, they propose a Multi-Prize Tickets (**MPTs**) algorithm to find MPIs on binary neural networks for the first time. (2) Some literature ([67, 109, 110, 111]) studies the transferability of a winning ticket found in a source dataset to another dataset, which provides insights into the transferability of LTH. For example, S. Morcos et al. [109] find OneTicket that can generalize across a variety of datasets and optimizers within the natural image domain. Mehta [110] propose the ticket transfer hypothesis and transfer winning tickets for different image classification datasets. (3) In addition to image classification, LTH is extended to numerous other contexts, such as node classification and link prediction ([67]) and vision-and-language ([111]). For example, Chen et al. [67] pioneer to generalize LTH to Graph Neural Networks (**GNNs**) [112] and propose Graph Lottery Ticket (**GLT**). (4) On one hand, some literature ([117, 118]) analyzes the reasons why LTH [47] is able to win. For example, Zhang et al. [117] exploit dynamical systems theory and inertial manifold to theoretically verify the validity of LTH. Evci et al. [102] observe that the success of LTH lies in effectively re-learning the original pruning solution they are derived. Zhang et al. [118] pioneer to provide formal justification of the improved generalization of winning tickets observed from experimental results in LTH. (5) On the other hand, some recent works ([119, 38, 120]) revisit and challenge the existence of LTH. For example, Ma et al. [119] provide a more rigorous definition of LTH for precisely identifying winning tickets and find that whether and when the winning tickets can be identified highly replies on the training settings, such as learning rate, training epochs, and the architecture characteristics, like network capacities and residual connections. It is more likely to find winning tickets by using a small learning rate or an insufficient number of training epochs. It is worth pointing out that in some works [16, 34], LTH [47] is classified as a PBT method. However, LTH selects masks based on a pretrained network, which does not conform to the definition of PBT that attempts pruning the initialized network before training. Therefore, it is more reasonable to classify LTH as a PAT method. #### 4.3.2 Other score-based Methods The most straightforward and intuitive way to select pruning candidates is to evaluate them based on their norms. For example, Han et al. [11] propose to measure the weight importance by its absolute value. Li et al. [69] score every filter in each layer by calculating the sum of its weights' \(l_{1}\)-norm. In addition to norm-based criteria, evaluating loss change with and without the weights is also popular. For example, Nonnenmacher et al. [50] propose Second-order Structured Pruning (**SOSP**) to selectively zero out filter masks to minimize the effects of the loss change from removing some filters. Discrimination-aware Channel Pruning (**DCP**) [121] selects the most discriminative channels by minimizing a joint loss which includes the regular loss with the discrimination-aware loss. Many works ([14, 58, 113, 116]) evaluate the importance of weights (or filters, neurons, etc.) locally within each layer. The key drawback of these methods is that the local ranking makes it hard to decide the overall optimal sparsity, and the pre-defining prune ratio per layer may be non-trivial and sub-optimal. Some works ([122, 123, 43]) are presented to cope with this problem. For example, Chin et al. [122] proposes Learned Global Ranking (**LeGR**) to learn the filter ranking globally across layers. Liu et al. [71] propose Group Fisher Pruning (**GFP**) to apply the Fisher information to evaluate the importance of a single channel and coupled channels. \begin{table} \begin{tabular}{l|c c} \hline \hline Method & Object function/Criteria & U/S \\ \hline Auto-Balance (2018) [113] & score(\(\mathcal{P}_{i,j}\))=\(|\mathcal{F}_{i,j}|\)\(|_{1}\) & S \\ LTH (2019) [47] & score(\(w_{i}\))=\(\|w_{i}\|_{1}\) & U \\ Taylor-CR-BN (2019) [114] & score(\(w_{i}\))=\((\nabla_{w_{i}}\!\! #### 4.3.3 Sparsity Regularization based Methods Some works ([125, 124, 126, 124]) exploit sparsity regularization technique. For example, He et al. [124] propose an alternative two-step algorithm that introduces a scalar mask to each channel of a pretrained CNN model and selects redundant channels based on LASSO regression [127] and reconstructs the outputs with unpruned channels with linear least squares. Energy-Constrained Compression (ECC) [128] builds the energy consumption model via a bilinear regression function. Network Pruning via Performance Maximization (**NPPM**) [129] trains a performance prediction network and uses it as a proxy of accuracy to guide searching for subnetworks based on regularization penalty. Fang et al. [44] develop a general method called **DepGraph** to analyze dependencies of various network structures (e.g., CNNs, RNNs, GNNs, Transformers) and propose a structured pruning based on sparsity regularization. Some methods ([44, 58, 113, 116]) select important weights (or filters, neurons, etc.) by combining norm-based criteria and sparsity regularization. #### 4.3.4 Pruning in Early Training Instead of fully training a network from \(f(\mathbf{x};\mathbf{w}_{0})\) to \(f(\mathbf{x};\mathbf{w}_{T})\), this class of methods explore the network architecture by training a network only for a few iterations or epochs, i.e., \(f(\mathbf{x};\mathbf{w}_{t})\), where \(t<<T\). For example, You et al. [130] propose Early-Bird (**EB**) tickets which indicate that winning tickets can be identified at the early training stage via inexpensive training schemes (e.g., early stopping and low-precision training) at large learning rates and achieve similar performance to the dense network. Inspired by [130], Chen et al. [131] propose **EarlyBERT** that identifies structured winning tickets in the early stage of BERT [132] training. Frankle et al. [53] find that, in large-scale settings (such as ResNet-50 and Inception-v3 on ImageNet), the subnetworks that exhibit stability to SGD noise are able to reach full accuracy early in training. #### 4.3.5 Post-Training Pruning In contrast to the general PAT methods that follow the Pretrain-Prune-Retrain procedure, recently proposed post-training pruning simplifies the three-step process as Pretrain-Prune. It involves pruning a pre-trained model \(f(\mathbf{x};\mathbf{w}_{T})\) without retraining, with a negligible accuracy loss. This class of pruning methods is particularly attractive for billion-parameter models because retraining such pruned models after pruning is still very expensive. For example, Frantar and Alistarh [15] propose an unstructured post-training pruning method called **SparseGPT**. By simplifying the pruning problem to an approximate sparsity regression, the authors prune GPT family models at least 50% sparsity at minor accuracy loss without retraining. To our best knowledge, it is the first pruning method specifically designed for GPT family models. Kwon et al. [133] propose a structured post-training pruning framework for Transformers, which includes three steps: Fisher-based mask search, Fisher-based mask rearrangement, and mask tuning. Without retraining, this framework can prune Transformers on one GPU in less than 3 minutes. ### _Run-time Pruning_ The prior works on pruning usually focus on static pruning methods where the pruned model is reused for different inputs. In contrast, some methods prune neural networks according to individual inputs dynamically, namely runtime pruning [134]. This line of work is based on the premise that for a given task, the difficulty of producing accurate output can vary, implying the necessity of model capacities for different inputs is different [51]. For example, Rao et al. [134] propose a Runtime Network Routing (**RNR**) framework to conduct dynamic routing based on the input image and current feature maps and select an optimal path subset for compression. Tang et al. [51] point out that the importance of channels highly depends on the input data and propose to generate different subnetworks for each instance. At inference, only channels with saliencies larger than the threshold need to be computed, and the redundant features are skipped. Hua et al. [135] exploit input-specific characteristics and propose **CGNets** to predict the unimportant regions by the partial sum of the output activation by performing convolution on a subset of input channels. Gao et al. [136] propose Feature Boosting and Suppression (**FBS**) to predict the saliency of channels and skip those with less contribution to the classification results at run-time. Fire Together Wire Together [33] poses the dynamic model pruning as a self-supervised binary classification problem. Meng et al. [137] propose Contrastive Dual Gating (**CDG**) that is another self-supervised dynamic pruning method by using contrastive learning [138]. Fig. 6: The illustration of typical sparsity changes for PBT, PDT, and PAT (best view in color and zoom in). PBT is usually the cheapest, and PAT is the most expensive. ## 5 Pruning Criteria In this section, we summarize some commonly used pruning criteria that are used to evaluate the importance of weights (or filters, neurons, etc.) from different perspectives, including magnitude ([139, 140, 141]), norm ([69, 86]), saliency and/or sensitivity ([142, 143, 85, 13]), loss change ([144, 50, 71, 13, 13]). There is no rigid boundary between these criteria but a different emphasis. ### _Magnitude-based Pruning_ [26] is one of the earliest works that propose magnitude-based pruning to reduce hidden units. Han et al. [11] popularize magnitude-based pruning for deep neural networks, which prunes the lowest-magnitude weights. It is based on the assumption that the weights with smaller absolute values tend to have the least influence on the network's output. The formulation is defined as \[m_{i}=\begin{cases}1:if\ \|w_{i}\|_{1}\geq a\\ 0:if\ \|w_{i}\|_{1}<a\end{cases}, \tag{3}\] where \(a\) is a threshold. Magnitude-based criteria can be applied for either unstructured ([147, 146, 145, 147, 139, 10]) or structured pruning ([69, 148, 94]). For example, Li et al. [69] score the filters by calculating the sum of their absolute magnitude of weights. In addition, magnitude-based criteria can be combined with global/local, one-shot/iterative schedules. For example, the works in [149] and [150] propose magnitude-based iterative global pruning methods. Singh Lubana and P. Dick [140] argue that magnitude-based pruning results in faster model convergence than magnitude-agnostic methods. ### _\(l_{p}\) Norm_ Some methods ([69, 86]) use the \(l_{p}\) norm to evaluate the importance of weights (or filters, channels, etc.). For example, He et al. [86] exploit \(l_{p}\) norm to evaluate the importance of the filter \(\mathcal{F}_{i,j}\) as Eq.(4). \[\|\mathcal{F}_{i,j}\|_{p}=\left(\sum_{n=1}^{c_{in}^{(i)}}\sum_{k_{1}=1}^{k^{( i)}}\sum_{k_{2}=1}^{k^{(i)}}|\mathcal{F}_{i,j}(n,k_{1},k_{2})|^{p}\right)^{ \frac{1}{p}}, \tag{4}\] where \(k^{(i)}\) is the kernel size of layer \(i\) in a network and \(c_{in}^{(i)}\) is the number of channels at layer \(i\). The filters with small \(l_{p}\) norm are more likely pruned than those of higher \(l_{p}\) norm. Some norm-based pruning methods ([69]) use \(l_{1}\) norm as the importance metric. In this case, these methods also belong to magnitude-based pruning methods. In addition, the importance value is often optimized with norm-based sparsity regularization ([113]) that is discussed in 6.1. ### _Sensitivity and/or Saliency_ Some works ([143, 85, 151]) utilize sensitivity and/or saliency to evaluate the importance of weights (or channels, filters, etc.). The definition of sensitivity or saliency may be different in prior works. For example, LeCun et al. [151] define weight saliency as the loss change induced by pruning that weight. SNIP [46] proposes a saliency criterion called connection sensitivity criterion as the normalized magnitude of the derivatives \(g_{j}\): \[s_{j}(\mathbf{w};\mathcal{D})=\frac{|g_{j}(\mathbf{w};\mathcal{D})|}{\sum_{k= 1}^{m}|g_{k}(\mathbf{w};\mathcal{D})|}, \tag{5}\] where \(s_{j}\) is the sensitivity of the weight \(j\), \(\mathbf{w}\) is the networks weights, \(g_{j}\) is the derivative of the loss \(L(\mathbf{w}\odot\mathbf{m})\) w.r.t. \(m_{j}\). The higher the sensitivity of weight, the more important it is. VCP [85] reformulates the BN layer by extending the scale factor \(\gamma\) on shift term \(\beta\) that is treated as channel saliency. They reformulate BN as follows: \[\mathbf{x}_{out}=\gamma\cdot BN(\mathbf{x})+\tilde{\beta}, \tag{6}\] where \(\tilde{\beta}=\gamma\cdot\beta\). Rather than relying on the value of \(\gamma\), VCP prunes unimportant channels based on \(\gamma\)distributions. ### _Loss Change_ It is a popular criterion to measure the importance of weight (or filter, channel, etc.) by evaluating the loss change of the network with and without it. For simplicity, we take filter importance evaluation as an example. Since reevaluating the whole network's performance after removing filters one by one is nontrivial, some researchers ([143, 50, 71]) approximate a filter's importance in a Taylor expansion based way. **The first-Order Taylor expansion** is the most commonly used method for measuring the loss change. The loss change with a small perturbation at \(\mathbf{w}\) is defined as follows: \[\Delta\mathcal{L}=\mathcal{L}(\mathbf{w}+\Delta\mathbf{w})-\mathcal{L}( \mathbf{w})=\nabla_{\mathbf{w}}\mathcal{L}\ \Delta\mathbf{w}. \tag{7}\] For example, GBN [13] introduces the scaling factors \(\boldsymbol{\lambda}\) to the BN and exploits the first-order Taylor expansion to estimate the loss change \(\Delta\mathcal{L}\) caused by setting some scaling factors to zero as follows: \[\Delta\mathcal{L}(\boldsymbol{\lambda})=|\boldsymbol{\lambda}\nabla_{\boldsymbol {\lambda}}\mathcal{L}-R_{1}(\boldsymbol{\lambda})|\approx|\boldsymbol{\lambda} \nabla_{\boldsymbol{\lambda}}\mathcal{L}|=\left|\frac{\partial\mathcal{L}}{ \partial\boldsymbol{\lambda}}\boldsymbol{\lambda}\right|, \tag{8}\] where \(R_{1}(\boldsymbol{\lambda})\) is the Lagrange remainder. The importance score of the \(i\)-th filter is defined as \[\text{Score}(\mathcal{F}_{i})=\sum_{(\mathbf{x},\mathbf{y})\in\mathcal{D}} \left|\frac{\partial\mathcal{L}(\mathbf{y},f(\mathbf{x};\mathbf{w})}{\partial \lambda_{i}}\lambda_{i}\right|, \tag{9}\] where \(\lambda_{i}\) is the scalar factor of the \(i\)-th filter. **The second-order Taylor expansion** of the loss function is early used in [151] for removing unimportant weights and gradually exploited in many subsequent methods ([50, 71]), which includes the first-order (gradient) term, the second-order (Hessian) term, and the higher-order terms are neglected. Without loss of generality, the approximation of the loss change leads to \[\mathcal{L}(\mathbf{w}+\Delta\mathbf{w})-\mathcal{L}(\mathbf{w})=\nabla_{ \mathbf{w}}\mathcal{L}\ \Delta\mathbf{w}+\frac{1}{2}\Delta\mathbf{w}^{T}H\Delta\mathbf{w}, \tag{10}\] where \(H=\nabla_{\mathbf{w}}^{2}\mathcal{L}(\mathbf{w})\). For example, GFP [71] applies the second-order Taylor expansion to approximate the loss change when removing a channel (setting its mask to 0): \[\begin{split} s_{i}&=\Delta\mathcal{L}=\mathcal{L}( \mathbf{m}-\mathbf{e}_{i})-\mathcal{L}(\mathbf{m})\approx-\mathbf{e}_{i}^{T} \nabla_{\mathbf{m}}\mathcal{L}+\frac{1}{2}\mathbf{e}_{i}^{T}(\nabla_{ \mathbf{m}}^{2}\mathcal{L})\mathbf{e}_{i}\\ &=-\mathbf{e}_{i}^{T}g+\frac{1}{2}\mathbf{e}_{i}^{T}H\mathbf{e}_{ i}=-g_{i}+\frac{1}{2}H_{ii},\end{split} \tag{11}\] where \(\mathbf{e_{i}}\) is the one-hot vector of which the \(i\)-th entry equals one, \(g\) is the gradient of loss function \(\mathcal{L}\) w.r.t. \(\mathbf{m}\). ## 6 Learn to Prune In this section, we present some methods through learning to prune networks, including sparsity regularization ([62, 64, 124, 152, 153]) and some pruning methods based on meta-learning ([87, 152]), graph neural network ([154]), and reinforcement-learning ([134, 43]). ### _Sparsity Regularization based Pruning_ Sparsity regularization based pruning learns the weights and their masks by solving the following problem: \[\min_{\mathbf{w},\mathbf{m}}\mathcal{L}(\mathbf{w},\mathbf{m}), \tag{12}\] where \(\mathcal{L}=\ell(\mathbf{w},\mathbf{m})+\lambda\mathcal{R}(\cdot)\). One common way of this class of pruning methods is introducing scaling factor vector \(\boldsymbol{\gamma}\) for weights (or channels, filters, etc.). The network weights and the scaling factors \(\boldsymbol{\gamma}\) are trained jointly with sparsity regularization imposed on the latter. The magnitude of the scaling factors is treated as the important scores. Specifically, \(\mathcal{L}\) in Eq. 12 can be exemplified as follows: \[\mathcal{L}=\frac{1}{N}\sum_{i=1}^{N}\ell(\mathbf{y}_{i},f(\mathbf{x}_{i}; \mathbf{w},\boldsymbol{\gamma}))+\lambda\sum_{\gamma_{i}\in\boldsymbol{ \gamma}}\mathcal{R}(\gamma_{i}). \tag{13}\] For example, He et al. [124] cast channel selection as reconstruction error minimization of feature maps and formulate the channel pruning problem as follows: \[\begin{split}&\min_{\beta,\mathbf{w}}\frac{1}{2N}\|\mathbf{y}- \sum_{i=1}^{c}\beta_{i}X_{i}W_{i}^{T}\|_{F}^{2}+\lambda\|\beta\|_{1},\\ &\text{subject to }\|\beta\|_{0}\leq c^{\prime},\forall i\;\|W_{i} \|_{F}=1.\end{split} \tag{14}\] where \(\|\cdot\|_{F}\) is Frobenius norm, \(X_{i}\) is \(N\times k_{h}k_{w}\) matrix from \(i\)-th channel of input \(\mathbf{x}\), \(W_{i}\) is \(n\times k_{h}k_{w}\) weights from \(i\)-th channel of \(\mathbf{w}\), \(k_{h}\) and \(k_{w}\) are the kernel height and width, respectively. \(N\), \(c\), \(c^{\prime}\), and \(n\) are the number of samples, channels, retained channels, and filters, respectively. To solve this problem, He et al. [124] use LASSO regression [127] and greedy strategy to select the unimportant channels. ### _Meta-Learning based Pruning_ Some works ([87, 152]) adopt meta-learning to prune models. For example, MetaPruning [87] trains a meta network, PruningNet, to predict weights for different pruned networks. The PruningNet takes a network encoding vector \((v_{1},v_{2},...,v_{L})\) as input and outputs the weights \(\mathbf{w}\) of the pruned network: \[\mathbf{w}=\text{PruningNet}(v_{1},v_{2},...,v_{L}), \tag{15}\] where \(v_{i}\) is the number of the channels for \(i\)-th layer. The weights and the corresponding accuracy of each pruned network are obtained by inputting the network encoding into the fully trained PruningNet. Considering the huge search space of network encoding vectors, the pruned network is found by evolutionary search under the constraints. ### _Graph Neural Network based Pruning_ Any network can be viewed as a graph. GraphPruning [154] applies graph convolution to model compression for the first time. Specifically, GraphPruning designs a graph aggregator \(G\) with weights \(\theta_{G}\) combined with the Fully Connected (FC) layers to generate the weights \(\mathbf{w}=(\mathbf{w}^{(1)},\mathbf{w}^{(2)},...,\mathbf{w}^{(L)})\) of the Pruned Network as follow: \[\begin{split}&(n_{1},n_{2},...,n_{L})=G(b_{1},b_{2},...,b_{L}| \theta_{G}),\\ &\mathbf{w}^{(i)}=FC_{i}(n_{i}|\theta_{i}),\end{split} \tag{16}\] where \(b_{i}\in R^{1\times 7}\) denotes the embedding features of \(i\)-th node, \(n_{i}\) is the \(i\)-th column of output with the graph aggregator, \(\theta_{i}\) is the weights of the \(i\)th FC layer, and \(\mathbf{w}^{(i)}\) is the weights of the \(i\)-th pruned layer of the pruned network. Then the pruned network is fully trained on the dataset. Herein, the graph aggregator is responsible for extracting high-level features for each node, while each FC layer is used to generate reasonable weights for the pruned network. Afterward, the best configuration of the pruned network under computational constraints is searched by RL methods, during which the weights of the graph aggregator and FCs are not updated. ### _Reinforcement Learning based Pruning_ Rather than using RL to search the best configurations of the pruned networks in [154], some AutoML pruning methods ([134, 133]) adopt RL to compress models automatically. For example, He et al. [43] propose AutoML for model compression (**AMC**) method that is based on Q-learning, a kind of RL, to concern how an agent should take actions in order to maximize the cumulative reward. Specifically, He et al. [43] design the Deep Deterministic Policy Gradient (**DDPG**) agent to receive an embedding state \(s_{i}\) of layer \(l_{i}\) from the environment and output a sparsity ratio as action \(a_{i}\). Then layer \(l_{i}\) is compressed with \(a_{i}\) using a specific compression method (such as a channel pruning method). After that, the agent moves to layer \(l_{i+1}\) and does the same work as layer \(l_{i}\) until the final layer \(l_{L}\). The update process is as follows: \[\begin{split} Loss=\frac{1}{N}\sum_{i=1}^{N}(y_{i}-Q(s_{i},a_{i}| \mathbf{w}^{Q}))^{2},\\ y_{i}=r_{i}-b+\gamma Q(s_{i+1},\mu\;(s_{i+1})|\mathbf{w}^{Q}), \end{split} \tag{17}\] where \(b\) is the baseline reward, \(\gamma\) is a discount factor used to avoid over-prioritizing short-term rewards, \(\mathbf{w}^{Q}\) is the weights of the network \(Q\) following Block-QNN [155], and \(r_{i}\) is the reward of the whole trajectory for the \(i\)-th sample. He et al. [43] observe that Error is inversely-proportional to \(log(\text{FLOPs})\) or \(log(\#\text{Param})\). Based on this observation, the reward function is defined as: \[\begin{split}&\text{R}_{\text{FLOPs}}=-\text{Error}\cdot log( \text{FLOPs}),\\ &\text{R}_{\text{Param}}=-\text{Error}\cdot log(\#\text{Param}). \end{split} \tag{18}\] This reward function provides an incentive for reducing FLOPs or the number of network parameters. ## 7 A Comprehensive Comparative Analysis In this section, we focus on a comparative analysis of how to behave in different pruning manners, including seven pairs of contrast settings for pruning, the different layer-wise densities of networks, and different levels of supervision for pruning. We also conduct comparative experiments to examine some pruning methods for VGGNet [2]/ResNet [6] on CIFAR-10 [156]/CIFAR-100 [156] under different contrast settings. The experimental settings refer to Appendix A. ### _Unstructured vs. Structured Pruning_ Unstructured pruning methods ([70, 11]) remove weights anywhere and can achieve high prune ratios with little impact on accuracy. In contrast, structured pruning ([13, 50, 71]) conducts pruning at entire filters (or channels, neurons, blocks, layers, etc.), which results in really compressed network and accelerated inference, but the accuracy is more likely lower than that of unstructured pruning under the same prune ratio, weight-level scoring, pipeline, and learning schemes. The possible reason is that unstructured pruning only focuses on the importance of a single weight, while structured pruning forces structural coupling, which demands the simultaneous pruning of multiple layers and expects all removed weights to be consistently unimportant. However, meeting the consistency of unimportant weights under the structural coupling constraints is challenging. The advantages and disadvantages of unstructured and structured pruning are briefly summarized in Table VI. We prune VGG-16 on CIFAR-10 [156] in 3 random runs and report the best results to compare unstructured and structured pruning of SNIP [46] and GraSP [61]. The vanilla SNIP and GraSP are unstructured pruning, denoted by SNIP-unstruct and GraSP-unstruct in Table VII, respectively. To prune channels, after scoring each weight by vanilla SNIP or GraSP, the sum of the weight-level scores in each channel is calculated as its importance score. As shown in Table VII, for SNIP and GraSP, Top-1 accuracy of unstructured pruning is generally better than their corresponding structured pruning under the same prune ratio of weights. ### _One-shot vs. Iterative Pruning_ One-shot pruning methods score once and then prune the network to a target prune ratio. Conversely, the iterative pruning methods alternately process the score-prune-retrain cycle until achieving the target prune ratio. As a result, the pruning cost in one-shot methods usually can be negligible, which greatly saves pruning efforts. However, this kind of method is not friendly to those significant weights whose importance is not immediately apparent at the beginning [109]. Hence, one-shot pruning generally requires more carefully designed scoring criteria to match the performance of the original network. In addition, the results in [39] show that one-shot pruning may more easily suffer from layer-collapse, resulting in a sharp accuracy drop. In contrast, iterative methods require more pruning cost but generally yield better accuracy [13, 157, 110, 69, 120]. Lin et al. [97] analyze the difference between one-shot and iterative pruning methods from the perspective of stochastic gradient. Their results show that the iterative pruning method computes a stochastic gradient at the pruned model and takes a step that best suits the compressed model. In contrast, one-shot pruning method computes a stochastic gradient at the original weights and moves towards the best dense model. We prune VGG-16 and ResNet-32 on CIFAR-10 by SynFlow [39] and Magnitude-based pruning (For simplicity, it will be referred to as Magnitude in the following.) under one-shot or iterative pruning, respectively. As illustrated in Fig. 7, Top-1 accuracy of iterative pruning is generally better than the corresponding one-shot pruning. ### _Data-free vs. Data-driven Pruning_ Most of the existing pruning works ([71, 50, 46]) belong to data-driven methods, and only a few methods ([39, 60, 158, 159]) are data-free. Data is generally believed to be essential for finding good subnetworks. We prune VGG-16 on CIFAR-10 and SVHN by two data-free pruning methods (i.e., SynFlow [39] and Smart-Ratio [60]) and two data-driven methods (i.e., SNIP [46] and Magnitude). Both CIFAR-10 and SVHN are 10-class datasets. As shown in Fig. 8, the prune ratio per layer of VGG-16 by SynFlow or Smart-Ratio on CIFAR-10 is the same as the prune ratio of the corresponding layer on SVHN. However, the prune ratio per layer differs when SNIP or Magnitude prunes VGG-16 on CIFAR-10 and SVHN. Especially for Magnitude, the prune ratios of lower layers on CIFAR-10 are different from those on SVHN. The results in Table VIII are the best in three random runs and show that although data-free methods achieve good Top-1 accuracy on CIFAR-10 [156], SVHN \begin{table} \begin{tabular}{l|c|c} \hline & Unstructured & Structured \\ \hline High sparsity with & \(\blacktriangledown\) & hard \\ minor accuracy drop & \(\blacktriangledown\) & \(\blacktriangledown\) \\ \hline Speedup w/o specific hardware & & \\ (e.g., FPGAs or ASICs) & hard & \\ \hline Speedup w/o specific software & & \\ (e.g., sparsify CNNs libraries) & hard & \\ \hline Really compressed with & & \\ significant acceleration & hard & \\ \hline Structure coupling & \(\bigstar\) & \(\bigstar\) \\ \hline \end{tabular} \end{table} TABLE VI: Advantages and disadvantages of unstructured and structured pruning. \begin{table} \begin{tabular}{l|c|c|c|c} \hline Dataset & CIFAR-10 & CIFAR-100 \\ \hline Parameters \(\downarrow\) (\%) & 10 & 40 & 10 & 50 \\ \hline SNIP-unstruct [46] & **93.34** & **93.73** & **73.09** & **72.67** \\ SNIP-struct & 93.74 & 93.71 & 72.82 & 70.68 \\ \hline GraSP-unstruct [61] & 93.58 & **93.18** & **72.46** & **71.42** \\ GraSP-struct & **93.67** & 93.04 & 72.43 & 71.30 \\ \hline \end{tabular} \end{table} TABLE VII: Top-1 accuracy of unstructured and structured pruning for VGG-16. The best results are shown in **bold**. Fig. 7: One-shot vs. iterative pruning on CIFAR-10. Shaded regions indicate standard deviation based on three independent runs (best view in color). and CIFAR-100 [156] with 50% or 90% parameters pruned, the data-driven methods outperform in most cases. Among these methods, SNIP performs best. Although it only uses a small number of randomly chosen samples (i.e., one sample per class) to calculate weight scores, the data is essential for SNIP. When it gets random inputs, as denoted by SNIP (data-free), its Top-1 accuracy has generally dropped. ### _Pruning on Initialized vs. Pretrained Weights_ Frankle et al. [48] find the subnetworks obtained by pruning on randomly initialized weights (such as SNIP [46], GraSP [61], SynFlow [39]) are robust to the ablation treatments (i.e., randomly shuffling the mask positions within each layer or reinitializing weights while keeping masks unchanged). To find the reason behind such immunity, Singh and Liu [160] use the Wasserstein distance to measure distributional similarity and find that the remained weights' distribution is changed minimally with these ablations, which reinforces keeping similar performances. In contrast, Su et al. [60] find the subnetworks achieved by pruning on pretrained weights, such as LTH [47], are sensitive to these ablations. Qiu and Suda [161] claim that training weights can be decoupled into two dimensions: the locations of weights and their exact values, among which the locations of weights hold most of the information encoded by the training. Wolfe et al. [162] theoretically analyze the impact of pretraining on the performance of a pruned subnetwork. Although pretraining is crucial for PAT methods, it does not always bring benefits. We conduct some experiments to explore whether the pretrained weights facilitate PBT methods to find better subnetworks. The results in Fig. 9 show that for both SynFlow [39] and SNIP [46], pruning on the pretrained weights does not guarantee improved Top-1 accuracy. The results are worse for some prune ratios of weights. ### _Training from Scratch vs. Fine-tuning_ After pruning, many pruning methods require training the subnetwork for several epochs to regain performance. Le and Hua [163] argue that retraining is essential to recover loss accuracy in pruning. Generally, retraining can be divided into two types: training from scratch or fine-tuning. There has been debate over whether fine-tuning is more powerful than training from scratch to recover accuracy. On the one hand, Liu et al. [38] find that for ResNet, VGG, and other standard structures on ImageNet, training the subnetworks with new random initialization can achieve better performance than fine-tuning them. On the other hand, Li et al. [69] observe that training a subnetwork from scratch performs worse than fine-tuning it. Liu et al. [120] investigate pruning ResNet20 on CIFAR-10 with ADMM-based [164] one-shot pruning method and find that pruning & fine-tuning outperforms LTH (pruning & training from scratch) over various prune ratios. In addition, the results in [129, 165] show that fine-tuning is necessary to achieve better performance on sparse mobile networks than training from scratch. In recent years, some compromise methods (such as weight rewinding [53]) have been proposed. The results in [53, 40] show that weight rewinding can achieve higher accuracy than fine-tuning. We prune ResNet-32 on CIFAR-32 by Magnitude and SNIP [46], and then train the pruned network from scratch or fine-tune it. The results in Fig. 10 show that fine-tuning outperforms training from scratch for Magnitude and SNIP. ### _Original Task vs. Transfer Pruning_ In recent literature, pruning is combined with transfer learning [166] that can dramatically improve accuracy and speed up convergence. For ease of distinction, in this survey, the original task pruning is used to denote the whole pruning pipeline directly performing the target task. In contrast, transfer pruning performs on the source task and then transfers the subnetwork to the target task. Specifically, transfer pruning is divided into two types: dataset transfer and architecture transfer. The former prunes networks on the source dataset and transfers the subnetwork to the target dataset, and the latter prunes on one architecture and transfers the subnetwork to another. Some works ([110, 123, 167, 168]) study the transferability of sparsity masks across datasets. For example, Tiwari Fig. 8: An illustration of the architectures of VGG-16 with 90% prune ratio of weights through data-free and data-driven pruning on CIFAR-10 and SVHN. \begin{table} \begin{tabular}{l|c|c|c|c|c|c} \hline Dataset & \multicolumn{2}{c|}{CIFAR-10} & \multicolumn{2}{c|}{SVHN} & \multicolumn{2}{c}{CIFAR-100} \\ \hline Parameters \(\downarrow\) (\%) & 50 & 90 & 50 & 90 & 90 & 95 \\ \hline Smart-Ratio [60] & 93.71 & 93.20 & 96.34 & 96.23 & 71.37 & 70.16 \\ SynFlow [39] & 93.94 & 93.26 & 96.28 & 96.34 & 71.03 & 69.16 \\ SNIP (data-free) & **93.90** & 93.20 & 96.37 & 96.29 & 71.46 & 70.23 \\ \hline SNIP [46] & 93.70 & **93.40** & **96.39** & **96.60** & **71.65** & 70.32 \\ Magnitude & 93.65 & 93.18 & 96.23 & 96.26 & 71.15 & **70.35** \\ \hline \end{tabular} \end{table} TABLE VIII: Top-1 accuracy (%) of data-free and data-driven pruning methods for VGG-16. The original Top-1 accuracy on CIFAR-10, SVHN, and CIFAR-100 are 93.76%, 96.36%, and 73.22%, respectively. The best results are shown in **bold**. Fig. 9: Initialized vs. pretrained weights on CIFAR-10. Shaded regions indicate standard deviation based on three independent runs (best view in color). et al. [123] compare the Top-1 accuracy of the pruned network on CIFAR-100 with the one wherein the masks are learned on Tiny ImageNet and transferred to CIFAR-100. The results show that the transferred masks perform better than those directly obtained from the original task, with 40% of the channels removed. S. Morcos et al. [109] observe that for image classification, winning tickets generated on larger datasets (such as bigger training set size and/or more number of classes) consistently transferred better than those generated with smaller datasets. For example, winning tickets generated on ImageNet and Places365 demonstrate better performance across other smaller target datasets such as CIFAR-10 and CIFAR-100. Iofirova et al. [169] present a pioneer study of the transfer performance of subnetworks and find that pruning methods with similar Top-1 accuracy on ImageNet [1] can have surprisingly different Top-1 accuracy when used for transfer learning. For architecture transfer pruning, Elastic Ticket Transformations (**ETTs**) [42] transforms winning tickets found in one kind of network (ResNet [6], or VGG [2]) to another deeper or shallower one from the same model family. ### _Static vs. Dynamic Pruning_ Static pruning [12] uses static pruning criteria and permanently removes components. In contrast, dynamic pruning ([135, 136, 51, 170]) exploits input-specific characteristic pruning criteria and preserves the entire network structures and accelerates the networks by dynamically skipping unimportant components. However, dynamic pruning generally does not perform run-time fine-tuning or retraining. The difference between static and dynamic pruning is mainly reflected in the pruning criteria and the pruned model. The advantages and disadvantages of static and dynamic pruning are shown in Table IX. ### _Layer-wise Weight Density Analysis_ Some works ([119, 154, 171, 71]) study the distributions of layer-wise weight density of a subnetwork, and their results show that different layers can have very different weight densities. The difference is produced by the joint action of structural characteristics of the dense network and the pruning methods. Zhang et al. [172] empirically study the heterogeneous characteristic of layers and divide the layers into either "ambient" or "critical". The ambient layers are not sensitive to changing weights to the initial values, while critical layers are. It seems that the ambient layers should be pruned heavily, and the corresponding weight densities will be lower. Pruning methods also can cause different weight densities. Take pruning for image classification as an example. Some pruning methods tend to assign more weights to earlier layers than later ones. For example, Ma et al. [119] investigate the layer-wise keep-ratios of the subnetworks obtained by GraSP, SNIP [46], LTH on VGG and ResNet, and observe the common trend of declining in layer-wise keep-ratios except for some special layers (such as the downsampling layers in ResNet). In contrast, Liu et al. [71] find their pruned networks keep higher percentages of channels in the deeper layers than those in the lower layers for image classification. The results in [171] show that global magnitude pruning tends to prune layers of Transformer uniformly [173], while global first-order methods heavily prune the deeper layers. ### _Pruning with Different Levels of Supervision_ In descending order of supervision level during neural network pruning, pruning can be divided into supervised, semi-supervised, self-supervised, and unsupervised pruning [174]. Self-supervised learning can be divided into two classes: generative or contrastive learning [175]. Like supervised learning, supervised pruning works on fully labeled datasets. Most of the current pruning methods fall into supervised pruning. However, supervised pruning suffers from similar bottlenecks as supervised learning (such as expensive manual labeling). As a promising alternative, semi-supervised, self-supervised, and unsupervised pruning have drawn massive attention 2. Footnote 2: The differences between supervised, semi-supervised, unsupervised, self-supervised learning refer to [175]. For example, Caron et al. [176] observe the different results in self-supervision pruning from in supervision pruning, where winning tickets initialization only introduce a slight performance improvement compared to random re-initialization. Pan et al. [177] claim that unsupervised pruning usually fails to preserve the accuracy of the original model. Notably, label supervision for network pruning and training can be independent. For example, Chen et al. [168] use supervised pruning method **IMP** (i.e., Iterative Magnitude Pruning) to explore the subnetworks of self-supervised pretrained models (simCLR [178] and MoCo [179]) on ImageNet. Similarly, Jeff Lai et al. [180] exploit the supervised pruning method IMP to prune self-supervised speech recognition models. ## 8 Fusion of Pruning and other Compression Techniques In this section, we provide a review of the fusion of neural network pruning with other network compression techniques, such as quantization [11], tensor decomposition Fig. 10: Training from scratch vs. fine-tuning for ResNet-32. Shaded regions indicate standard deviation based on three independent runs (best view in color). \begin{table} \begin{tabular}{l|c c} \hline \hline Type & Advantages & Disadvantages \\ \hline Static Pruning & model size reduced & fixed subnetwork \\ \hline Dynamic Pruning & flexible subnetwork & model size unreduced \\ \hline \hline \end{tabular} \end{table} TABLE IX: Advantages and disadvantages of static and dynamic pruning. [144], knowledge distillation [21], and network architecture search [73]. However, on the one hand, fusion provides more choices for network compression. On the other hand, the combined compression techniques can complement each other to improve the performance and prune ratio further. **Pruning & Quantization:** Quantization [147] is a compression technique to reduce the number of bits used to represent the network weights and/or activations, which can significantly reduce the model size and memory footprint but with a minor performance drop. To obtain more compacted models as well as model acceleration, Han et al. [11] pioneer to prune the redundant network connections and quantize the weights. CLIP-Q [147] jointly perform pruning and quantization during the fine-tuning stage. MPTs [108] integrates pruning and quantizing randomly weighted full-precision neural networks to obtain binary weights and/or activations. EB [130] applies 8-bit low-precision training to the stage of searching EB tickets. **Pruning & Tensor Decomposition:** Tensor decomposition [19] decomposes the convolutions into a sequence of tensors with fewer parameters. In contrast to pruning, it explores the original weights' low-rank structure, keeping the dimension of the convolutional output unchanged. CC [144] combines channel pruning and tensor decomposition to compress CNN models by simultaneously learning the model sparsity and low rankness. Hinge [181] introduces group sparsity to fuse filter pruning and decomposition under the same formulation. **Pruning & NAS:** Neural Architecture Search (**NAS**) provides a mechanism to automatically discover the best architecture for the problem of interest, which provides a new idea for pruning to find suitable network depth and width. NPAS [73] performs a compiler-aware joint network pruning and architecture search, determining the filter type (different kernel sizes), the pruning scheme, and the rate for each layer. TAS [182] exploits NAS to search for the depth and width of a network to obtain the pruned networks and uses knowledge distillation to train these pruned networks. **Pruning & Knowledge Distillation:** Knowledge Distillation (**KD**) [21] guides the student to effectively inherit knowledge from the teacher and mimic the output of the teacher. Some works ([183, 184]) exploit pruning before KD to boost the KD quality. For example, Liu et al. [183] prune unimportant channels to the contents of interest and focus the distillation on the interest regions. Park and No [184] prune the teacher network first to make it more transferable and then distill it to the student. Some works ([185, 66, 135]) use KD to train the pruned networks. The results in [185] show that the pruned network recovered by KD performs better than it regained by fine-tuning. Zou et al. [186] propose a data-free deraining model compression method that distills the pruned model to fit the pretrained model. **Pruning & Multi-compression Techniques:** Some works ([187, 188]) explore the fusion of pruning with more than one compression technique. For example, GS [189] fuses pruning, quantization, and KD for Generative Adversarial Networks (**GANs**) compression. Joint-DetNAS [188] joins pruning, NAS, and KD for image translation. LadaBERT [187] integrates pruning, matrix factorization, and KD to compress Bidirectional Encoder Representations from Transformers (**BERTs**) [132] for natural language understanding. ## 9 Suggestions and Future Directions In this section, we discuss how to choose different pruning methods and provide promising directions for future work. ### _Recommendations on pruning method selection_ After years of research and exploration, there are many off-the-shelf pruning methods. However, no golden standard exists to measure which one is the best. Different suitable pruning methods exist to compact deep neural networks to the specific application requirements and the hardware and software resources. Here are some general recommendations for choosing an appropriate pruning method. (1) If you do not have special hardware (e.g., FPGAs or ASICs) or software (such as sparsity convolutional libraries) but need actual neural network acceleration and compression, structured pruning is more suitable than unstructured pruning because most software frameworks and hardware cannot accelerate sparse matrices' computation. (2) If you have enough computational resources in the pruning stage, iterative PAT methods may be considered. Overall, this class of methods can minimize the impact on performance under the same prune ratio. On the other hand, if you have limited computational resources in both the pruning and inference stages, one-shot PBT or one-shot post-training pruning methods may be considered. (3) If you have enough labeled examples on the target task, supervised pruning methods may be considered. However, if only a few examples on the target task are labeled, semi-supervised or transfer pruning methods may be considered. If the examples on the target task are not labeled, self-supervised, unsupervised, or transfer pruning methods may be considered. (4) If you have enough memory footprint during pruning for NLP tasks, heavily compressing large models can be considered rather than lightly compressing smaller models to meet the same budgets. Some results in [190] show that for NLP tasks finding pruned models from large dense networks outperform small dense networks with a size comparable to pruned models. (5) If you have enough memory footprint to store the dense neural network in the inference stage and hope to provide run-time flexible computational cost allocation for different inputs, dynamic pruning methods can be considered where inputs with smaller shapes can allocate less computational cost to perform the task and if the input shape is bigger more computational cost can be allocated. (6) If you need to trim down neural networks in multiple dimensions, you can comprehensively consider layerwise pruning (decreasing the model's depth), channel pruning (reducing the model's width), and image resolution pruning (scaling down the model's input resolution). In addition, pruning can be integrated with quantization to further reduce the memory footprint and the neural networks' size. (7) If you want to reach a better tradeoff between speed and accuracy, the following settings may help: use a pre-trained model; set a more appropriate learning rate (if any) in both the pruning and the retraining stages; fine-tune the pruned models for several epochs; integrate pruning, knowledge distillation, NAS or other compression methods to achieve complementarity; adversarial training may have some help [111]. (8) If you need to train a subnetwork to recover loss accuracy, the results in [119] show that when residual connections exist, the subnetwork achieves higher accuracy at a relatively small learning rate. In contrast, a larger learning rate is preferable in training a subnetwork without residual connections. ### _Future Directions_ We discuss four promising directions for the further development of neural network pruning, namely, (1) theories, (2) techniques, (3) applications, and (4) evaluation. **Theories:** Despite the existing works, several fundamental questions about pruning still need to be answered. For example, prior works demonstrate that network layers contain irreplaceable information as long as redundant ones. Does a theoretical upper bound of the prune ratio exist for a given network that still keeps the matching performance of its dense equivalent? In other words, how heavily can a network be pruned theoretically without accuracy loss? It is a tricky question because of the intricate relationships between network layers. Besides, is pruning explainable? A common belief is deep neural network is hard to interpret. As such, making explainable pruning is an uphill task. However, the interpretability of pruning is vital for understanding the factors behind pruning (e.g., model structure and weights) and exploring more effective pruning methods. **Techniques:** To obtain better algorithm designs whose architectures are learned in an economical, efficient, and effective manner, it is a trend to extend Automated Machine Learning (**AutoML**) methods and NAS to pruning. Furthermore, pruning also begins to combine with various learning contexts, such as lifelong learning [66], continual learning [191], contrast learning [32], federated learning [192], etc. In addition, networks' rising energy consumption requires more attention to energy-aware pruning. However, preliminary efforts mainly focus on reducing computation and memory costs, which may not necessarily reduces the most energy consumption. Besides, incorporating pruning into the hardware to help deploy pruned networks is also an emerging trend. For example, Sui et al. [54] propose a hardware-friendly pruning method and deploy the pruned models on the FPGA platform. **Applications:** The prior mainstream research targets pruning studies in CV, especially in image classification. Recently, pruning has begun to draw attention to more complex applications, like object tracking, visual question answering, natural language understanding, speech recognition, etc. For example, in recent years, foundation models such as GPT-4 [193] might be the possible way to Artificial General Intelligence (**AGI**). However, its huge model hinders its application in many downstream tasks. Therefore, colossal foundation models can benefit from pruning research to be more compact and efficient [15]. **Evaluation:** With the emergence of many pruning methods, standardized benchmarks and metrics are required to provide a fair evaluation. Different pruning techniques, network architectures, tasks, and experimental settings lead to incomparable results and make it hard to compare pruning methods fairly [194]. ShrinkBench [37] takes the first step and provides a benchmark of pruning methods for image classification. As pruning is applied to applications other than image classification, standardized benchmarks and metrics for other applications are needed. ## 10 Conclusion As an essential compression technique, deep neural network pruning has attracted increasing research attention with the recent emergence of a wide variety of pruning methods and applications. This survey conducts a comprehensive review on the following four scopes: 1) universal/specific speedup, with a systematic review from unstructured, structured, and semi-structured pruning; 2) when to prune, including pruning before/during/after training for static pruning and run-time pruning; 3) how to prune, including pruning by heuristic criteria and by learning; 4) fusion of pruning with other compression techniques, such as KD, NAS, so on. A comprehensive comparative analysis, including seven pairs of contrast settings for pruning, layer-wise weight density, and different supervision levels, can help researchers to efficiently and effectively grasp the characteristics of different pruning methods. Additionally, recommendations on pruning method selection and future research directions are highlighted and discussed. To facilitate future research, real-world miscellaneous applications and commonly used resources of datasets, networks, and evaluation metrics in different applications are summarized in Appendix B. To help researchers and practitioners keep up with the development of pruning technologies, we continue updating the representative research efforts and open-source codes for pruning at [https://github.com/hrcheng1066/awesome-pruning](https://github.com/hrcheng1066/awesome-pruning).
2304.05805
GDP nowcasting with artificial neural networks: How much does long-term memory matter?
We apply artificial neural networks (ANNs) to nowcast quarterly GDP growth for the U.S. economy. Using the monthly FRED-MD database, we compare the nowcasting performance of five different ANN architectures: the multilayer perceptron (MLP), the one-dimensional convolutional neural network (1D CNN), the Elman recurrent neural network (RNN), the long short-term memory network (LSTM), and the gated recurrent unit (GRU). The empirical analysis presents results from two distinctively different evaluation periods. The first (2012:Q1 -- 2019:Q4) is characterized by balanced economic growth, while the second (2012:Q1 -- 2022:Q4) also includes periods of the COVID-19 recession. According to our results, longer input sequences result in more accurate nowcasts in periods of balanced economic growth. However, this effect ceases above a relatively low threshold value of around six quarters (eighteen months). During periods of economic turbulence (e.g., during the COVID-19 recession), longer input sequences do not help the models' predictive performance; instead, they seem to weaken their generalization capability. Combined results from the two evaluation periods indicate that architectural features enabling long-term memory do not result in more accurate nowcasts. Comparing network architectures, the 1D CNN has proved to be a highly suitable model for GDP nowcasting. The network has shown good nowcasting performance among the competitors during the first evaluation period and achieved the overall best accuracy during the second evaluation period. Consequently, first in the literature, we propose the application of the 1D CNN for economic nowcasting.
Kristóf Németh, Dániel Hadházi
2023-04-12T12:29:58Z
http://arxiv.org/abs/2304.05805v3
# GDP nowcasting with artificial neural networks: How much does long-term memory matter? ###### Abstract In our study, we apply different statistical models to nowcast quarterly GDP growth for the US economy. Using the monthly FRED-MD database, we compare the nowcasting performance of the dynamic factor model (DFM) and four artificial neural networks (ANNs): the multilayer perceptron (MLP), the one-dimensional convolutional neural network (1D CNN), the long short-term memory network (LSTM), and the gated recurrent unit (GRU). The empirical analysis presents the results from two distinctively different evaluation periods. The first (2010:Q1 - 2019:Q4) is characterized by balanced economic growth, while the second (2010:Q1 - 2022:Q3) also includes periods of the COVID-19 recession. According to our results, longer input sequences result in more accurate nowcasts in periods of balanced economic growth. However, this effect ceases above a relatively low threshold value of around six quarters (eighteen months). During periods of economic turbulence (e.g., during the COVID-19 recession), longer training sequences do not help the models' predictive performance; instead, they seem to weaken their generalization capability. Our results show that 1D CNN, with the same parameters, generates accurate nowcasts in both of our evaluation periods. Consequently, first in the literature, we propose the use of this specific neural network architecture for economic nowcasting. _Keywords_: GDP nowcasting, Artificial neural networks, 1D CNN, Long-term memory Journal of Economic Literature (JEL) codes: C45, C53, C51 ## 1 Introduction Gross domestic product (GDP) is the market value of all final goods and services made within a country during a specific period. GDP is arguably the most important flow-type monetary measure of economic activity over a given period. GDP is typically calculated on an annual basis, but in most market economies it is also measured on a quarterly frequency. Considering its relevance, the availability and reliability of these quarterly data are of great significance. However, due to the time required for data collection and statistical data processing, statistical offices are delayed in releasing GDP data for the current quarter. The first measurements are usually available only a few months after the end of the current quarter, which makes it difficult to assess economic activity in real-time (i.e., synchronously). Therefore, many decision makers (such as central banks, budget offices, etc.) rely on the current quarter forecast, that is, the nowcast of GDP growth for more informed policy making. This underscores the need for accurate nowcasts. In nowcasting current quarter GDP growth, one typically tries to extract the informational content of higher frequency monthly data to track the real-time development of economic activity. Such an analysis faces the following three problems (Giannone et al., 2008): (i) Combining monthly predictor variables and a quarterly target variable. (ii) Handling a large number of potential regressors. (iii) Monthly data are released at different times (unsynchronized) within a quarter. This leads to the so-called _"ragged edge"_ problem, where some monthly features may have missing values, usually at the end of the sample period (Wallis, 1986). In our study, we apply different statistical models to nowcast the quarterly U.S. GDP growth of the current quarter. Using the monthly FRED-MD database, we measure the nowcasting performance of the dynamic factor model (DFM) and four different artificial neural networks (ANNs) relative a naive constant growth model. These methods are similar in that they all try to meet the above-mentioned challenges of nowcasting. However, the models have a different structure. As far as classical statistical modeling goes, DFM is widely considered as the state-of-the-art modeling framework. In the course of the empirical analysis, we adopt four different ANN architectures: the multilayer perceptron (MLP), the one-dimensional convolutional neural network (1D CNN), the long short-term memory network (LSTM), and the gated recurrent unit (GRU). Our results indicate that some ANNs can outperform the dynamic factor model in terms of out-of-sample nowcasting performance, while others cannot. The first main contribution of our study is that it proposes the utilization of a neural network architecture that has not yet been applied for economic nowcasting, namely the one-dimensional convolutional neural network (hereinafter, 1D CNN). Our results suggest that the 1D CNN could be a highly suitable architecture for GDP nowcasting as it generates accurate nowcasts for both evaluation periods, i.e., both during a balanced growth period and in times of high economic turbulence. While this ANN architecture has been neglected compared to MLP and the more modern gated RNNs, we argue that it represents a _"sweet spot"_ for this type of analysis in many aspects. In contrast to the MLP, 1D CNN has an intrinsic architectural constraint that usefully limits the hypothesis space, i.e., the range of mappings the network can learn during the training process. During training, the network learns the coefficients of different finite impulse response filters, so it can only learn time-invariant (translation-invariant) mappings. Intuitively, the network performs a series of hierarchical pattern recognition tasks where the result is time-invariant with respect to the relative position of those patterns (Goodfellow et al., 2016). It is worth noting that the DFM, and the majority of the traditional time series approaches are also built around this assumption; namely, the conditional distribution of the target variable only depends on time through the regressors (predictors). Consequently, it seems especially advantageous to narrow the hypothesis space to this type of mappings. Unlike the MLP, 1D CNN is trained with input sequences, reflecting the architecture's temporal "awareness". In this regard, MLP is the exception here: While we can form "training sequences" by hand, the MLP does not recognize the natural temporal ordering in the data. Thus, training of the MLP cannot make use of this type of regularity either. Compared to the other three networks investigated in this paper, MLP is a simple, time-agnostic architecture which is not tolerant to shifts (translations) in time (Ekman, 2021; Goodfellow et al., 2016). In our study, we investigate two types of gated RNNs: the long short-term memory network (LSTM) and the gated recurrent unit (GRU). Both of these architectures also reflect an explicit temporal aspect, i.e. they are trained with input sequences, and possess a time-invariant property as well. In fact, they are more flexible and complex compared to the 1D CNN: They can be trained with much longer and even variable-length input sequences. This type of flexibility and complexity comes at a cost however, since gated RNNs have much more trainable parameters than 1D CNNs - even in their simplest form (Ekman, 2021; Goodfellow et al., 2016). The results from the second evaluation period indicate that this trade-off clearly favors the 1D CNN: Its more restricted architecture results in a smaller hypothesis space and ultimately more accurate nowcasts during sharp changes in economic growth. The second main contribution of the paper is that it presents the results of a nowcasting competition focusing on the performance of different ANN architectures. We believe that the results from two distinctively different evaluation periods provide a better understanding of the underlying data-generating process. The major novelty of gated RNNs is that they introduce a so-called _gating mechanism_ (practically, element-wise multiplication) that enables the network to develop long-term memory. This feature helps to overcome the vanishing gradient problem of the vanilla RNNs, making them a much more viable option for modeling time series with path-dependent behavior i.e., with long-term memory (Chung et al., 2014, Hochreiter and Schmidhuber, 1997). Financial time series, such as stock prices or foreign exchange rates, generally show characteristics of path-dependency (e.g., a slowly decaying autocovariance function). Here, it can easily happen that the current value of the exchange rate is affected (supported) by a distant technical level whose effect, however, is no longer reflected in any nearby values. As a result, this old technical level should be remembered by the network in a predictive exercise. We try to answer, how important long-term memory is in modeling GDP growth? If the unobserved data generation process of GDP growth was actually path-dependent, than that would speak for the use of gated RNNs in almost any predictive scenario. Due to the gating mechanism, their architecture supports the modeling of path-dependent (long-term memory) processes much better than the MLP or the 1D CNN. The first evaluation period ranges from 2010:Q1 to 2019:Q4, so it ends before the economic consequences of the COVID-19 pandemic would hit the economy. The results for this period suggest that economic growth can be better modeled in normal times based on longer input sequences and more refined network architectures. While gated RNNs provide the most accurate nowcasts for this period, 1D CNN comes close in terms of both RMSE and MAE evaluation. Our second evaluation period is from 2010:Q1 to 2022:Q3, so it also includes the COVID-19 crisis. Under such circumstances, MLP comes out on top with its simple time-agnostic architecture. According to the results, shorter input sequences generally result in more accurate nowcasts. Here we see again that 1D CNN with eight-month-long sequences comes close to the best performing model in terms of both RMSE and MAE. This time, however, architectural complexity does not help the gated RNNs' nowcasting performance in any meaningful way. Combined results from the two evaluation periods show that longer input sequences do not improve our models' predictive accuracy. That is especially interesting to see in the case of the LSTM and the GRU: While their architectural design enables them to handle long input sequences, forming a long-term memory, even these networks tend to have better accuracy with shorter sequences. Considering the results from the two test periods as a whole, GDP growth could be approximated as a well-behaved ergodic time series - at least for prediction purposes. The remainder of the paper is structured as follows: Section 2 briefly summarizes the related literature on the topic. Section 3 presents the different models applied in the empirical analysis, i.e., the dynamic factor model and the four different neural network architectures mentioned above. Section 4 describes the data behind the analysis and exposes the nowcasting exercise. Then, it presents the results of the empirical analysis. Finally, Section 5 concludes. Related works Giannone et al., 2008 combine a dynamic factor model and the Kalman filter to nowcast the quarterly GDP growth for the US economy. Their two-step approach addresses all three problems of nowcasting mentioned before: it deals with the mixed frequency issue of combining monthly predictor variables and quarterly GDP, it can handle a large number of potential predictor variables, and it can cope with the ragged edge problem of the underlying data. Additionally, it has the potential to capture the essential dynamics of the time series of the panel. After the seminal work of Giannone et al., 2008, DFMs have been found particularly successful at addressing many of the data issues inherent in nowcasting, and have been applied in many empirical studies (Stock & Watson, 2002). Matheson, 2014 develop monthly indicators for tracking short-run trends in real GDP growth and conduct nowcasting analysis for 32 advanced and emerging-market economies. Marcellino and Schumacher, 2010 conducts nowcasting analyis for the German economic activity, while Chernis and Sekkel, 2017 perform a similar analysis for the Canadian GDP growth. The fundamental idea of DFMs is that one or more latent factors dictates the movement of many different variables, each with an idiosyncratic component in relation to the factor(s). With historical data, the factor(s) can be estimated from the variables. Subsequently, even in future periods where not all data are complete, the factor(s) can still be estimated and used to generate forecasts for variables that are not yet published, as each variable's relation to the factor(s) has already been estimated. The theory behind the two-step estimator is derived in Doz et al., 2011. Artificial neural networks (ANNs) have been the catalyst to numerous advances in a variety of fields and disciplines in recent years. Their impact on economics, however, has been comparatively muted. While only a few study of nowcasting has applied ANNs, several other studies have applied neural networks to forecast macroeconomic and financial variables. For example, Tkacz, 2001 uses neural networks to forecast the Canadian GDP growth rate between 1989 and 1992 by applying lagged GDP growth and several other financial variables, such as yield spreads and monetary aggregates. While Tkacz, 2001 uses quarterly data to forecast Canadian GDP by using ANNs, Heravi et al., 2004 apply ANNs to forecast monthly industrial production between 1978 and 1995 for the three largest European economies, with data provided by Eurostat. In contrast to Tkacz, 2001, they only use the information contained in the lagged values of monthly year-on-year growth of industrial production. Besides these studies, ANNs have also been used in financial forecasting. For instance, Kuan and Liu, 1995 investigate the forecasting ability of ANNs and recurrent ANNs for daily exchange rates of five major currencies between 1980 and 1985. More recently, Torres and Qiu, 2018 apply recurrent neural networks to daily data of several crypto-currencies, exchange rates, commodities and stocks between 2013 and 2017. Results of Loermann and Maas, 2019 indicate that the MLP outperforms the dynamic factor model in terms of now- and forecasting accuracy, while it generates at least as good now- and forecasts as the Survey of Professional Forecasters. Compared to Loermann and Maas, 2019, Hopp, 2021 investigates a more complex recurrent network architecture, namely the long short-term memory network. The paper shows that LSTM networks produce more accurate nowcasts compared with DFMs on three different target series: global merchandise export values and volumes, and global services exports. In addition to better empirical performance for the three target series, LSTMs provide advantages over DFMs by being able to handle large numbers of features without computational bottlenecks and the ability to use any mixture of frequencies in features or target. Disadvantages include the stochastic nature of the parameter estimation and the lack of interpretability in their coefficients (Hopp, 2021). These advantages and disadvantages emerge at a more general level as well, in the comparison of the traditional time series approaches and the artificial neural networks (Goodfellow et al., 2016). ## 3 Models and methods ### Dynamic factor model The dynamic factor model (hereinafter, DFM) is a state space model whose main characteristic is that the observation vector is much larger in dimension than the vector of the unobserved (latent) common factors. The general specification of the DFM can be written as follows: \[y_{t} =\Lambda f_{t}+Bx_{t}+u_{t}\] \[f_{t} =A_{1}f_{t-1}+\cdots+A_{p}f_{t-p}+\eta_{t}\qquad\eta_{t}\sim N(0,I)\] \[u_{t} =C_{1}u_{t-1}+\cdots+C_{q}u_{t-q}+\varepsilon_{t}\qquad \varepsilon_{t}\sim N(0,\Sigma)\] where \(y_{t}\) are observed data, \(f_{t}\) are the unobserved factors (evolving as a vector autoregression), \(x_{t}\) are (optional) exogenous variables, and \(u_{t}\) is the error, or "idiosyncratic" process (\(u_{t}\) is also optionally allowed to be autocorrelated). The \(\Lambda\) matrix is also referred here to as the matrix of _factor loadings_. The variance of the factor error term is set to the identity matrix to ensure identification of the unobserved factors. The size of the observation vector is typically large while the dimension of the state vector is small so we have \(p>>m\)(Durbin & Koopman, 2012). This model can be cast into state space form, and the unobserved factor estimated via the Kalman filter. The likelihood can be evaluated as a byproduct of the filtering recursions, and maximum likelihood estimation used to estimate the parameters. The (log)likelihood function of the unknown parameters can be formulated as follows (Harvey, 1990): \[\log L(Y_{n})=-\frac{np}{2}\log 2\pi-\frac{1}{2}\sum_{t=1}^{n}\log|\mathbf{F_{t} }|-\frac{1}{2}\sum_{t=1}^{n}\nu_{\mathbf{t}}^{\prime}\mathbf{F_{t}^{-1}}\nu_{ \mathbf{t}} \tag{1}\] where \(p\) denotes the dimension of the observation vector \(y_{t}\). The quantities \(\nu_{t}\) and \(F_{t}\) are calculated routinely by the Kalman filter, thus \(\log L(Y_{n})\) is easily computed from the Kalman filter output. We assume that \(F_{t}\) is non-singular for \(t=1,...,n\). If this condition is not satisfied initially it is usually possible to redefine the model so that it is satisfied. The representation (1) of the log-likelihood was first given by Schweppe, 1965. Harvey, 1990 refers to it as the _prediction error decomposition_. The dynamic factor model described above has long been considered the state-of-the-art statistical modeling framework for economic nowcasting. This modeling framework compresses information from a large dataset into a few underlying factors, while at the same time applying Kalman-filtering techniques to fill up the missing data of the ragged edge within the dataframe. Although this approach provides a unified framework incorporating dynamic imputation (model-based interpolation) and nowcasting, the central predictor equation remains linear, potentially restricting the model from generalizing to non-linear patterns (Bartholomew et al., 2011). ### Artificial neural networks Artificial neural networks (hereafter, ANNs) are flexible nonlinear (universal) estimators which represent the set of alternatives to the benchmark factor model examined in this paper. Similarly to most machine learning algorithms, ANNs can be used for classification problems, predictive exercises where the target variable is categorical, and also for regression function estimation. One of the biggest strengths of ANNs is that they can handle the curse of dimensionality in an _automated_ way, much more naturally than traditional time series models. The latter set of models require the preparatory use of a dimension reduction method (e.g., PCA) or an unobserved component model for feature extraction, where the number of potential explanatory variables is large. For example, PCA can give us an optimal lower dimensional representation of the data in the sense that it changes the basis to the direction of maximum variance. However, we cannot be sure if there is no more relevant lower-dimensional representation of the features for the prediction of our target variable. Similarly, when we extract common factors from the input data, the procedure should be driven heavily by our a priori knowledge (choice): We should have a relatively concrete idea about the potentially relevant explanatory variables (features). After the set of observable indicators have been defined, method of explanatory factor analysis extracts common factors in such a way that they can explain the co-movements, i.e., the co-variance structure of our features best. Here we see again that feature extraction is somewhat separated from the essential modeling task. Hence, it is not surprising that DFM-based GDP nowcasting is referred to as a two-staged estimation procedure in the literature (Giannone et al., 2008). By contrast, ANNs, can, in principle at least, learn the relevant feature representation by themselves. The demand to connect the feature extraction with the actual predictive modeling task arises naturally and justifiably. Here is where artificial neural networks perform really well because they are inherently capable of learning the relevant representation of the features for the prediction of the target variable.1 Footnote 1: We should note that this kind of _connected_ feature extraction (with some limitations) can be conducted with statistical models as well, but traditional statistical models are clearly more limited in this regard. This is not to say however, that ANNs are generally superior modeling frameworks compared to traditional linear models. While ANNs handle the _curse of dimensionality_ more easily, they can perform worse in other areas. For example, they require a much more sophisticated data pre-processing step where we must deal with missing observations as well. One possible solution to fill up missing values is applying univariate ARMA(p,q) forecasts for each single input series. In this case, the lag lengths of the individual ARMA(p,q) models can be selected based on the value of Akaike or Schwarz information criterion (Greene, 2017, Loermann and Maas, 2019). Although missing data issue for ANNs can be solved in many ways, state space models handle this problem by design. If we think about the three big challenges of nowcasting mentioned in the introduction, we can say that mixed-frequency data can be treated relatively well in both modeling frameworks. Compared with the DFM, proper construction of our training and test samples with mixed-frequency data may require some additional effort. More generally, we should also mention that even the smallest ANNs have much more parameters than a typical statistical model. The large number of trainable (_free_) parameters results in a relatively large hypothesis space. From the bias-variance trade-off follows that with a larger hypothesis space, it is more likely to find a hypothesis which fits the training data very well. This phenomenon is called overfitting, and it happens when a model learns the fine details and noise in the training data rather than the actual **systematic** relationship between the regressors and the target variable(s). Overfitting can substantially weaken a statistical model's generalization capability, and ANNs are substantially more prone to overfitting compared to the traditional time series models. So far, we tried to summarize the most important characteristics of ANNs as one of our nowcasting machines. In the following sections, we investigate those architectures in more detail that were adopted in the empirical analysis. #### 3.2.1 Multilayer perceptron While a single Rosenblatt perceptron can be used as a linear classifier, its straightforward extension, the multilayer perceptron (MLP) with non-linear activation functions, can perform non-linear classification and regression tasks as well.2. This neural network is one of the simplest examples of a fully connected feedforward network. Footnote 2: Hereafter, we refer to a perceptron as a neuron because the perceptron is just a special type of neuron (just like the Adaline for example), and we prefer the more generic name _neuron_ According to Figure 1, the MLP's input-output mapping - if we assume the same non-linearity in each layer - is as follows: \[\mathbf{y}=f\left(\mathbf{w}^{L}f\left(\mathbf{w}^{L-1}f\left(\mathbf{w}^{L-2} \ldots f\left(\mathbf{w}^{1}\mathbf{x}\right)\right)\right)\right) \tag{2}\] where \(\mathbf{w}^{L}\) is the matrix combining the weight vectors of the neurons in the \(l\)-th layer, and \(f(.)\) denotes the activation functions (sigmoid) applied to the outputs of the neurons belonging to the same layer. An MLP, even in its simplest form when it contains one hidden layer, implements a non-linear mapping on its parameters. As equation (2) suggests each hidden layer of an MLP Figure 1: Multilayer perceptron. can learn an arbitrary affine transformations of its inputs.3 As we will see below, this kind of universality will also affect the generalization capability of the network. Footnote 3: An affine transformation is the combination of linear transformation with translations. Translation can be learned through the bias.) While MLPs can be used in time series forecasting, we should see that its architecture lacks any explicit temporal aspect. As long as any hidden layer can learn an arbitrary affine transformation of its inputs, the size of the hypothesis space can be even too large for our purposes. Notwithstanding that MLPs can learn time-invariant mappings between their inputs and outputs, their inner (hidden) structure is not invariant to shifts (translations) in time. A more fitting feedforward architecture for time series prediction can be the time-delay neural network, or in other words, the one-dimensional convolutional neural network (1D CNN). #### 3.2.2 1D Convolutional network Convolutional Neural Networks (CNNs), similarly to MLPs, are also feedforward neural networks that consist of convolutional and pooling (subsampling) layers. 2D CNNs have become the standard for various computer vision tasks in the last decade. As the field of application of 2D CNNs has constantly broadened, 1D CNNs have also received growing attention. 1D CNNs have recently been proposed and achieved state-of-the-art performance levels in several applications, such as biomedical data classification, anomaly detection, and structural health monitoring (Kiranyaz et al., 2021). Nevertheless, we have not yet seen any application in the literature which is specifically related to economic nowcasting or forecasting. In the following, we try to argue that this type of empirical exercise possesses characteristics that render the application of 1D CNNs a suitable choice. First, we want to find a time-invariant mapping between our features and our target variable. Intuitively, this means that the same feature vector should have the same response in the target variable, even if it is shifted in time - assuming steady state. While MLPs can also learn time-invariant mappings, their intrinsic architecture, which favors flexibility, does not enforce this type of restricted learning. Since 1D CNNs, in their convolutional layers, learn the coefficients of multiple finite impulse response filters, they can only learn time-invariant mappings by definition. In other words, the network's architecture intrinsically restricts the hypothesis space to the composition of time-invariant mappings, which we supposedly want to find in the nowcasting analysis of a stationary time series. Figure 2 below shows a simple example of single channel 1D convolution, where the input sequence size is 7 and the filter (kernel) size is 3. Figure 2, shows that a 1D CNN practically realizes finite impulse response filters on its inputs, where filter coefficients are estimated during the training process. Based on this simple example, we can also see that unlike MLPs, 1D CNNs are trained with sequential data where the network receives a fixed size input sequence in each \(t\) time step. Obviously, in more complex cases we can have multiple input series (features) and multiple output channels as well. Figure 3 below illustrates a case where we have 4 input features (i.e., the input depth is 4), a filter the size (length) of which is 5, and 4 output channels (i.e., the output depth is 4). As Figure 3 suggests, in a convolutional layer, we will have a separate filter corresponding to each channel of the feature map. Summarizing the above, the inclusion of 1D CNN layers enables the network to learn its own internal representation of sequential (time series) data. Hence, 1D CNNs are trained with sequences where time series data are split into fixed-sized windows (sequences). Since their architecture represents a feedforward network, similar to the MLP, only the data points inside that window (input sequence related to time \(t\)) can affect the outcome at time \(t\). Recurrent neural networks (hereafter, RNNs) remove this key restriction by allowing loops in their computational graph. Through this feedback loop, RNNs can remember data points much further in the past than a typical window size. Figure 3: 1D convolution with multiple input features and output channels. Figure 2: Single channel 1D convolution. Source: Ganesh, 2019. #### 3.2.3 Gated recurrent networks As opposed to the unidirectional relationship between inputs and outputs, previously seen in feedforward networks, RNNs introduce a feedback loop, where layer outputs can be fed back into the network (Dematos et al., 1996). This architecture makes RNNs well-suited to applications with a temporal aspect or flow, such as natural language processing or speech processing. A recurrent neural network (RNN) is a class of artificial neural networks where connections between nodes can create a cycle, allowing output from some nodes to affect subsequent input to the same nodes. This allows it to exhibit temporal dynamic behavior. Derived from feedforward neural networks, RNNs can use their internal state (memory) to process variable length sequences of inputs. This makes them applicable to tasks such as unsegmented, connected handwriting recognition, speech recognition or time series analysis. However, due to vanishing gradients, RNNs tend to have a very "short, memory, limiting their usefulness in the nowcasting application (Ekman, 2021). In our paper, we do not investigate RNNs in general but focus on their more advanced variants that implement a so-called gating mechanism, namely the long short-term memory network (LSTM) and the gated recurrent unit (Hochreiter and Schmidhuber, 1997, Chung et al., 2014). Long short-term memory (LSTM) network is a special form of gated RNNs which was introduced by Hochreiter and Schmidhuber, 1997. A common way of drawing LSTM was introduced in a popular blog post that explains how LSTM works (Olah, 2015). Our summary on LSTMs is based on Ekman, 2021, Goodfellow et al., 2016 and Olah, 2015. Figure 4 below, illustrates an LSTM layer unrolled in time for three timesteps. For each timestep \(t\), the corresponding cell receives \(c_{t-1}\) and \(h_{t-1}\) from the previous timestep (cell) and \(x_{t}\) from the current timestep and outputs new values for the cell state (\(c\)) and the hidden state (\(h\)). Accordingly, \(h_{t}\) and \(c_{t}\) denote the _hidden state_ (also referred to as the _output_ of the LSTM cell) and the _cell state_ (also known as the _internal state_) at time step \(t\), respectively. the same as in Figure 4. As Figure 4 illustrates, LSTM introduces a memory cell and three gates: an input gate, an output, and a forget gate. Essentially, the architecture then allows gradients to flow unchanged through the so-called _gradient highway_, mitigating the vanishing gradient problem of standard RNNs and rendering them more suitable for applications where long memory matters. Considering our empirical analysis, we are interested to see whether allowing for long memory does lead to better nowcasts. Gated recurrent unit (hereafter, GRU) represents the other gated recurrent network adopted in our nowcasting analysis. Considering its architecture, GRU is very similar to an LSTM but belongs to a newer generation of gated RNNs (Chung et al., 2014). The GRU removes the cell state (denoted by \(c_{t}\) in the LSTM) and uses its hidden state (denoted by \(h_{t}\), similar to the LSTM) even for transferring information. This way, it only has two gates, a reset gate and an update gate. Thereby, GRUs has fewer parameters and tensor operations compared to LSTMs (Chung et al., 2014). Consequently, they are a little speedier to train, and a bit less prone to overfitting. Researchers and engineers usually try both to determine which one works better for their use case. So we do the same in empirical analysis. Similarly to 1D CNNs, both LSTMs and GRUs are trained with sequential data. We have seen that gated RNNs provide a solution to the vanishing gradient problem through different gating mechanisms. This way, they can explore long-term dependencies in the sequences and connect information from the past to the present. Considering our empirical analysis, it is an essential question if there are such input sequences whose much older values have a significant impact on current-quarter GDP growth while that impact is no longer reflected in any more recent values of the sequences. To put this question into a more formal manner, let us consider Figure 4: LSTM layer unrolled in time. Source: Olah, 2015 the conditional probability distribution of our target variable. If we assume that GDP growth has no long-term memory, i.e., that it is ergodic, then the following equation is expected to hold for a given sequence length (\(l\)) and for all \(t^{*}<t-l\) time period - at least, approximately: \[\mathbb{P}(y_{t}|\Omega_{t^{*}},\Omega_{t})=\mathbb{P}(y_{t}|\Omega_{t}), \tag{3}\] where \(\mathbb{P}(y_{t}|\Omega_{t-1})\) denotes the conditional probability distribution of \(y_{t}\) conditional on the information set \(\Omega_{t}=[\mathbf{x_{t}},y_{t-1},\mathbf{x_{t-1}},\ldots,y_{t-l+1},\mathbf{ x_{t-l+1}}]\). This question is of essential relevance to our analysis because the choice of the fitting neural network architecture largely depends on what we think about the data-generating process of GDP growth. In other words, in the context of system theory, what do we think about the impulse response function of the target variable? It is worth noting that both the MLP and the 1D CNN build around the assumption of fixed finite support for their target variable, in our case, GDP growth.4 While gated RNNs still assume a finite impulse response for the target variable, they allow for a much longer support. Furthermore, through their gating mechanism, they can dynamically adjust for the length of the impulse response. With this type of flexibility, however, comes complexity (much more trainable parameters) as well. Footnote 4: The support of a real-valued function \(f(.)\) is the subset of the function domain containing the elements which are not mapped to zero. In our case, finite support means that the impulse response is bounded in time. We should also note that gated RNNs are even more complex than those standard RNNs: While in standard RNNs cells are represented by a single neuron, LSTM and GRU cells contain several neurons inside, requiring at least a matrix for every gate. As a result, they are more prone to overfitting and highly sensitive to input noise. Moreover, due to their feedback loop, the stability analysis of (gated) RNNs is also more complicated than the feedforward networks. Even the initialization of such recurrent networks can be complicated in many cases (Ekman, 2021). On the other hand, if we think about the economy as a system with a long memory, then gated RNNs might provide more accurate nowcasts than any previously presented architectures, despite the aforementioned difficulties. Below, in the empirical analysis, we let the data speak and evaluate the results of different models. In addition to the DFM, the state-of-the-art representative of traditional time-series approaches, we apply four different network architectures from the ANNs' side. We believe that this type of an analysis might be informative about the competitor models' nowcasting performance and some important aspects of GDP growth as well. ## 4 Empirical analysis In this section, we first describe the data used in the empirical analysis then define the concrete nowcasting exercise. After that, we present the results of the empirical analysis. ### Description of data The target variable of the empirical analysis is the quarterly GDP growth, that is the percent change (relative to the preceding period) of the US Gross Domestic Product. The series is measured on a quarterly frequency and is available from 1947:Q2 to 2022:Q3. Thus it contains 302 observations. Figure 5 plots the time series for quarterly GDP growth. When the empirical analysis was closed, the last GDP measurement was released for 2022:Q3. This release was revised later, in December. So the fundamental idea of nowcasting, using the informational content of higher-frequency data to help the prediction of our target variable, seems valid in this case. In our empirical analysis, we try to extract the informational content of several monthly macroeconomic indicators (i.e., features) whose intra-quarterly development might be expressive of the current economic growth. The data for the input features comes from the FRED-MD database, the monthly database for Macroeconomic Research of the Federal Reserve Bank of St. Louis, which is described Figure 5: The percent change (relative to the preceding period) of the US Gross Domestic Product. Source: FRED-MD. extensively in McCracken and Ng, 2016. FRED-MD is a large macroeconomic database that is designed for the empirical analysis of "big data". The database is publicly available and updated in real-time on a monthly basis. The FRED-MD database is available for download under the following link: [https://research.stlouisfed.org/econ/mccracken/fred-databases/](https://research.stlouisfed.org/econ/mccracken/fred-databases/). It consists of 134 monthly time series (indicators or features) which are clustered into eight categories: 1. Output and income (17 series) 2. Labour market (32 series) 3. Housing (10 series) 4. Consumption, orders and inventories (14 series) 5. Money and credit (14 series) 6. Interest and exchange rates (22 series) 7. Prices (21 series) 8. Stock market (4 series) The complete list of the data and the series-related data transformations are described in detail in Appendix A.1. Monthly indicator data are available from 1960:M1 to 2022:M9, so we have 753 observations for the potential regressors. It is important to note that as a result of the corresponding data transformation, all of the monthly indicators (features) are transformed into stationarity. Except for the MLP, all of our models are designed to estimate time-invariant prediction rules, which is preferred for stationary time series. In this case, where both the target variable and the regressors (features) are stationary, we can generally expect better predictive performance from these models compared to when modelling non-stationary series. Figure 6 below shows the level values of Real personal income (upper panel) and the result of the adequate stationarity transformation (lower panel). For the training of the different ANNs, we use the same sixteen selected indicator series from the FRED-MD database.5 To estimate the DFM, we use an even more restricted subset of the monthly indicators. Unlike the different ANN architectures presented in our study, the DFM's computation time scales exponentially with the number of input features (i.e., regressors (Hopp, 2021). In the case of the DFM, feature selection is also separated from the actual predictive step. Figure 6: Real personal income (RPI). Source: FRED-MD. These two idiosyncrasies can make the process of feature selection a much more complicated task than that is usually experienced with different ANNs. Based on these considerations, we used the following four monthly macro indicators during the course of the DFM-based nowcasting routine. * Industrial production: Manufacturing (IPMANSICS) * Real aggregate income (excluding transfer payments) (W875RX1) * Manufacturing and trade sales (CMRMTSPL) * Employees on non-farm payrolls (PAYEMS) These series are proposed by the related documentation of the _statsmodels_ Python module (Seabold & Perktold, 2010). All of these series are also included in the FRED-MD dataset. ### Exposition of the nowcasting exercise Our full dataset ranges from 1960:Q1 to 2022:Q3, so that it contains feature observations for every month and target observations for every third month (i.e., for every quarter). We assume that quarterly measured GDP observations are available for months M3, M6, M9, and M12.6 Our training dataset ranges from 1960:Q1 to 2009:Q4. Thus it contains 200 observations for quarterly GDP growth and 600 observations for the monthly indicators (features). We evaluate the results from two test (evaluation) periods in the empirical analysis. The first evaluation period ranges from 2010:Q1 to 2019:Q4, so it ends before the COVID-19 pandemic hits the US economy. It includes 40 observations for the target variable and 120 measurements for the monthly indicators. In comparison, the second evaluation period lasts until 2022:Q3, so it also includes those periods of the COVID crisis. Specifically, it ranges from 2010:Q1 to 2022:Q3, containing 51 target and 153 feature observations. Consequently, we can see the results from two distinctly different evaluation periods. The first is mainly characterized by the balanced economic growth after the Great Recession, while the second is heavily affected by the economic impacts of the COVID-19 pandemic. Footnote 6: FRED data releases associate these quarterly measurements with timestamps M1, M4, M7, and M10. However, using these timestamps would be highly counter-intuitive in this type of analysis. Following the literature, we assume that quarterly GDP measurements are published at the end of the current quarter. In reality, the first measurements are usually available only a few months after the end of the current quarter. In addition to the two separate evaluation periods, we evaluate the results of three different nowcasting scenarios, depending on the information set available for our models. The _1-month_ nowcasting scenario presumes that the monthly indicators' value is available up through the first month within a quarter. In the _2-month_ scenario, the information set also contains feature observations released until the second month within the current quarter. Finally, in the _3-month_ scenario, we use all monthly indicator data available at the end of the current quarter. If we define the nowcast as the conditional expected value of current-quarter GDP growth (\(y_{q}\)), we can write as follows (Giannone et al., 2008): \[\hat{y}_{q}=\mathbb{E}(y_{q}|\Omega_{v},\mathcal{M}), \tag{4}\] where \(t=1,2,\dots\) denotes months, \(q=3t\) denotes quarters, \(\Omega_{v}\) represents the information set containing monthly indicator data until the \(v\)-th month and \(v=[3t-2,\quad 3t-1,\quad 3t]\). Lastly, \(\mathcal{M}\) represents the underlying model. Based on 4, we see that different nowcasting scenarios mentioned above only differ in their corresponding information set. More specifically, \(v=3t-1\) refers to the 2-month nowcasting scenario. So within a given quarter, training sequences of length \(l\) include observations for monthly indicators until the second month. Intuitively, we expect to see the most accurate nowcasts in the 3-month nowcasting scenario (\(v=3t\)), where all intra-quarterly indicator data are available for prediction. In equation 4, \(\mathcal{M}\) denotes a concrete element of the set of our (competitor) models (DFM, MLP, 1D CNN, LSTM, GRU). The underlying model determines what function \(f()\) can be learned between the target variable and the regressors during the training (estimation) process. In the line of the above, the nowcast for quarter \(q\) can be generated as follows: \[\hat{y}_{q}=f\left(\mathbf{x}_{v},\mathbf{x}_{v-1},\dots\mathbf{x}_{v-l+1}\right) \tag{5}\] where \(\mathbf{x}_{v}\) represents a row in the regressor vector, containing observations for \(n\) number of features in month \(v\). As equation (5) suggests, we do not include any lagged values of the target variable in the regressor vector, which is denoted by \(\varphi(\mathbf{x}_{v})\). Hence, if \(l\) denotes the length of the training sequences (i.e. sequences of monthly indicators), the dimensionality of the regressor vector is \(l\times n\). Training samples \((\varphi(\mathbf{x}_{v}),y_{q})\) are formed then by pairing the actual target observations for quarter \(q\) with the corresponding regressor vector. For training samples, \(q\in\{1960:Q1,\dots 2009:Q4\}\). All of our models are estimated (trained) on a fixed-size, static training window, which ranges from 1960:Q1 to 2019:Q4. So it contains 200 observations for quarterly GDP growth. Accordingly, the training dataset has 600 measurements for the monthly indicators (regressors). Training sequences are sampled then by a fixed-length rolling window where the size of the rolling window is determined by the sequence length (\(l\)). Since each (sub)sample of the features is related to a given quarterly target observation, successive rolling windows differ in values for their last 3 months. Consequently, they overlap in \(l-3\) monthly values, provided that \(l>3\) As a criterion (loss) function, we apply the mean squared error according to equation 4. Our training setup ensures that the weights, estimated values of the trainable parameters, are the same for both evaluation periods. Based on (5), we generate the series of nowcasts for the first evaluation period where \(q\in\{2010:Q1,\dots 2019:Q4\}\). We do the same for the second test period, where \(q\in\{2010:Q1,\dots 2022:Q3\}\). The predictive accuracy of the competitor models is evaluated relative to the so-called naive constant growth model. The naive growth model is a basic benchmark model that assumes constant growth for GDP. From a computational point of view, this means that the nowcast for quarter \(q\) is assumed to be equal to its previous actual value: \(\hat{y}_{q}=y_{q-1}\). While even this simple approach might have some theoretical background, its predictive performance is expected to be weak, especially in periods of high economic turbulence. Figure 7 below, illustrates the predicitve performance of the naive constant growth model during the two evaluation periods. In Figure 7, we see that the naive growth model fits the data relatively well in normal economic circumstances (e.g., during the first evaluation period). It clearly fails however when large shocks (positive or negative) hit the economy, just like during our test period. The economic impact of the COVID-19 pandemic resulted in a V-shaped recession: a sharp downturn in 2020:Q2 Figure 7: Nowcasting performance of the naive constant growth model. The first evaluation period ranges from 2010:Q1 to 2019:Q4. The second evaluation period is from 2010:Q1 to 2022:Q3. Source: Own editing based on the FRED-MD database. followed by a quick rebound in growth in 2020:Q3. While signs of the economic downturn had been clearly visible by April or May, the naive benchmark model totally misses to predict the forthcoming recession. We believe that it is an interesting question in itself, how accurately our competitor models can predict this sharp V-shaped recovery? We evaluate the nowcasting accuracy of our models in terms of root mean squared error (RMSE) and mean absolute error (MAE). As a benchmark, the constant growth model generates an RMSE value of 0.538 and an MAE value of 0.414 during the first test period. These measures for the second test period are 2.781 and 1.078, respectively. These values provide the basis for model evaluation and also help to indicate the competitor models' absolute nowcasting accuracy. ### Results In the following, we present the results of the empirical analysis. As the COVID-19 pandemic hit the US economy in 2020, we decided to evaluate our models on two different evaluation periods: The first evaluation period ranges from 2010:Q1 to 2019:Q4, so it does not reflect the economic impact of the COVID-19 pandemic. In comparison, the second evaluation period is from 2010:Q1 to 2022:Q3, containing those periods of the COVID crisis as well. We believe that the results from these two evaluation periods show a more balanced and well-rounded picture of the different models' nowcasting performance. Clearly, these two test periods are very different in their characteristics. The first can be basically described as a period of balanced economic growth. Under such circumstances, the naive benchmark model is expected to be a strong contender for our competitor models. Consequently, competitor models should accurately predict even more intricate movements in economic growth to beat the benchmark model. In contrast, the second evaluation period would favor the models that can capture the sharp V-shaped recovery of 2020:Q2 and 2020:Q3. We believe that results from these two evaluation periods will provide a robust assessment about the generalization capability of the different competitor models, showing their strengths and weaknesses. Below, Table 1 presents the results of the nowcasting competition in our first evaluation (test) period, which ranges from 2010:Q1 to 2019:Q4. Table 1 also shows how the length of the training sequences affect the competitor models' nowcasting accuracy: For the MLP, we formed input sequences of four different lengths by hand: \(l=[4,8,18,36]\). Similarly, we investigated three different sequence length configurations for the other ANN architectures to be trained with input sequences: \(l=[8,18,36]\). In the line of the above, \(n\) refers to the number of features (regressors) selected for training (estimation). First, it is apparent that all of the competitor models can outperform significantly the naive benchmark model, at least under some configurations. Given that the entire sample period was characterized by balanced and stable economic growth, the results of Table 1 seem to justify the use of this type of modeling exercise. In accordance with the recent literature, we see that application of neural networks for economic nowcasting can yield significantly more accurate nowcasts than the naive growth model. Results of Table 1 also suggest that some ANN \begin{table} \begin{tabular}{l|c c|c c|c c} & \multicolumn{2}{c|}{\(v=3t-2\)} & \multicolumn{2}{c|}{\(v=3t-1\)} & \multicolumn{2}{c}{\(v=3t\)} \\ & RMSE & MAE & RMSE & MAE & RMSE & MAE \\ \hline \hline DFM (n=4) & 0.755\({}^{*}\) & 0.777\({}^{*}\) & 0.706\({}^{**}\) & 0.725\({}^{**}\) & 0.712\({}^{**}\) & 0.719\({}^{**}\) \\ \hline MLP (n=16, l=4) & 1.146 & 1.049 & 0.924 & 0.846 & 0.935 & 0.886 \\ MLP (n=16, l=8) & 1.048 & 0.981 & 0.906 & 0.996 & 1.008 & 1.045 \\ MLP (n=16, l=18) & 0.851 & 0.931 & 0.752\({}^{**}\) & 0.759\({}^{**}\) & 0.833\({}^{*}\) & 0.853 \\ MLP (n=16, l=36) & 0.938 & 0.942 & 1.090 & 1.154 & 0.923 & 1.018 \\ \hline 1D CNN (n=16, l=8) & 1.053 & 1.086 & 0.948 & 0.981 & 0.677\({}^{**}\) & 0.715\({}^{**}\) \\ 1D CNN (n=16, l=18) & 0.892 & 0.919 & 0.943 & 0.939 & 0.748\({}^{**}\) & 0.769\({}^{**}\) \\ 1D CNN (n=16, l=36) & 0.952 & 0.981 & 1.056 & 1.127 & 0.816 & 0.874 \\ \hline LSTM (n=16, l=8) & 0.759\({}^{*}\) & 0.743\({}^{*}\) & 0.915 & 1.002 & 0.775\({}^{*}\) & 0.769\({}^{**}\) \\ LSTM (n=16, l=18) & 0.673\({}^{**}\) & 0.699\({}^{**}\) & 0.869 & 0.965 & 0.673\({}^{**}\) & 0.677\({}^{***}\) \\ LSTM (n=16, l=36) & 0.621\({}^{**}\) & 0.644\({}^{***}\) & 0.945 & 1.056 & 0.776\({}^{*}\) & 0.782\({}^{*}\) \\ \hline GRU (n=16, l=8) & 0.659\({}^{**}\) & 0.684\({}^{**}\) & 0.903 & 0.905 & 0.605\({}^{***}\) & 0.592\({}^{***}\) \\ GRU (n=16, l=18) & 0.646\({}^{**}\) & 0.682\({}^{**}\) & 0.829 & 0.843 & 0.632\({}^{***}\) & 0.631\({}^{***}\) \\ GRU (n=16, l=36) & 0.643\({}^{**}\) & 0.652\({}^{***}\) & 0.811 & 0.781 & 0.674\({}^{**}\) & 0.675\({}^{**}\) \\ \hline \end{tabular} * **Notes: This table reports the relative RMSE and MAE of GDP growth for our competitor models relative to a naive constant growth model for GDP. A value below one indicates that the competitor model beats the naive benchmark model. The stars denote statistical significance at 10%(\(*\)), 5%(\(**\)) and 1%(\(***\)) level of the one-sided Diebold and Mariano, 1995 test. Columns are related to the individual nowcasting scenarios: e.g. \(v=3t-2\) refers to the 1-month nowcasting scenario.** \end{table} Table 1: Nowcasting performance of the competitor models relative to a naive constant growth model for GDP: RMSE and MAE evaluation. Evaluation period: 2010:Q1 – 2019:Q4. architectures can beat even the DFM in terms of nowcasting performance: While the DFM can beat the naive benchmark model only on a 5% significance level, the LSTM and the GRU beat it on a 1% level under different configurations. Focusing on the nowcasting performance of the different ANNs, the lack of any temporal aspect clearly hinders the MLP during the test period. As Table 8 shows, it can only outperform the naive benchmark model under just one configuration (\(n=16,l=18\)). Compared to the MLP, 1D CNN generates considerably better nowcasts in the first evaluation period. When indicator data is available until the last month within a quarter, 1D CNN beats the naive benchmark model on a 5% significance level. Clearly though, gated RNNs produce even more accurate nowcasts, according to both evaluation metrics as they beat the constant growth model on a 1%. The overall best-performing model is the GRU which produces a 0.605 relative RMSE and a value of 0.592 of MAE, beating the benchmark model on a 1% significance level. It is interesting to see that the increase of the sequence length above a given threshold does not improve the nowcasting performance of the competitor models. Moreover, this particular threshold for sequence length also seems to be quite stable between the different network architectures. LSTM is the only exception where the increase of the sequence length from 18 to 36 resulted in more accurate results in the 1-month nowcasting scenario. However, longer sequences did not generally yield better nowcasts, even for the LSTM, because the configuration with input sequences of length 18 proved to be an equally good choice. Considering the nowcasting accuracy of the GRU, it is safe to say that the increase of the sequence length does not improve the nowcasting performance. In fact, the configuration with the shortest input sequnces generated the most accurate results in our first evaluation period. Figure 8 plots the nowcasts generated by the best GRU configuration and the actual values of GDP growth. After we have seen the results for our first test period, Table 2 presents the outcome of the nowcasting competition for our second evaluation period which ranges from 2010:Q1 to 2022:Q3. Figure 8: Nowcasting performance of the GRU (n=16, l=8). Evaluation period ranges from 2010:Q1 to 2019:Q4. Source: Own editing based on the FRED-MD database. Table 2 shows that all the competitor models have a better relative nowcasting performance than in the first evaluation period. Controversially, in terms of statistical significance, we see quite the opposite picture: None of the competitor models can beat the naive benchmark model on a 1% significance level, which applies to our evaluation metrics. The reason for this counter-intuitive phenomenon can be traced back to the special characteristics of the evaluation period. The sharp V-shaped recession in 2022:Q2 and Q3 is indicated by extreme values (_outliers_) in \begin{table} \begin{tabular}{l|c c|c c|c c} & \multicolumn{2}{c|}{\(v=3t-2\)} & \multicolumn{2}{c|}{\(v=3t-1\)} & \multicolumn{2}{c}{\(v=3t\)} \\ & RMSE & MAE & RMSE & MAE & RMSE & MAE \\ \hline \hline DFM (n=4) & 0.615 & 0.707 & 0.519 & 0.628\({}^{*}\) & 0.525 & 0.618\({}^{*}\) \\ \hline MLP (n=16, l=4) & 0.436 & 0.577\({}^{*}\) & 0.234\({}^{*}\) & 0.426\({}^{**}\) & 0.219\({}^{*}\) & 0.400\({}^{**}\) \\ MLP (n=16, l=8) & 0.344 & 0.550\({}^{*}\) & 0.234\({}^{*}\) & 0.479\({}^{**}\) & 0.217\({}^{*}\) & 0.442\({}^{**}\) \\ MLP (n=16, l=18) & 0.303\({}^{*}\) & 0.554\({}^{*}\) & 0.391 & 0.594\({}^{*}\) & 0.432 & 0.666\({}^{*}\) \\ MLP (n=16, l=36) & 0.418 & 0.582\({}^{*}\) & 0.471 & 0.656\({}^{*}\) & 0.475 & 0.652\({}^{*}\) \\ \hline 1D CNN (n=16, l=8) & 0.293\({}^{*}\) & 0.581\({}^{*}\) & 0.294\({}^{*}\) & 0.530\({}^{*}\) & 0.297\({}^{*}\) & 0.472\({}^{**}\) \\ 1D CNN (n=16, l=18) & 0.562 & 0.678 & 0.532 & 0.715 & 0.494 & 0.647 \\ 1D CNN (n=16, l=36) & 0.296\({}^{*}\) & 0.526\({}^{*}\) & 0.647 & 1.072 & 0.563 & 0.690\({}^{*}\) \\ \hline LSTM (n=16, l=8) & 0.473 & 0.559\({}^{**}\) & 0.546 & 0.673 & 0.542 & 0.628\({}^{*}\) \\ LSTM (n=16, l=18) & 0.463 & 0.578\({}^{**}\) & 0.558 & 0.701 & 0.512 & 0.579\({}^{**}\) \\ LSTM (n=16, l=36) & 0.424 & 0.497\({}^{**}\) & 0.561 & 0.707 & 0.538 & 0.608\({}^{*}\) \\ \hline GRU (n=16, l=8) & 0.426 & 0.532\({}^{**}\) & 0.547 & 0.641\({}^{*}\) & 0.506 & 0.527\({}^{**}\) \\ GRU (n=16, l=18) & 0.380\({}^{*}\) & 0.514\({}^{**}\) & 0.520 & 0.609\({}^{*}\) & 0.518 & 0.547\({}^{**}\) \\ GRU (n=16, l=36) & 0.402\({}^{*}\) & 0.506\({}^{**}\) & 0.541 & 0.605\({}^{*}\) & 0.492 & 0.546\({}^{**}\) \\ \hline \end{tabular} * **Notes:** This table reports the relative RMSE and MAE of GDP growth for our competitor models relative to a naive constant growth model for GDP. A value below one indicates that the competitor model beats the naive benchmark model. The stars denote statistical significance at 10%(\(*\)), 5%(\(**\)) and 1%(\(***\)) level of the one-sided Diebold and Mariano, 1995 test. Columns are related to the individual nowcasting scenarios: e.g. \(v=3t-2\) refers to the 1-month nowcasting scenario. \end{table} Table 2: Nowcasting performance of the competitor models relative to a naive constant growth model for GDP: RMSE and MAE evaluation. Evaluation period: 2010:Q1 – 2022:Q3. the target series. In these periods, the naive benchmark model, which assumes constant growth, performs particularly poorly. Recalling the formula of the Diabolid - Mariano test statistic, these extreme values affect the variance of the loss differential (series) much more than its mean. In the following version of this paper, we plan to adopt an evaluation method more suitable to the characteristics of the second test period. Nonetheless, the results of Table 2 provide some valuable insights into the generalization capabilities of the different models and the role of long-term memory. Here, the MLP's simple yet highly flexible architecture results in highly accurate nowcasts. Concretely, best MLP configurations consistently beat the benchmark model on a 5% significance level in terms of MAE evaluation and on a 10% significance level in terms of RMSE. It is apparent that the best-performing configurations are the ones trained with shorter input sequences \((l=4,8)\). These configurations detect the COVID-crisis particularly well which leads to remarkably good relative performance in term of RMSE. Considering the other time-invariant architectures, 1D CNN is the only one which comes close to MLP's performance. Some 1D CNN configurations with shorter sequences can detect the COVID crisis almost as good as the best MLPs. The configuartion with 8 long input sequences actually beats the benchmark model in all the nowcasting scenarios. The relatively weak performance of the gated RNNs suggests that long-term memory does not help predict sharp changes in economic growth, just like the V-shaped recession of 2020:Q2 and Q3. Architectural constraints providing time-invariant behavior also seem more of a handicap as well. Figure 9 plots the nowcasts generated by our best MLP configuration and the actual values of GDP growth. As we proposed, 1D CNN represents a _"sweet spot"_ in terms of architectural design between the simple time-agnostic MLP and the more complex gated recurrent networks. Based on the results of Table 1 and Table 2, nowcasting performance of the 1D CNN seems very balanced as well. Although it does not achieve the best result in either of the two evaluation periods, its accuracy comes considerably close to that of the best model. Figure 10 below illustrates the nowcasting performance of the 1D CNN during our two evaluation periods. Figure 9: Nowcasting performance of the MLP (n=16, l=4). Evaluation period ranges from 2010:Q1 to 2022:Q3. Source: Own editing based on the FRED-MD database. Figure 10: Nowcasting performance of the 1D CNN (n=16, l=8). Source: Own editing based on the FRED-MD database. Conclusion In our study, we have conducted a nowcasting competition between different statistical models. The results of the empirical analysis show that all of our models can beat the naive benchmark model in terms of nowcasting performance. While the statistical significance of the performance gain changes between the different nowcasting scenarios, it is the strongest in the 3-month nowcasting scenario - as expected. So, the results clearly justify the use and relevance of this type of analysis. The results suggest that some properly selected neural network architectures can have even better nowcasting performance than the dynamic factor model, the state-of-the representative of traditional time-series approaches. We believe that our empirical analysis might indicate some important aspects of economic growth as well. Concretely, they can be expressive of the data-generating process of GDP growth. Previously, we have seen the results of two distinctively different evaluation periods. One is characterized by balanced economic growth, while the other also includes periods of the COVID-19 recession. The results show that longer input sequences result in more accurate nowcasts in periods of balanced economic growth. However, this effect ceases above a relatively low threshold value of around six quarters (eighteen months). During periods of economic turbulence (e.g., during the COVID-19 recession), longer sequences do not help the models' predictive performance. Instead, they seem to weaken their generalization capability. Generally, the results suggest that long-term memory is not particularly relevant in the nowcasting of GDP growth. Our results show that 1D CNN, with the same weights, generates considerably accurate nowcasts in both of our evaluation periods. Consequently, first in the literature, we propose the use of this specific neural network architecture for economic nowcasting. There remains much scope for future research and development on this topic. First, we plan to adopt a systematic (automated) procedure for feature selection. Sadly, as we know, gated RNNs do not have efficient filters and wrappers, similar to what was described in Crone and Kourentzes, 2010. In addition, a more systematic hyperparameter optimization routine could yield more accurate nowcasts and strengthen the conclusion of the empirical analysis.
2303.06367
Probing neural representations of scene perception in a hippocampally dependent task using artificial neural networks
Deep artificial neural networks (DNNs) trained through backpropagation provide effective models of the mammalian visual system, accurately capturing the hierarchy of neural responses through primary visual cortex to inferior temporal cortex (IT). However, the ability of these networks to explain representations in higher cortical areas is relatively lacking and considerably less well researched. For example, DNNs have been less successful as a model of the egocentric to allocentric transformation embodied by circuits in retrosplenial and posterior parietal cortex. We describe a novel scene perception benchmark inspired by a hippocampal dependent task, designed to probe the ability of DNNs to transform scenes viewed from different egocentric perspectives. Using a network architecture inspired by the connectivity between temporal lobe structures and the hippocampus, we demonstrate that DNNs trained using a triplet loss can learn this task. Moreover, by enforcing a factorized latent space, we can split information propagation into "what" and "where" pathways, which we use to reconstruct the input. This allows us to beat the state-of-the-art for unsupervised object segmentation on the CATER and MOVi-A,B,C benchmarks.
Markus Frey, Christian F. Doeller, Caswell Barry
2023-03-11T10:26:25Z
http://arxiv.org/abs/2303.06367v1
Probing neural representations of scene perception in a hippocampal dependent task using artificial neural networks ###### Abstract Deep artificial neural networks (DNNs) trained through backpropagation provide effective models of the mammalian visual system, accurately capturing the hierarchy of neural responses through primary visual cortex to inferior temporal cortex (IT) [41, 43]. However, the ability of these networks to explain representations in higher cortical areas is relatively lacking and considerably less well researched. For example, DNNs have been less successful as a model of the egocentric to allocentric transformation embodied by circuits in retrosplenial and posterior parietal cortex. We describe a novel scene perception benchmark inspired by a hippocampal dependent task, designed to probe the ability of DNNs to transform scenes viewed from different egocentric perspectives. Using a network architecture inspired by the connectivity between temporal lobe structures and the hippocampus, we demonstrate that DNNs trained using a triplet loss can learn this task. Moreover, by enforcing a factorized latent space, we can split information propagation into "what" and "where" pathways, which we use to reconstruct the input. This allows us to beat the state-of-the-art for unsupervised object segmentation on the CATER and MOVi-A,B,C benchmarks. ## 1 Introduction Recently, it has been shown that neural networks trained with large datasets can produce coherent scene understanding and are capable of synthesizing novel views [12, 21]. These models are trained on egocentric (self-centred) sensory input and can construct allocentric (world-centred) responses. In animals, this transformation is governed by structures along the hierarchy from the visual cortex to the hippocampal formation, an important model system related to navigation and memory [20, 30]. Notably, the hippocampus is a necessary component of the network supporting memory and perception of places and events and is one of the first brain regions compromised during the progression of Alzheimer's disease (AD) [3, 34]. However, experimental knowledge regarding the interplay across multiple interacting brain regions is limited and new computational models are needed to better explain the single-cell responses across the whole transformation circuit. Here, we developed a scene recognition model to better understand the intrinsic computations governing the transformation from egocentric to allocentric reference frames, which controls successful view synthesis in humans and other animals. For this, we developed a novel hippocampally dependent task, inspired by the 4-Mountains-Test [18], which is used in clinics to predict early-onset Alzheimer's disease [40]. We tested this task by creating a biologically realistic model inspired by recent work in scene perception, in which scenes need to be re-imagined from several different viewpoints. The main contributions of our paper are the following: * We introduce and open-source the allocentric scene perception (ASP) benchmark for training view synthesis models based on a hippocampally dependent task which is frequently used to predict AD. * We show that a biologically realistic neural network model trained using a triplet loss can accurately distinguish between hundreds of scenes across many different viewpoints and that it can disentangle object information from location information when using a factorized latent space. * Lastly, we show that by using a reconstruction loss combined with a pixel-wise decoder we can perform unsupervised object segmentation, outperforming the state-of-the-art models on the CATER, MOVi-A,B,C benchmarks. ## 2 Related work ### Related work in neuroscience The study of scene perception in neuroscience was first systematically explored in behavioural experiments in 1972, by showing for the first time scenes in real-world contexts to human participants [2]. These outdoor scenes were either shown intact or scrambled into six randomly arranged pieces. It was shown, that the correct identification of cued objects was drastically lower when the scenes were scrambled, indicating that the various parts of a scene are perceived as a whole. Neural recordings as a response to scenes were first reported in fMRI experiments that showed that the parahippocampal place area (PPA) is involved in perceiving the visual environment, being more active for outdoor scenes than single objects [9]. Moreover, activity is reduced when scrambling the picture into random pieces, indicating that neurons in PPA are sensitive to the structure of the entire scene [10]. A second scene-selective region was shown to be also active during mental imagination of scenes, subsequently labelled as the retrosplenial complex (RSC). The RSC also acts as a hub to integrate sensory, motor and visual information and is crucial for the transformation from egocentric to allocentric reference frames [8, 29]. Computational modelling has suggested that the transformation in RSC is governed by head direction cells [5], which encode the world-centred facing direction of the head of the animal in the azimuthal plane [32]. When egocentric information from the parietal cortex reaches RSC, the head direction signal aligns these cells to a common reference, creating complementary allocentric cell types. These include object vector cells in the medial entorhinal cortex [19], which are active at spatially confined objects and boundary vector cells (BVCs) in the subiculum [25] which encode boundary information in their neuronal activity. The combined activity of several BVCs giving rise to allocentric place cells in the hippocampus [1, 5]. In recent years, normative machine-learning approaches have investigated visual information processing in an egocentric reference frame while translating it into an allocentric representation for downstream task performance. Several types of these models have been explored, most notably the Tolman-Eichenbaum-Machine (TEM) [38] and the Spatial Memory Pipeline (SMP) [37]. These normative models have shown the emergence of allocentric spatial cells in two separate tasks, using a similar objective function: predicting the next sensory observation. However, both of these models have not been tested on their abilities to generate images from novel viewpoints, with TEM only taking in abstract sensory observations and SMP being employed in a reinforcement-learning (RL) environment using a spatial navigation task. ### Related work in computer science Beyond TEM and SMP, specially designed scene perception models have tackled the problem of novel view synthesis in several distinct ways. For example, in robotics, SLAM (Simultaneous localization and mapping) algorithms have been used extensively to represent scenes and navigate within them, but mainly in a supervised setting on partially occluded scenes and with a focus on the navigational abilities of robots, which are endowed with additional sensors [6]. Neural radiance field (NERF) networks [27, 28, 35] try to mimic the image synthesis based on real-world physics, namely the way light is reflected from certain materials and Figure 1: **Task design and model architecture** how these rays end up in the camera sensor. For this, the neural network must infer all the scene's physical properties. The actual reconstruction of an image is done analytically by a traditional rendering engine, which is typically not changed during training [36]. The advantage of these rendering methods lies in the fact that arbitrary resolutions can be achieved. This is possible as it is not using image or voxel space, but a continuous neural representation, where coordinates are mapped through a neural network to their corresponding value - representing colour, occupancy or material properties [27, 31]. However, a common shortfall of neural rendering methods is the use of separate neural networks for each scene, making it hard to gauge the generalization abilities beyond its training scenes. Traditional scene decomposition methods beyond NERFs are able to generalize across many scenes, while still relying on pixel-level information. Most commonly, the model takes several snapshots of a scene from different viewpoints which are joined in a latent space. To produce new views, the latent space is conditioned with a new set of camera coordinates, reconstructing a novel viewpoint [12]. Recent models have focused on architectures using a slot structure which disentangles objects within a scene from each other using self-attention [26, 21, 16]. This allows the model to learn a fully unsupervised factorized latent space, which is used to synthesize novel viewpoints and scenes with different compositionality [21]. ## 3 Task design None of the above-mentioned biologically inspired models is equipped to deal with randomly sampled egocentric sensory observations. Therefore we built a model inspired by novel view synthesis tasks while considering the particularities of the hippocampus dependent 4-Mountains-Test [7, 18]. This test is used in the clinic and requires allocentric topographical processing for successful task performance, thus is sensitive to hippocampal damage including that which accumulates during the early stages of AD. The participant first views an image of a scene with four mountains in it and after a two-second delay is asked to match the same-scene image out of four images (three distractors and one target image, see Figure S1 for the same test using our adapted design). Most importantly, the correct image is the same scene, seen from a different viewpoint. In contrast, the distractor images show scenes where the objects are located in different allocentric configurations compared to the original scene. We simplified the task into its core components by rendering four objects with circular symmetry and a global reference frame given by the surrounding landscape. Novel scenes were rendered by randomly changing the world-centred location of each object, thereby changing the relative distances of the objects to themselves and the boundary. We acquire egocentric sensory observations by rendering the scene across different viewpoints, varying both azimuth and elevation (Figure 2). We also render views from the 'inside' of the environment, simulating the views of an agent navigating the scene. We render six different versions of this task, by varying both the distal landmark \((with|without)\) and the colours of the objects \((mix|green|white)\), while randomly varying the number of objects within the scene from 1 to 4, with 10% of the scenes having one object, 20% two, 30% three, and 40% containing four objects. We sampled different colours, as traditional scene perception models struggle to differentiate objects with the same colour or the floor's colour. During rendering, we also store segmentation masks and depth profiles for each rendered viewpoint (Figure 2 & Figure S2). Moreover, we store positional information for analysis of neural activity with respect to different reference frames. This includes the positions of the objects in an egocentric reference frame (position 'on the screen'), angular information such as azimuth and elevation and the allocentric positions of each object within the environment (Figure 4). ## 4 Model architecture The overall architecture of the model follows known biological connectivity between visual cortices and the hippocampal formation [3] (Figure 1). To simulate the responses of the visual cortex, we use a pre-trained convo Figure 2: **Variations of task design** lutional neural network which accurately predicts neural responses from the macaque visual system [24, 33] (CORNet-Z). This ensures that visual cortex responses do not overfit the objects, colours and backgrounds we use but generalize onto natural images. We extract activations from visual cortex area 4 (V4) and inferior temporal (IT) cortex for each rendered viewpoint. The information from V4 and IT is then routed through perirhinal (PR) and parahippocampal (PH) cortices using either weak or strong connectivity. We implement the strong connections using a feedforward layer with non-linearity between two areas, and the weak connections by adding a residual connection consisting of a linear feedforward layer that uses the summed input of all previous activations. Both areas receive information mainly from the ventral visual processing stream, with PR being crucial for the representation of objects ('what'), while PH predominantly processes visuospatial information [3]. We implement this split of information by averaging the visual cortex representation either across the temporal or spatial axis, which also enforces disentangled latent representations in subsequent layers, namely the medial (MEC) and lateral (LEC) entorhinal cortex. MEC receives input which is averaged across time, therefore being trained to keep spatial information, while LEC receives input averaged across the spatial dimension, thereby retaining temporal information. We implement the hippocampus consisting of CA3 and CA1, with the former integrating information using a self-attention layer across different snapshots of the same scene and the latter integrating both temporal and spatial information using the outer product, which is fed through a simple feedforward layer, similar to how TEM integrates information in the hippocampal formation [39]. To reconstruct the input across novel views, we use a pixel-wise decoder similar to the one used in SIMONe [21]. For the feedback connections, we use the CA1 layer which is split into temporal (LEC) and spatial (MEC) information exactly as the forward pass splits the visual information at the level of the PR/PH layers. We then sample from LEC and MEC for each object and pixel and combine them with periodic positional encodings. These are fed through a 5-layer MLP decoder using 128 units each, decoding RGB values for each pixel and object which are combined with alpha masks to produce the full reconstructed image (Figure S3). ## 5 Model optimization During model training, the model receives egocentric sensory observations which are transformed into allocentric representations in the hippocampal formation. The model is trained by minimizing either a triplet loss on this hippocampal latent space or an L2-reconstruction loss in pixel space if the model is tasked to reconstruct the image: \[\mathcal{L}_{a,p,n}=\sum_{i}\max\left(\sqrt{(x_{i}^{a}-x_{i}^{p})^{2}}-\sqrt{( x_{i}^{a}-x_{i}^{n})^{2}}+\alpha,0\right) \tag{1}\] \[\mathcal{L}_{MSE}=\frac{1}{n}\sum_{n}\left(x_{i}-\hat{x}_{i}\right)^{2} \tag{2}\] where \(x^{a,p,n}\) denotes the anchor, positive or negative representation from a given layer. If the image layer is used, these correspond to the original image in pixel space. The L2-reconstruction loss is calculated between the predicted reconstruction \(\hat{x}_{i}\) and the original image \(x_{i}\) on the full-resolution image. The final loss is summed across the width, height and timesteps and averaged across batches. The predictive objective function used in previous models [37, 38] is similar to the reconstruction loss in our model as the latent space enforces the reconstruction of scenes from different viewpoints, which can be understood as a prediction of not only the next observation but all possible observations. Note that many recent models capable of novel view synthesis use variational inference [4, 21], for which it is unclear how individual distribution statistics would be sampled in biological tissue. We, therefore, do not sample from the distribution and only use the mean, similar to how TEM constructs its latent space [38]. ## 6 Results ### Performance on adapted 4-Mountains-Test We first train our scene perception model to separate between different scenes, closely linked to the original task in Figure 3: **Model performance on scene perception task.** Model performance across layers. For each layer, we calculate the accuracy by sampling triplets and quantifying the number of correctly classified same-scene images. Scenes used for training are depicted as grey circles and test scenes as white circles. Most world-centred responses are measured in late layers, indicating that hippocampal responses are similar for images from the same scene from different viewpoints. the 4-Mountains-Test (Figure S1). We use a triplet loss in which we sample an anchor and a positive image from the same scene, together with a negative image from a different scene. This contrastive loss function allows us to disentangle the hippocampal representation between different scenes maximally. Model performance is evaluated by randomly sampling triplets (anchor, positive, negative) from the whole dataset, calculating a cross-correlation matrix and using the smallest off-diagonal value as the correct image. If a layer is able to distinguish between scenes, the correlation between the same-scene pair seen from different viewpoints should be high, while the correlation between different-scene pairs should be low. This performance measure allows us to evaluate accuracy across all model layers. We observe that the pre-trained layers and the image itself show performance levels around chance, with IT performing best (Chance: 33%, IT: 39%, Figure 3). This means that even though IT is thought to contain object-specific information, it lacks crucial information to differentiate between scenes containing the same objects but in different allocentric positions. Nevertheless, these scenes can be distinguished by late layers in our model, with CA3 and CA1 showing performance close to 90% (CA3 89%, CA1 88%), indicating that these layers construct a world-centred representation of the environment, which is needed for separating the scenes in the adapted 4-Mountains-Test. ### Neural representations within network layers To quantify the amount of allocentric information contained in each trained layer, we calculate an allocentricity measure. We define allocentricity as the coefficient of variation of the activation of each artificial neuron across several images of the same scene. A neuron that fires similarly across images of the same scene from a different viewpoint has a high allocentric score, while a neuron with a high variance in its activations for the same stimuli has a low allocentric score. We observe that the hippocampal layers show the highest allocentricity score (PH, -5.5\(\pm\)0.03; PR, -2.6\(\pm\)0.05; CA3, 5.0\(\pm\)2.2; CA1, 3.5 \(\pm\) 1.7), indicating that these layers have learned to be active for the same scene across different viewpoints, i.e. have formed an allocentric representation of the environment (Figure S4). Having established a differentiation across layers between egocentric and allocentric information, we sought to investigate which scene properties are represented in each layer. We use a linear readout to investigate the separation of scene properties into low-level features like colours or the position on the screen, mid-level elements like object size and high-level features like allocentric position and scene identity [11]. We observe a trend toward later layers incorporating more high-level information. However, the overall structure is less clear than previously reported in the visual cortex [17, 42, 22]. Information regarding the position of objects in allocentric coordinates can only be effectively read out from hippocampal layer CA3, while egocentric information - object's position in screen coordinates - is reduced drastically in the layers beyond MEC, with CA1 seemingly only retaining allocentric information (Figure S4). We next sought to investigate individual neural responses to obtain a fine-grained understanding of the computations being performed within each layer and, importantly, the ways in which they relate to known biological data. For this purpose, we visualize the activity of a subset of neurons within each layer with regard to different reference frames (Figure 4). We use the egocentric reference frame for pixel coordinates and the allocentric reference frame for objects or locations in the environment. To visualize angular allocentric responses, we visualize the activity using polar coordinates. We observe allocentric boundary and place-like activity in the CA1 layers as a function of the position of an object (Figure 4). This indicates that single neurons within the model layer are highly activated whenever an object is close to the boundary or occupies a certain allocentric position within the environment, similar to the boundary and place-like activity observed in biological organisms [25, 30]. These spatial responses also show similar mechanisms to biological cells, as they tend to remap across different scenes (S5. We observe these responses as a result when using only the triplet loss on the CA1 layer. As we describe further below, we can reconstruct and segment the image into distinct objects using an additional reconstruction loss. ### Reconstructing the input through feedback connections Having established that the model is able to discern between novel scenes from arbitrary viewpoints, we next explored its ability to reconstruct the scene across these viewpoints. For this, we added an additional reconstruction loss in pixel space (Figure S3). Reconstructing the input image is more challenging than just differentiating between scenes, as complete scene information has to be retained across layers or reinstated from a latent representation. Therefore, we used a factorized latent space to sample objects and frame information for each individual pixel and time point, similar to recent scene perception models [21]. It is assumed that mental imagination (and similarly novel view synthesis) is guided by a viewpoint-changing signal likely provided by grid cells in the medial entorhinal cortex, which is combined with object information in the lateral entorhinal cortex and is then further disentangled into egocentric information inside the retrosplenial cortex, which together with visual cortex establishes the mental image [1]. We first test the reconstruction loss across our six variations of the task, in which we varied object colour and back ground information (Figure S2). We observe a difference in the segmentation performance of the model depending on the object colours used, with the green and white colours performing worse than the mixed objects, likely because it is harder to differentiate between objects of the same colour (Table 1). This has also been noticed in traditional scene decomposition models, which struggle to disentangle objects of the same colour and objects having a similar colour to the background [12]. Interestingly, if we do not enforce the disentanglement in CA1 via the triplet loss, we can still see a differentiation between scenes in the late layers of the model by just training on the reconstruction loss. ### Model performance on CATER and MOVi Lastly, we evaluated our neural network architecture on the Compositional Actions and TEmporal Reasoning (CATER) benchmark [13] as well as the MOVi-A,B,C datasets [14]. These datasets consist of three to eleven randomly placed objects, with a fixed camera location but moving objects. We use the modified CATER dataset from [21], which includes segmentation masks for each object in order to explore the model's ability to perform object segmentation fully unsupervised. We use the same model architecture for higher-level cortices as described above, but replace the pre-trained visual representation with four convolutional layers, using a kernel size of four and a stride of 2. We additionally increase the number of units in the pixel-wise decoder from 128 to 512 and train the model for 300000 steps using a batch size of 1. As shown in Figure 5, our model is able to reconstruct the input frames and segment the ob \begin{table} \begin{tabular}{l l l l} \hline \hline & & Distal landmark & No landmark \\ \hline \multirow{3}{*}{MSE} & Green & \(\mathbf{27.912\pm 1.289}\) & 46.411 \(\pm\) 2.777 \\ & Mix & 45.908 \(\pm\) 4.405 & 60.159 \(\pm\) 1.923 \\ & White & 52.713 \(\pm\) 4.119 & \(\mathbf{19.167\pm 0.575}\) \\ \hline \multirow{3}{*}{FG-ARI} & Green & 0.137 \(\pm\) 0.122 & 0.046 \(\pm\) 0.010 \\ & Mix & \(\mathbf{0.207\pm 0.148}\) & \(\mathbf{0.297\pm 0.119}\) \\ & White & 0.086 \(\pm\) 0.035 & 0.140 \(\pm\) 0.023 \\ \hline \multirow{3}{*}{ARI} & Green & 0.122 \(\pm\) 0.063 & \(\mathbf{0.067\pm 0.066}\) \\ & Mix & \(\mathbf{0.383\pm 0.122}\) & 0.016 \(\pm\) 0.016 \\ \cline{1-1} & White & 0.136 \(\pm\) 0.089 & 0.039 \(\pm\) 0.033 \\ \hline \hline \end{tabular} \end{table} Table 1: **Reconstruction and unsupervised segmentation performance on ASP** We compare the mean-squared error for reconstructing the input images (MSE), the foreground adjusted rand index (FG-ARI) and the full adjusted rand index (ARI) across all six variations of our dataset. We use random seeds to report the mean and standard deviation across five model runs. The lowest MSE values and highest ARI values are displayed in bold. \begin{table} \begin{tabular}{l c c c c} \hline \hline & MONet & SIMOne & SAVi & Ours \\ \hline CATER & 0.412 \(\pm\) 0.012 & 0.918 \(\pm\) 0.036 & 0.928 \(\pm\) 0.008 & \(\mathbf{0.939\pm 0.013}\) \\ MOVi-A & - & 0.618 \(\pm\) 0.200 & 0.820 \(\pm\) 0.030 & \(\mathbf{0.790\pm 0.017}\) \\ MOVi-B & - & 0.307 \(\pm\) 0.330 & 0.615 \(\pm\) 0.030 & \(\mathbf{0.460\pm 0.033}\) \\ MOVi-C & - & 0.198 \(\pm\) 0.005 & 0.470 \(\pm\) 0.030 & \(\mathbf{0.318\pm 0.099}\) \\ \hline \hline \end{tabular} \end{table} Table 2: **Segmentation performance across unsupervised models on CATER and MOVi.** We compare the foreground adjusted rand index (FG-ARI) across different unsupervised models, quantifying how well the model segmentation matches the real masks. Note that MONet is a static-frame model which predicts segmentation for each frame separately, likely causing the model to fail to track objects stably. SAVi is not a fully unsupervised model, using optical flow as a supervision signal. Baseline scores for MONet, S-IODINE and SIMOne were taken from [21], SAVi score was taken from [21]. To obtain the final model performance, we first train a model for 200000 steps with a fixed learning rate and subsequently present the efficacy of five models initialized with these weights and trained utilizing an annealing learning rate. Figure 4: **Single-cell representations across different reference frames.** (Top) Illustration of egocentric and allocentric schemas. The left side shows two snapshots from the same scene using different viewpoints. The panels to the right depict the egocentric and allocentric schema for the respective snapshot. Black lines indicate screen coordinates for the same object in the egocentric view and world coordinates in the allocentric view. Note that by definition the allocentric, world-centred schema is the same for both snapshots. (Bottom) Example representations from neurons within the network, across each reference frame, showing activity of two neurons for azimuth, egocentric object position and allocentric object position. jects on the CATER dataset, by using only a reconstruction loss. We compare our model against other unsupervised segmentation models like MONet [4], S-IODINE [15], SIMONe [21] and SAVi [23] (see Table 2). We achieve comparable or better performance to the best baseline models on CATER (FG-ARI: SAVi 0.928 \(\pm\) 0.008; Ours 0.939 \(\pm\) 0.013) while outperforming all unsupervised models (SAVi is trained on optical flow information). Based on visual examination of background segmentation in [21], we note that the full ARI score (taking into account both background and foreground) of our model likely outperforms many of the baseline models, which do not report the full score (Ours, FG-ARI: 0.939 \(\pm\) 0.013, ARI: 0.825 \(\pm\) 0.04). For the more challenging MOVi datasets, we further increase the number of units in the decoding layer to 1024 and train the model for 400000 steps using a batch size of 1. We observe a decline in performance with increasing scene complexity (FG-ARI, MOVi-A 0.790, MOVi-B 0.460, MOVi-C 0.318), while still outperforming SIMONe on all three datasets. Taken together, these comparisons show that our biologically inspired model is not only able to reconstruct images from our novel benchmark but shows comparable performance to state-of-the-art unsupervised scene segmentation models. ## 7 Discussion Here we explored the neural representations of an artificial neural network which was trained to perform allocentric topographical processing, similar to how the Four-Mountains-Test is used to predict the early onset of Alzheimer's disease. The model uses visual representations from V4 and IT and uses higher-level areas like the entorhinal and hippocampus to successfully differentiate between scenes from different viewpoints. We show that this biologically inspired model can discern between hundreds of scenes and generalize beyond its training set. Moreover, it is able to reconstruct the visual input through a factorized latent space [21, 24], disentangling object from spatial information. Our model is able to perform novel view synthesis by imagining scenes from different viewpoints (4MT) or dif Figure 5: **Model performance for reconstructing and segmenting novel scenes. (Left) Model performance across three scenes taken from the test set of CATER. The top two rows show model input and reconstruction of input, the bottom two rows show the true segmentation of objects within the scene and the predicted segmentation of the model. (Right) Reconstruction and segmentation performance across time for Scene 3. The top left object (red in the original input) moves up and to the left of the frame. The model is able to accurately segment and track the object across all 16 frames (4 intermediate frames shown here), albeit classifying the shadow as part of the object.** ferent moments in time (CATER & MOVi) and can segment objects on par with recent state-of-the-art models. One shortcoming of this approach is the relatively small model size which likely prevents it from performing well on more challenging real-world datasets like MOVi-C,D,E or COCO. More powerful visual representations might help for these datasets, for which our visual cortex can be easily replaced with features from models that have a higher similarity to visual cortices [33]. In the future, we want to further explore the difference in neural representations across the objective functions used. We observed that spatially modulated cells also arise in the model using a reconstruction loss, but only in the temporally averaged pathway (MEC) and only in a small subset of neurons. This likely arises from the use of LEC & MEC as a bottleneck, forcing the model to retain scene information in order to fully reconstruct the image, which is not needed for the disentangling of the latent representation.
2307.12183
An X3D Neural Network Analysis for Runner's Performance Assessment in a Wild Sporting Environment
We present a transfer learning analysis on a sporting environment of the expanded 3D (X3D) neural networks. Inspired by action quality assessment methods in the literature, our method uses an action recognition network to estimate athletes' cumulative race time (CRT) during an ultra-distance competition. We evaluate the performance considering the X3D, a family of action recognition networks that expand a small 2D image classification architecture along multiple network axes, including space, time, width, and depth. We demonstrate that the resulting neural network can provide remarkable performance for short input footage, with a mean absolute error of 12 minutes and a half when estimating the CRT for runners who have been active from 8 to 20 hours. Our most significant discovery is that X3D achieves state-of-the-art performance while requiring almost seven times less memory to achieve better precision than previous work.
David Freire-Obregón, Javier Lorenzo-Navarro, Oliverio J. Santana, Daniel Hernández-Sosa, Modesto Castrillón-Santana
2023-07-22T23:15:47Z
http://arxiv.org/abs/2307.12183v1
# An X3D Neural Network Analysis for Runner's Performance Assessment in a Wild Sporting Environment ###### Abstract We present a transfer learning analysis on a sporting environment of the expanded 3D (X3D) neural networks. Inspired by action quality assessment methods in the literature, our method uses an action recognition network to estimate athletes' cumulative race time (CRT) during an ultra-distance competition. We evaluate the performance considering the X3D, a family of action recognition networks that expand a small 2D image classification architecture along multiple network axes, including space, time, width, and depth. We demonstrate that the resulting neural network can provide remarkable performance for short input footage, with a mean absolute error of 12 minutes and a half when estimating the CRT for runners who have been active from 8 to 20 hours. Our most significant discovery is that X3D achieves state-of-the-art performance while requiring almost seven times less memory to achieve better precision than previous work. ## 1 Introduction With the progress of technology, the world of sports undergoes a tremendous transformation as competition teams seek new ways to gain an advantage. Computer vision, which employs artificial intelligence algorithms to analyze camera footage in real-time, is one of the most promising research areas on this topic. In this regard, computer vision has already been utilized in various applications, such as player position estimation, ball trajectory prediction, and technological assistance to referee decisions [1]. Recently, algorithms for action quality assessment (AQA) have emerged as a result of human action recognition research [2]. AQA aims to design a system that can automatically and objectively evaluate specific human actions based on input videos. Contrary to the traditional video action recognition problem, AQA evaluates the execution of an action. Sports have benefited from AQA in many practical scenarios, such as athlete posture correction, coaching systems, and action evaluation. In recent years, the score to be assigned to an athlete's performance by a panel of judges has been estimated, such as diving and gymnastics movements. Consequently, numerous AQA approaches treated this task as a regression problem to learn the direct mapping between videos and action scores [3, 4]. Lately, ultra-distance competitions have been considered for runners' performance evaluation [5]. Contrary to previous sporting AQA works, the task is not to measure the performance of methods between the ground truth and a predicted score series but the CRT. The CRT at a particular recording point \(RP_{i}\) can be defined as \(T_{i}=T_{1}+\sum_{j=2}^{j=i}(T_{j}-T_{r})\ where\ r=j-1\), see Figure 1. Moreover, the problem framed in ultra-distance races is challenging due to the highly dynamic scenes and the race span, i.e., runner's appearance variance, multiple scenarios, occlusive elements, etc. Recent advances in ultra-distance races CRT estimation provide high generality regarding the action recognition networks considered [5, 6]. We seek to bridge these approaches by gradually increasing the network's complexity to resolve this task. Our work explores X3D expanded insta Figure 1: **Samples of a runner’s footage at each recording point.** The runner of interest is surrounded by a green container. We analyze different X3D instances for each footage to extract the runner’s embeddings. Then, these embeddings are fed into a model to infer the CRT at a specific recording point. CRT predictions, as shown in Figure 1. The used architecture is X3D for expanding from the 2D space into the 3D space-time domain [7]. The 2D base architecture is the MobileNet. The considered expansion then progressively increases the computation by expanding only one axis at a time, i.e., frame rate, sampling rate, footage resolution, network depth, number of layers, and number of units. We have analyzed the X3D instances in a dataset collected to evaluate runner re-identification methods in real-world scenarios. The achieved results are remarkable (up to 12 minutes and a half of MAE), and they have also provided interesting insights. Contrary to other action recognition networks, X3D instances generate shorter embeddings. As a consequence, k-NN instance-based approach turns to be enough to tackle the problem efficiently. Second, a few network expansions are enough to achieve the best performance. Finally, our proposal outperforms other approaches in literature. ## 2 Related Work AQA is inherently an action recognition problem facing challenges like automatically and objectively evaluating specific actions people complete through input footage. A common approach to handling action recognition in supervised training has been to limit input data to skeleton-based approaches, e.g., detecting human body joints [8, 9]. This encourages the supervised network to infer knowledge from a metric scale that may be globally inconsistent in scenarios where the human body shifts rapidly, such as violence detection [10] and sports AQA [11]. In addition, the estimated skeleton data can frequently be noisy in realistic scenes due to occlusions or changing lighting conditions [12], particularly in ultra-distance races held in uncontrolled environments. Regarding this issue, appearance-based approaches have been used in the past to tackle AQA. Pioneer research conducted by Parmar et al. already uses C3D neural networks at a clip level for feature computations [13, 14]. More recently, several works have used the I3D network on clips not to predict a score but a score distribution [11, 15]. I3D ConvNets have also been used to tackle the runner's performance in the past [5, 6]. Contrary to these works, we aim to analyze the athletes performance by progressively expanding an X3D architecture to achieve a lightweight architecture that preserves robustness. ## 3 Method We develop a modular multi-stage pipeline for runners' CRT estimation in ultra-distance races. Its structure is illustrated in Figure 2. **Context constrain**. According to Freire et al. [6], action recognition networks require clean footage input for CRT inference. Therefore, objects (athletes, race personnel, cars) that are not interesting must be removed from the scene. Specifically, the initial block pre-processes the raw input data to focus on the runner of interest. We have applied ByteTrack [16], a multi-object tracking network, to track the runner of interest in each footage. Then, a context-constrain pre-processing yielded the scenario considered in our experiments. Given a runner \(i\) bounding box area \(BB_{i}(t,RP)\) at a given time \(t\in[0,T]\) and in a recording point \(RP\in[0,P]\), the new pre-processed footage \(F_{i}^{\prime}[RP]\) can be formally denoted as follows: \[F_{i}^{\prime}[RP]=BB_{i}(t,RP)\cup\tau(RP) \tag{1}\] Where \(\tau(RP)\) is the average number of frames to generate the clean footage where the runner appears with a still background. **Feature extraction and regression**. The input footage consisting of \(n\) frames is down-sampled Figure 2: **The proposed pipeline for regressing runner’s CRT. The designed process consists of two primary components: the footage pre-processing block, and the regression block. In the first scenario, the tracker aids by neutralizing the runner’s background activity. The latter entails the division into \(n\) small clips by down-sampling. Then the clips are sent into X3D instances for extracting features. An average pooling synthesizes the final features. The resulting tensor is the input to the regressor.** and split into \(n\) video clips (\(v_{1}\),..., \(v_{n}\)), each containing \(q\) consecutive frames representing an activity snapshot (see Figure 2). Next, each video clip _vi_ is passed through a pre-trained X3D network, resulting in a 192-dimensional feature vector. These X3D instances have been pre-trained with the Kinetics dataset [17], which comprises 400 action categories. Once all the feature vectors of the \(n\) video clips are obtained, an average pooling layer is applied to ensure that the information from each clip is given equal consideration. Finally, the extracted features are used to train a k-NN regressor, which is used to infer the CRT. **X3D instances**. We have used four X3D expanded instances that are named according to their size; extra small (X3D-XS), small (X3D-S), medium (X3D-M), and large (X3D-L). Each considered expansion is used for sequentially expanding X2D from a tiny spatial network to a spatiotemporal X3D network by performing the following operations on temporal (frame rate and sampling rate), spatial (footage resolution), width (network depth), and depth dimensions (number of layers and number of units) [7]. X3D-XS is the output after five expansion steps. The following larger model is X3D-S, defined by one backward contraction step following the seventh expansion step. The contraction step reduces the frame rate and, therefore, temporal resolution while holding the clip duration constant. The eighth and the tenth expansions generate the X3D-M and X3D-L, respectively. As seen in Table 1, X3D-M expands the spatial resolution by increasing the spatial sampling resolution of the input video. In contrast, X3D-L expands not only the spatial resolution but also the depth of the network by increasing the number of layers per residual stage. ## 4 Dataset and Experiments A key challenge in performing AQA is the lack of publicly available sporting datasets. Our pipeline needs athlete's data to regress CRT properly. While many works in this sporting domain rely on statistical data, manually gathering sufficient multimedia data is expensive. We employ a dataset derived from TGC20ReId dataset [18] provided by the authors, that contains seven-second clips at 25 fps at each recording point for each participant. The initial dataset includes annotations for nearly 600 participants across six recording points. Given the varying performances of the runners, the gap between the leaders and the last runners increases along the course as the number of active participants decreases. Consequently, a subset of 214 runners is eligible for estimating the CRT, that is, those runners that have covered the last three recording points during the dataset recording time. **Metric**. An athlete \(i\) observation \(o_{i}[RP]\) at a recording point \(RP\in[0,P]\) consists of a pre-processed footage \(F^{\prime}_{i}[RP]\) and a CRT \(\phi_{i}[RP]\). In addition, the CRT of the runners has been normalized between [0,1] using Equation 2. \[\phi^{\prime}_{i}[RP]=\frac{\phi_{i}[RP]-min(\phi_{i}[0])}{max(\phi_{i}[RP])} \tag{2}\] Our task is to identify an end-to-end regression technique that minimizes the following objective: \[min\ L(\phi^{\prime}_{i}[RP],\psi_{i}[RP])=\frac{1}{N}\sum_{j=0}^{N}|\phi^{ \prime}_{i}[RP]_{j}-\psi_{i}[RP]_{j}| \tag{3}\] where \(\psi_{i}[RP]\) represents for the runner \(i\) predicted value at a recording point \(RP\) based on seven seconds of movement observation, and \(N\) is the batch size. The following section presents the average Mean Absolute Error (MAE) across 20 repetitions of 10-fold cross-validation. On average, 410 samples are chosen for training, leaving 46 for testing. ### X3D Instances Evaluation As Section 3 points out, we have considered several X3D instances, namely X3D-XS, X3D-S, X3D-M, and X3D-L. Additionally, inspired by [6], we have combined these instances averaging them (192 embeddings) or concatenating (\(192\times\#I\) embeddings, where \(\#I\) is the number of combined instances) the last ResNet block output. Table 1 shows the achieved results by each configuration. The table is divided into three blocks, with four entries in the first and three in the rest. The first block is related to the basic X3D instances, the second is the average of different X3D instances embeddings, and the last is the average of different X3D instances concatenation. Average and concatenation experiments combine models sequentially by both, model size -first XS and S, then XS, S and M, and so on- and individual performance. From the temporal dimension perspective, each X3D-XS and X3D-S input clip is composed by four frames and a large sample rate (12 frames), whereas X3D-M and X3D-L increase the number of frames per clip (13 and 16) but reduce the sample rate by a half. Table 1 also highlights the relative importance of the model size. As can be appreciated, smaller models consistently outperform bigger models, i.e., X3D-XS is 18% better than X3D-L. Averaging model embeddings partially outperform individual approaches, but the rates are inconclusive since there is no correlation between the size and the performance. For instance, the middle combination configuration (XS+S+M) is worse than any other, bigger or smaller, configuration. Freire et al. have recently achieved their best results when concatenating I3D ConvNet embeddings [6]. Similarly, in our study, we consistently observed a substantial and consistent reduction in loss as the model size increased, highlighting the effectiveness of concatenating embeddings. Despite these findings, it is worth noting that the X3D-XS model, albeit with a slight margin, still maintains the highest success rate among all tested models. After considering various classifiers such as linear regression, random forest, gradient boosting, SVM, and a multi-layer perceptron, we have found that k-NN outperforms all of them. To ensure the optimal performance, we conducted a grid search to identify the most suitable regressor. It turns out that k-NN reported the best result. Furthermore, due to the small number of dimensions and the moderate number of observations, we have reported rates using a k-NN regression method. Consequently, an instance-based classifier is good enough to select the best embeddings for inference. In terms of minutes, a 0.010 MAE is roughly 12 minutes and a half. Since the fastest runner was recorded after 8 hours of CRT, and the last one after 20 hours of CRT, the achieved MAE is a really positive outcome. To better compare the proposed pipeline with the related work, we have included our best result in Table 2. This table summarizes the performance reported in recent literature on the mentioned dataset but also the size of the model. The table includes three major architectures, C3D, 3D ResNets considering different depths, and the I3D ConvNet. Overall, the X3D-XS model outperforms other considered prior architectures on this task. Moreover, Table 2 shows that the X3D-XS model is more than six and a half times smaller than the model with the second best result. Note that the ranking in this table shows no correlation between the model size and the model performance. ## 5 Conclusions Combining metric accuracy and lightweight models is a key challenge in AQA. We propose an X3D analysis by progressively expanding the architecture on temporal, spatial, width, and depth dimensions. Then, an instance-based classifier (k-NN) provides good performance on the generated embeddings. We show improved error reduction with each basic X3D instance alone and demonstrate successful results when concatenating instance signals. Our best result was achieved by a model almost seven times smaller and a 34% better than the best proposal in the literature. Several applications can benefit from our proposal, not only monitoring a runner's performance, but also relieving the race staff from paying exhausting continuous attention to health concerns. In addition, we hope it will assist in deploying robust and general CRT estimation models. **Acknowledgments:** This work is partially funded by the the Spanish Ministry of Science and Innovation under project PID2021-122402OB-C22, and by the ACIISI-Gobierno de Canarias and European FEDER funds under project, ProID2021010012, ULPGC Facilities Net, and Grant EIS 2021 04
2307.05602
Auxiliary Physics-Informed Neural Networks for Forward, Inverse, and Coupled Radiative Transfer Problems
In this paper, we develop and employ auxiliary physics-informed neural networks (APINNs) to solve forward, inverse, and coupled integro-differential problems of radiative transfer theory (RTE). Specifically, by focusing on the relevant slab geometry and scattering media described by different types of phase functions, we show how the proposed APINN framework enables the efficient solution of Boltzmann-type transport equations through multi-output neural networks with multiple auxiliary variables associated to the Legendre expansion terms of the considered phase functions. Furthermore, we demonstrate the successful application of APINN to the coupled radiation-conduction problem of a participating medium and find distinctive temperature profiles beyond the Fourier thermal conduction limit. Finally, we solve the inverse problem for the Schwarzschild-Milne integral equation and retrieve the single scattering albedo based solely on the knowledge of boundary data, similar to what is often available in experimental settings. The present work significantly expands the current capabilities of physics-informed neural networks for radiative transfer problems that are relevant to the design and understanding of complex scattering media and photonic structures with applications to metamaterials, biomedical imaging, thermal transport, and semiconductor device modeling.
Roberto Riganti, Luca Dal Negro
2023-07-10T20:35:08Z
http://arxiv.org/abs/2307.05602v1
Auxiliary Physics-Informed Neural Networks for Forward, Inverse, and Coupled Radiative Transfer Problems ###### Abstract In this paper, we develop and employ auxiliary physics-informed neural networks (APINNs) to solve forward, inverse, and coupled integro-differential problems of radiative transfer theory (RTE). Specifically, by focusing on the relevant slab geometry and scattering media described by different types of phase functions, we show how the proposed APINN framework enables the efficient solution of Boltzmann-type transport equations through multi-output neural networks with multiple auxiliary variables associated to the Legendre expansion terms of the considered phase functions. Furthermore, we demonstrate the successful application of APINN to the coupled radiation-conduction problem of a participating medium and find distinctive temperature profiles beyond the Fourier thermal conduction limit. Finally, we solve the inverse problem for the Schwarzschild-Milne integral equation and retrieve the single scattering albedo based solely on the knowledge of boundary data, similar to what is often available in experimental settings. The present work significantly expands the current capabilities of physics-informed neural networks for radiative transfer problems that are relevant to the design and understanding of complex scattering media and photonic structures with applications to metamaterials, biomedical imaging, thermal transport, and semiconductor device modeling. ## I Introduction Over the past few years, there has been a growing interest in developing deep learning (DL) and artificial intelligence (AI) algorithms for electromagnetic wave engineering, metamaterials design, and radiative transport problems [1; 2; 3]. Rapidly emerging approaches include training artificial neural networks (ANNs) to solve complex inverse problems, parameter estimation in structured photonic environments, and in strongly scattering media [4; 5; 6; 7; 8]. Although successfully demonstrated with respect to several inverse design problems, traditional methods remain essentially data-driven techniques and require time-consuming training steps and massive datasets [9; 10]. In order to improve on purely data-driven methods, it is essential to constrain and regularize them by leveraging the underlying physics of the investigated problems, thus relaxing the burden on training and data acquisition. Building on the firm foundation of the universal approximation theorem for multi-layer ANNs [11; 12], physics-informed neural networks (PINNs) have recently emerged as a powerful framework for the efficient solution of both forward and inverse problems mathematically described by partial differential equations (PDEs) of integer or fractional orders [13; 14; 15; 16]. The approach of PINNs has been successfully applied to a number of differential problems in engineering ranging from Navier-Stokes fluid dynamics, solid mechanics, and thermal transport [17; 18; 19]. Moreover, PINNs have shown remarkable results and noise robustness in the solution of electromagnetic inverse problems for metamaterials design, radiative transfer, imaging, and in the parameter retrieval of resonant photonic nanostructures [20; 21; 22; 23]. However, the solution of Boltzmann-type, integro-differential transport equations using PINNs still poses significant challenges due to the need to resort to numerical quadrature methods such as Gauss-Legendre or Gauss-Chebyshev for the approximation of the integral terms [24]. Such methods add computational complexity and inevitably introduce quadrature errors in the numerical solutions [25; 26; 27]. In order to eliminate such problems, a new PINN framework called auxiliary physics-informed neural networks (APINNs) was recently introduced by Yuan et al. [28]. This approach allows one to recast integro-differential equations into equivalent differential ones through the introduction of a network architecture containing additional auxiliary variables at its output, each corresponding to an integral term in the original, constrained by suitable relations. Therefore, the APINN formulation avoids the numerical approximation of integrals that are instead directly "guessed" by the network at a minimal cost, significantly improving both the numerical accuracy and computational efficiency compared to traditional PINNs. In this paper, we develop a general APINN framework for solving relevant forward and inverse integro-differential transport equations of radiative transfer theory, which is a domain of vital importance in science and engineering with applications to complex photonic devices, medical imaging, metamaterials, thermal transport, as well as astrophysics, climate dynamics, and nuclear engineering [29; 30; 31]. In particular, we address and demonstrate APINN formulations for the accurate solution of forward, inverse, and coupled radiation-conduction problems of radiative transport in the relevant slab geometry for different choices of scattering phase functions. Our paper is organized as follows: in Section II, we will provide a brief introduction to the radiative transfer equation (RTE), along with a description of the general APINN employed throughout this paper. In Section III.1, we dis cuss forward problems for different phase functions governing the scattering processes. Specifically, we present benchmarked solutions for isotropic, Rayleigh, and Henyey-Greenstein scattering phase functions that are often utilized in engineering applications [29; 30; 32]. In Section III.2, we discuss the APINN solution of a coupled radiation-conduction problem, enabling the accurate description of radiation transfer in a participating medium. Lastly, in Section III.3, we show the solution of a canonical inverse problem described by the Schwarzschild-Milne integral equation, and we show that the radiative intensity solution and the single scattering parameters are accurately retrieved solely based on intensity data at the boundaries of the slab. Our work shows that APINNs possess the flexibility, accuracy, and robustness required to become a powerful tool for inverse scattering and thermal transport modeling beyond the limitations of Fourier theory. Therefore, this work expands significantly upon the current capabilities and range of applications of PINNs methods and paves the way to the study of higher-dimensional transport problems in strongly scattering media with applications to nanophotonics, metamaterials, biomedical imaging, and optoelectronic device modeling. ## II Apinns for radiative transfer problems The framework of radiative transfer theory for the study of complex scattering media was originally developed in astrophysics as a way to quantitatively describe the radiative equilibrium in interstellar clouds, planetary and stellar atmospheres [33]. Radiative transfer theory has found a very wide range of applications beyond astrophysics, including biomedical optics [32], atmospheric science [31], radiation hydrodynamics [34; 35] and remote sensing [36; 37]. For example, the propagation of light through fogs and clouds, white pains or paper, milky and turbid liquids, human tissue, and the brain can be adequately described by the classical theory of radiation transfer that we discuss in this paper using APINNs. The radiation transfer theory is founded upon the RTE, which is a Boltzmann-type integro-differential equation expressing the detailed energy balance for the propagation of directed energy flow, or radiance, through a multiply scattering discrete random medium. For scalar waves in three spatial dimensions the RTE can be written as follows: \[\begin{split}\frac{1}{c}\frac{\partial I(\mathbf{r},\hat{s},t)}{ \partial t}&=-\hat{s}\cdot\nabla I(\mathbf{r},\hat{s},t)-(\kappa+ \sigma)I(\mathbf{r},\hat{s},t)+\\ \sigma\int_{4\pi}I(\mathbf{r},\hat{s}^{\prime},t)p(\hat{s}^{\prime}, \hat{s})d\Omega^{\prime}+S(\mathbf{r},\hat{s},t)\end{split} \tag{1}\] where \(\kappa\) and \(\sigma\) are the absorption and scattering coefficients, respectively. Here \(S(\mathbf{r},\hat{s},t)\) denotes a generic source term and \(p(\hat{s}^{\prime},\hat{s})\) is the phase function describing the angular distribution of the scattering process. Alternatively, after introducing the optical thickness \(\tau\) and the single scattering albedo \(\omega\) as: \[\tau(S)=\int_{S^{\prime}=0}^{S}\beta(S^{\prime})dS^{\prime} =\int_{S^{\prime}=0}^{S}[\kappa(S^{\prime})+\sigma(S^{\prime})]dS^{\prime} \tag{2}\] \[\omega=\frac{\sigma}{\beta}=\frac{\sigma}{\kappa+\sigma} \tag{3}\] one can rewrite Eq. 1 in the alternative form: \[\begin{split}\frac{1}{\beta c}\frac{\partial I(\mathbf{\tau},\hat{ s},t)}{\partial t}&=-\hat{s}\cdot\nabla_{\tau}I(\mathbf{\tau},\hat{s},t)-I( \mathbf{\tau},\hat{s},t)+\\ \omega\int_{4\pi}I(\mathbf{\tau},\hat{s}^{\prime},t)p(\hat{s}^{ \prime},\hat{s})d\Omega^{\prime}+S(\mathbf{\tau},\hat{s},t)\end{split} \tag{4}\] which is the RTE in its standard form. For a detailed discussion and derivation of the RTE, we refer the reader to references [29; 30; 33]. In essence, the RTE states that a directed beam of light in a uniform random medium loses energy through divergence and extinction, including both absorption and scattering away from the beam (i.e., out-scattering contributions), and it gains energy from radiation sources, fluorescence or scattering events that redirect it towards the beam (i.e., in-scattering contributions). In the standard formulation, wave interference effects, polarization and non-linearity in the medium are neglected. Radiative transfer theories for vector waves have also been developed but are outside the scope of this work and more details on these subjects can be found in references [31; 37]. Even for the relevant slab geometry, the RTE introduced above is generally very difficult to solve [38]. Analytic solutions only exist for very simple cases while in many realistic situations, numerical methods such as Monte Carlo transport simulations are usually employed [39]. For this reason, the RTE is often approximated, under suitable conditions, by the simpler but less accurate diffusion equation [32]. In our paper, we developed APINNs to obtain the forward and inverse solution of the scalar RTE in the steady-state and for different choices of phase functions. However, the developed framework can be naturally extended to time-dependent and vector RTE problems, anisotropic phase functions, and arbitrary nonlinear responses. All the implementations of the APINN algorithms developed in this paper are obtained in the powerful TensorFlow environment [40]. The general APINN network utilized to solve forward and inverse RTE problems in the slab geometry is illustrated in Fig. 1. We considered a fully connected neural network Figure 1: Schematics of the APINN solving the RTE problem in a slab. The FCNN has \(N+1\) outputs where \(N\) is the number of auxiliary variables \(v_{i}\) required in the Legendre polynomial expansion of the scattering phase function. The outputs of the network are then used to satisfy the PDE, initial conditions (ICs), and boundary conditions (BCs) of the differential equation, which are then combined into the loss function \(\mathcal{L}\). During the training process, the loss function is minimized until it passes a threshold \(\sigma\). (FCNN) with input vector \(\mathbf{x}=(\mathbf{\tau},\mathbf{\mu})\) with randomly distributed values of the optical thickness \(\tau\) and \(\mu=\cos\theta\) over a two-dimensional spatial-angular domain \(\Omega\) and output that is the predicted surrogate \(\hat{I}(\mathbf{\mu},\mathbf{\tau};\mathbf{\tilde{\theta}})\) of the RTE solution \(I(\mathbf{\mu},\mathbf{\tau};\mathbf{\theta})\). Here, \(\mathbf{\theta}\) denotes the angle of the directed energy flow with the axis \(z\) perpendicular slab's surface and \(\mathbf{\tilde{\theta}}\) is the vector of weights and biases of our FCNN. In addition, the FCNN outputs \(n\) auxiliary variables \(v_{i}(\mathbf{\mu},\mathbf{\tau};\mathbf{\tilde{\theta}})\), each corresponding to an integral expansion term in the RTE. The outputs of the APINN are then used to compute, by means of automatic differentiation (AD), the derivatives of \(\hat{I}(\mathbf{\mu},\mathbf{\tau};\mathbf{\tilde{\theta}})\) and \(v_{i}(\mathbf{\mu},\mathbf{\tau};\mathbf{\tilde{\theta}})\), along with the PDE, initial conditions, and boundary conditions, depending on the nature of the problem. Each calculated value is then combined into a term of the loss function \(\mathcal{L}(\mathbf{\tilde{\theta}})\) defined as: \[\begin{split}\mathcal{L}(\mathbf{\tilde{\theta}})=& \mathcal{L}_{int}(\mathbf{\tilde{\theta}};\mathcal{N}_{int})+\mathcal{L}_{b}( \mathbf{\tilde{\theta}};\mathcal{N}_{b})\\ &+\mathcal{L}_{aux}(\mathbf{\tilde{\theta}};\mathcal{N}_{aux})+ \lambda\sum_{i}\mathbf{\tilde{\theta}}_{i}^{2}\end{split} \tag{5}\] In the expression above, \[\mathcal{L}_{int}(\mathbf{\tilde{\theta}};\mathcal{N}_{int})=\frac{1}{|\mathcal{N }_{int}|}\sum_{\mathbf{x}\in\mathcal{\mathcal{\mathcal{\mathcal{\mathcal{\mathcal{ \mathcal{\mathcal{\mathcal{\mathcal{\mathcal{\mathcal{\mathcal{\mathcal{\mathcal{ \mathcal{\mathcal{\mathcal{ \mathcal{ \mathcal{ \mathcal{ }}}}}}}}}}}}}} \left|\int\left(\mathbf{x};\mathbf{\hat{I}}} \frac{\partial\mathbf{\hat{I}}{\partial\mathbf{\tau}}}{v_{0},\ldots,v_{n}}\right) \right|\right|^{2} \tag{6}\] denotes the loss term calculated in the interior domain \(\Omega\) and \[\mathcal{L}_{b}(\mathbf{\tilde{\theta}};\mathcal{N}_{b})=\frac{1}{|\mathcal{N}_ {b}|}\sum_{\mathbf{x}\in\mathcal{\mathcal{\mathcal{\mathcal{\mathcal{\mathcal{ \mathcal{\mathcal{\mathcal{\mathcal{\mathcal{\mathcal{\mathcal{\mathcal{\mathcal{ \mathcal{\mathcal{\mathcal{\mathcal{ \mathcal{ \mathcal{ }}}}}}}}}}}}}}} \left|\mathbf{\mathbf{\mathbf{\mathbf{\mathbf{\mathbf{\mathbf{\mathbf{\mathbf{\mathbf{\mathbf{\mathbf{ \mathbf{\mathbf{\mathbf{\mathbf{\mathbf{\mathbf{\mathbf{\mathbf{\mathbf{\ which is constrained by the following system: \[\mu\frac{dI}{d\tau}+I-\frac{\omega}{2}v(1)=0 \tag{11a}\] \[v(\mu;\tau)=\int_{-1}^{\mu}I(\mu^{\prime};\tau)d\mu^{\prime}\] (11b) \[v(-1;\tau)=0,\quad\frac{dv}{d\mu}(\mu;\tau)=I(\tau,\mu)\] We then train the APINN to solve the problem for different values of the albedo \(\omega\) varying from 0.2 to 1.0. Table 2 shows the speed and accuracy of our APINN implementation in solving the Milne problem. In the large scattering limit of \(\omega\geq 0.9\), APINN minimized the loss function with values that are two orders of magnitude lower and for a fraction of the time than for the equivalent geometry displayed in Ref. [27], where a quadrature method was employed. Two representative APINN solutions for the spatial-angular distributions of the radiation intensity for \(\tau_{\max}=1.0\) are displayed in Fig. 2 (a) and (b). To benchmark our solutions using the tables calculated by Van de Hulst's in Ref. [42], we computed the zeroth moment or point-direction gain \(G(\tau)\) of the radiative intensity, which is defined as [29; 30; 33; 42]: \[G(\tau)=\int_{-1}^{1}I(\tau,\mu)d\mu \tag{12}\] Fig. 2 (c) displays the validation data of \(G(\tau)\) calculated by Van de Hulst and the solution from our network, showing an excellent agreement achieved by the APINN framework. This is further confirmed by the average relative error between the two solutions displayed in the last column of Table 2. Fig. 2 (d) shows a comparison between the APINN and the standard PINN quadrature loss function to solve the same problem, as implemented in Ref. [27]. In this figure, we display the loss function versus the number of epochs for the three largest scattering values of \(\omega\). We can immediately notice that the quadrature solution is heavily affected in its performance by the scattering strength, and the L-BFGS-B solver terminates the training early because the loss function has already saturated to its minimum value and is not decreasing further. In contrast, the APINN's loss function monotonically decreases independently of \(\omega\). This result confirms the robustness, flexibility, and accuracy of the APINN framework in solving transport problems for strongly scattering media. In a variety of engineering applications, however, the material's response is not isotropic. Therefore, in Section III.1.2, we employ the APINN framework to solve the RTE in a slab with an anisotropic Rayleigh scattering phase function. #### ii.1.2 The Rayleigh scattering phase function The Rayleigh phase function is employed to study anisotropic light scattering processes in various fields, from Figure 2: (a) and (b) APINN solutions for the Milne equation in a slab, with the single scattering albedo set to \(\omega=1\) and \(\omega=0.2\), respectively. \(\omega\) sets the strength of the scattering term in the PDE. (c) Validation of the APINN solutions using Van de Hulst’s data results for the point direction gain \(G(\tau)\). (d) Comparison of the APINN training performance in minimizing the objective loss function with the quadrature solution: the APINN method consistently trains independently of scattering strength, whereas the quadrature method’s performance worsens as the scattering strength, represented by \(\omega\), increases. optics to astronomy [33]. The phase function reads: \[p(\cos\theta)=\frac{3}{4}(1+\cos\theta^{2}) \tag{13}\] and because the scattering from spherically symmetric particles is cylindrically symmetric with respect to the incoming direction, this symmetry holds after averaging over all possible orientations. Therefore, in these situations, the phase function depends on \(\phi-\phi^{\prime}\) and one can compute this average resulting in the projected phase function [41]: \[p_{0}(\mu,\mu^{\prime})=\int\frac{d\phi}{2\pi}\frac{d\phi^{\prime}}{2\pi}p(\mu, \phi;\mu^{\prime},\phi^{\prime}) \tag{14}\] Using the equality \(\mu=\cos\Theta=\mathbf{n}\cdot\mathbf{n}^{\prime}=\sin\!\theta\!\sin\!\theta^{\prime} \!\cos(\phi-\phi^{\prime})+\!\cos\!\theta\!\cos\!\theta^{\prime}\) one obtains: \[p_{0}(\mu,\mu^{\prime})=\frac{3}{8}(3-\mu^{2}-\mu^{\prime 2}+3\mu^{2}\mu^{ \prime 2}) \tag{15}\] To facilitate the calculations and the auxiliary variable formulation of the APINN framework, one typically considers the expansion of the scattering phase function in Legendre polynomials: \[\Phi(\mu,\mu^{\prime})=\sum_{\ell=0}^{\infty}w_{\ell}P_{\ell}(\mu)P_{\ell}( \mu^{\prime}) \tag{16}\] Note that, for the Rayleigh phase function, the only nonzero \(w_{\ell}\) terms are \(w_{0}=1.0\) and \(w_{2}=0.1\). Therefore, Eq. 9 in a slab with Rayleigh scattering becomes \[\mu\frac{dI(\tau,\mu)}{d\tau}+I(\tau,\mu)=\frac{\omega}{2}\int_{-1}^{1}I(\tau,\mu^{\prime})\sum_{\ell=0}^{\infty}w_{\ell}P_{\ell}(\mu)P_{\ell}(\mu^{\prime} )d\mu^{\prime} \tag{17}\] and after rearranging terms and truncating the series expansion at \(\ell=2\) we get: \[\mu\frac{dI(\tau,\mu)}{d\tau}+I(\tau,\mu)=\frac{\omega}{2}\Big{[} w_{0}P_{0}(\mu)\int_{-1}^{1}I(\tau,\mu^{\prime})P_{0}(\mu^{\prime})d \mu^{\prime}\] \[+w_{2}P_{2}(\mu)\int_{-1}^{1}I(\tau,\mu^{\prime})P_{2}(\mu^{\prime })d\mu^{\prime}\Big{]} \tag{18}\] Finally, we recast the problem by adding two auxiliary variables to the network with their respective constraints as follows: \[\mu\frac{dI(\tau,\mu)}{d\tau}+I(\tau,\mu)=\frac{\omega}{2}\left[w_{0}P_{0}( \mu)v_{0}(1)+w_{2}P_{2}(\mu)v_{2}(1)\right] \tag{19a}\] \[v_{0}(\mu;\tau)=\int_{-1}^{\mu}I(\tau,\mu^{\prime})P_{0}(\mu^{ \prime})d\mu^{\prime}\] (19b) \[v_{0}(-1;\tau)=0,\quad\frac{dv_{0}}{d\mu}(\mu;\tau)=I(\tau,\mu)P_{0}(\mu)\] \[v_{2}(\mu;\tau)=\int_{-1}^{\mu}I(\tau,\mu^{\prime})P_{2}(\mu^{ \prime})d\mu^{\prime}\] (19c) \[v_{2}(-1;\tau)=0,\quad\frac{dv_{2}}{d\mu}(\mu;\tau)=I(\tau,\mu)P_{2}(\mu)\] Due to the lack of benchmark solutions for Rayleigh scattering in a slab, we decided to consider a physical system similar to the one studied by Mishra and Molinaro in Ref. [27], namely the case where the single scattering albedo depends on the optical thickness \(\tau\) of the material. In this case, Eq. 19a becomes \[\frac{dI(\tau,\mu)}{d\tau}+I(\tau,\mu)=\frac{\omega(\tau)}{2} \Big{[} w_{0}P_{0}(\mu)v_{0}(1;\tau) \tag{20}\] \[+w_{2}P_{2}(\mu)v_{2}(1;\tau)\Big{]}\] To solve this problem, we train APINN with the parameters specified in Table 1, using 40 neurons per layer. The training for this solution took 12 minutes, and the final value of the loss function \(\mathcal{L}\) was \(10^{-6}\), demonstrating the adaptivity and flexibility of APINN in solving anisotropic scattering problems. Fig. 3(a) displays the APINN radiative intensity solution as a function of \(\mu\) and the optical thickness. This result highlights the flexibility of APINN in finding the solution to an analytically intractable problem [27]. In turn, this motivates us to study the RTE with strongly anisotropic scattering properties modeled by the Henyey-Greenstein (HG) phase function. #### ii.2.3 The Henyey-Greenstein phase function Here we consider the forward RTE problem in the slab with the Henyey-Greenstein (HG) phase function governing the scattering processes. The HG phase function finds applications in astrophysics, atmospheric optics, and biomedical imaging, and it depends on both the cosine of the incident angle and the asymmetry factor \(g\in[0,1]\) that appears in the equation below [30; 43; 44; 29; 45]: \[p(\mu,g)=\frac{1-g^{2}}{(1-2g\mu+g^{2})^{3/2}} \tag{21}\] where \(\mu=\cos\!\theta\). In the limit of \(g\to 0\), the HG phase function reduces to isotropic scattering, while in the limit of \(g\to 1\), HG describes strongly anisotropic scattering events. As for the Rayleigh phase function, the HG phase function can be rewritten using the Legendre polynomials expansion in Eq. (16). However, unlike the Rayleigh case, the Legendre \begin{table} \begin{tabular}{c c c c} \(\omega\) & Training time & Loss & Avg. Rel. Error \\ \hline 0.2 & 3 min & \(7\times 10^{-6}\) & \(7\times 10^{-2}\) \\ 0.6 & 10 min & \(5\times 10^{-6}\) & \(8\times 10^{-2}\) \\ 0.9 & 10 min & \(3\times 10^{-6}\) & \(7\times 10^{-2}\) \\ 0.99 & 10 min & \(3\times 10^{-6}\) & \(7\times 10^{-2}\) \\ 1.0 & 10 min & \(3\times 10^{-6}\) & \(7\times 10^{-2}\) \\ \end{tabular} \end{table} Table 2: APINN training information for the Milne equation in a slab. The last column shows the average relative error between the network solution of \(G(\tau)\) and Van de Hulst’s results. expansion converges more slowly, and additional terms need to be included to achieve accurate numerical results: \[\begin{split}\mu\frac{dI(\tau,\mu)}{d\tau}+I(\tau,\mu)=\frac{\omega}{ 2}\Big{[}& w_{0}P_{0}(\mu)\int_{-1}^{1}I(\tau,\mu^{\prime})P_{0}(\mu^{ \prime})d\mu^{\prime}\\ &+w_{1}P_{1}(\mu)\int_{-1}^{1}I(\tau,\mu^{\prime})P_{1}(\mu^{ \prime})d\mu^{\prime}\\ &+\ldots\\ &+w_{n}P_{n}(\mu)\int_{-1}^{1}I(\tau,\mu^{\prime})P_{n}(\mu^{ \prime})d\mu^{\prime}\Big{]}\end{split} \tag{22}\] where: \[w_{\ell}=(2n+1)g^{n} \tag{23}\] In our numerical studies, we chose to benchmark the RTE with HG phase function, \(g=0.5\), which allowed us to utilize Van de Hulst's tables as validation data [46]. The polynomial expansion of the phase function was truncated after ten terms, introducing ten auxiliary variables and their corresponding constraint conditions in the simulation: \[\begin{split}&\mu\frac{dI(\tau,\mu)}{d\tau}+I(\tau,\mu)=\frac{ \omega}{2}\Big{[}w_{0}P_{0}(\mu)v_{0}(1;\tau)\\ &+\cdots+w_{10}P_{10}(\mu)v_{10}(1;\tau)\Big{]}\\ & v_{0}(\mu;\tau)=\int_{-1}^{\mu}I(\tau,\mu^{\prime})P_{0}(\mu^{ \prime})d\mu^{\prime}\\ & v_{0}(-1;\tau)=0,\quad\frac{dv_{0}}{d\mu}(\mu;\tau)=I(\tau,\mu) P_{0}(\mu)\\ &\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad \qquad\ldots\\ & v_{10}(\mu;\tau)=\int_{-1}^{\mu}I(\tau,\mu^{\prime})P_{10}(\mu^{ \prime})d\mu^{\prime}\\ & v_{10}(-1;\tau)=0,\quad\frac{dv_{10}}{d\mu}(\mu;\tau)=I(\tau, \mu)P_{10}(\mu)\end{split} \tag{24c}\] Table 3 provides a summary of the APINN training for this problem. Considering the larger number of auxiliary variables, we trained using 80 neurons per layer instead of 40. Similarly to the isotropic and Rayleigh cases, the loss function is minimized to extremely low values with a minor trade-off in speed due to the larger number of auxiliary variables in the system, as the second and third columns of Table 3 demonstrate. The accuracy of these results, displayed in the last column of Table 3, confirms the versatility of the APINN framework, which excels in solving even strong anisotropic scattering problems. Fig. 3 (c) shows a representative solution of the radiation intensity when \(\omega=1.0\), and Fig. 3 (b) displays the benchmarked solutions for this problem by comparing the integrated radiative intensity \(G(\tau)\) calculated from the APINN network with the Van de Hulst's data. These results open the doors for multiple biomedical, metamaterials, and nano-optics applications where the HG phase function is often utilized to model realistic scattering processes [43, 44, 45]. ### The coupled radiation-conduction problem of a participating medium We now apply our APINN method to the solution of a coupled problem in radiative transfer theory. Specifically, we con Figure 3: (a) APINN solution for the RTE with Rayleigh scattering phase function, where the single scattering albedo \(\omega(\tau)\) depends on the optical thickness. (b) Validation of the APINN solutions for the HG phase function with \(g=0.5\) using Van de Hulst’s data results for the point direction gain \(G(\tau)\). (c) Representative APINN solution for the RTE in a slab with HG scattering phase function, \(g=0.5\), \(\omega=1.0\). \begin{table} \begin{tabular}{c c c c} \(\omega\) & Training time & Loss & Avg. Rel. Error \\ \hline 0.2 & 49 min & \(8\times 10^{-6}\) & \(3\times 10^{-2}\) \\ 0.6 & 50 min & \(2\times 10^{-5}\) & \(2\times 10^{-2}\) \\ 0.9 & 65 min & \(3\times 10^{-5}\) & \(6\times 10^{-3}\) \\ 0.99 & 65 min & \(6\times 10^{-5}\) & \(2\times 10^{-3}\) \\ 1.0 & 65 min & \(5\times 10^{-5}\) & \(1\times 10^{-3}\) \\ \end{tabular} \end{table} Table 3: APINN training information for the HG phase function in a slab, \(g=0.5\). The last column shows the average relative error between the network solution of \(G(\tau)\) and Van de Hulst’s table. sider a conducting and participating slab that couples to the radiation hitting the boundary in the steady-state. Such problems have been analyzed extensively in the literature [47; 48; 49; 50; 51; 52; 53; 54; 55; 56], but, to our knowledge, have never been solved using physics-informed neural networks. Here, we use the APINN framework to analyze this problem, where the slab's temperature profile is governed by a Poisson-like equation with a coupling term to the RTE [51]. We will further analyze how the conduction-radiation parameter \(N_{CR}\) affects the traditional Fourier temperature solution in the steady-state when significant temperature differences are imposed at the boundaries of the slab. The conduction-radiation parameter \(N_{CR}\) measures the ratio of conductive to radiative heat contributions in a given medium, and it is defined as [29]: \[N_{CR}=\frac{k\beta}{4k_{B}T^{3}}=\frac{k(\kappa+\sigma)}{4k_{B}T^{3}} \tag{25}\] For the simulations that follow, we chose to study coupled systems where \(N_{CR}\) varies from 10 (for \(N\rightarrow\infty\), we get the Fourier limit) to 0.001 (for \(N\to 0\), radiative processes dominate). We consider the heat transfer problem due to conduction and radiation in a participating medium presented by Ref. [51] governed by the two following coupled integro-differential equations: \[\frac{d^{2}\Theta}{d\tau^{2}}-\frac{(1-\omega)}{N_{CR}}\left[ \Theta^{4}(\tau)-\frac{1}{2}G(\tau)\right]=0 \tag{26}\] \[\mu\frac{dI(\tau,\mu)}{d\tau}+I(\tau,\mu)=H[\Theta(\tau)]+\frac{ \omega}{2}\int_{-1}^{1}I(\tau,\mu^{\prime})\Phi(\mu,\mu^{\prime})d\mu^{\prime}\] (27) \[\text{for}\quad 0<\tau<1,\quad-1\leq\mu\leq 1,\quad\Phi(\mu,\mu^{ \prime})=1,\quad\omega=0.9\] where the temperature is being modeled by the normalized adimensional quantity \(\Theta=T/T_{1}\). The coupling terms are: \[G(\tau)=\int_{-1}^{1}I(\tau,\mu)d\mu,\quad H[\Theta(\tau)]=(1-\omega)\Theta^{4} \tag{28}\] and \(G(\tau)\) is the zeroth moment of the intensity \(I(\tau,\mu)\). The boundary conditions are: \[I(0,\mu)=1,\mu\in(0,1],\quad\text{and}\quad I(1,\mu)=0,\mu\in[-1,0) \tag{29}\] \[\Theta(0)=1\quad\text{and}\quad\Theta(1)=T_{2}/T_{1} \tag{30}\] Since the problem involves two undetermined coupled functions, we modified the architecture of the APINN framework. The changes are illustrated in Fig. 4: the input parameters are passed to the radiative intensity network \(\hat{I}(\tau,\mu)\) with auxiliary variables as for the uncoupled cases discussed so far, but the spatial variable \(\tau\) is also used to train simultaneously the adimensional temperature network \(\hat{\Theta}(\tau)\). The coupled problem recasted in the APINN formalism reads: \[\frac{d^{2}\Theta}{d\tau^{2}}-\frac{(1-\omega)}{N_{CR}}\left[ \Theta^{4}(\tau)-\frac{1}{2}v(1;\tau)\right]=0 \tag{31}\] \[\mu\frac{dI(\tau,\mu)}{d\tau}+I(\tau,\mu)=H[\Theta(\tau)]+\frac{ \omega}{2}v(1;\tau) \tag{32}\] where we introduced the auxiliary variable \(v(\mu;\tau)\) and its corresponding conditions like in Eq. (11): \[v(\mu;\tau)=\int_{-1}^{\mu}I(\mu^{\prime};\tau)d\mu^{\prime}, \tag{33a}\] \[v(-1;\tau)=0,\quad\frac{dv}{d\mu}(\mu;\tau)=I(\tau,\mu) \tag{33b}\] By means of automatic differentiation, the outputs of the two networks are then used to compute the required PDE conditions, initial conditions, and boundary conditions, which are then incorporated into the coupled loss function: \[\mathcal{L}=\mathcal{L}_{I(\tau,\mu)}+\mathcal{L}_{\hat{\Theta}(\tau)} \tag{34}\] To solve this problem, we coupled the APINN network for the radiative intensity with a PINN estimating the dimensionless Figure 4: Schematics of the APINN solving the coupled radiation-conduction problem in a slab. Here, two FCNNs representing the intensity of radiation \(\hat{I}(\mu,\tau)\) and temperature \(\hat{\Theta}(\tau)\) are combined in a loss function that minimizes the PDE, initial conditions (ICs), and boundary conditions (BCs) of two coupled partial differential equations. The training process minimizes the loss function \(\mathcal{L}\) until it passes a threshold \(\sigma\). \begin{table} \begin{tabular}{c c c c} \(\Delta\Theta\) & \(N_{CR}\) & Training time & \(\mathcal{L}_{I(\tau,\mu)}\) & \(\mathcal{L}_{\hat{\Theta}(\tau)}\) \\ \hline \multirow{4}{*}{150K} & 10 & 18 min & \(6\times 10^{-4}\) & \(6\times 10^{-6}\) \\ & 0.1 & 18 min & \(5\times 10^{-4}\) & \(5\times 10^{-7}\) \\ & 0.01 & 18 min & \(5\times 10^{-4}\) & \(7\times 10^{-6}\) \\ & 0.001 & 18 min & \(5\times 10^{-4}\) & \(8\times 10^{-5}\) \\ \hline \multirow{4}{*}{270K} & 10 & 33 min & \(5\times 10^{-4}\) & \(2\times 10^{-5}\) \\ & 0.1 & 30 min & \(5\times 10^{-4}\) & \(2\times 10^{-6}\) \\ \cline{1-1} & 0.01 & 31 min & \(5\times 10^{-4}\) & \(6\times 10^{-6}\) \\ \cline{1-1} & 0.001 & 30 min & \(5\times 10^{-4}\) & \(4\times 10^{-5}\) \\ \end{tabular} \end{table} Table 4: APINN Training information for radiative-conductive coupled problem in a slab. temperature \(\Theta(\tau)\), with parameters according to Table 1. Fig. 5 shows the solutions for the coupled problem when two different temperature jumps are imposed at the rightmost boundary. Fig. 5(a) displays a \(\Delta\Theta=150K\), whereas Fig. 5(b) a \(\Delta\Theta=270K\). Moreover, we analyze the dimensionless temperature behavior when the conduction-radiation parameter \(N_{CR}\) decreases, as previously investigated in Refs. [29; 30]. It is important to realize that both panels in Fig. 5 display a beyond-Fourier behavior as \(N_{CR}\) decreases, demonstrating that the temperature profile is significantly affected by radiative scattering phenomena. Lastly, Table 4 presents some relevant information regarding the APINN training. We note that, even for the coupled case, the APINN successfully minimizes both the temperature loss function \(\mathcal{L}_{\hat{\Theta}(\tau)}\) and the radiative intensity loss function \(\mathcal{L}_{\hat{\Theta}(\tau)}\) independently of the parameter \(N_{CR}\). ### Inverse problem: retrieval of the albedo from the boundary data Finally, we present here the solution of an inverse problem of radiative transfer theory where we employ APINN to retrieve simultaneously the forward solution of the intensity \(I(\tau,\mu)\) and the single scattering albedo \(\omega\). We do not, however, introduce synthetic data everywhere in the domain, as it has been done previously in the literature [27], but we limit ourselves to introducing two data points representing the integrated intensity \(G(\tau)\) at the edges of the slab, simulating a lab environment with two detectors capturing integrated radiation entering and exiting the slab, respectively. The reason to present an inverse problem in such a fashion is to demonstrate the full potential and capabilities of physics-informed neural networks that, with no additional overhead and computing power, can solve a forward and parameter retrieval problem simultaneously. We thus modify the Schwarzschild-Milne equation for a slab discussed in an earlier section. In particular, Eq. (11) is changed to include the unknown albedo parameter \(\omega_{\theta}\): \[\mu\frac{dI}{d\tau}+I-\frac{\omega_{\theta}}{2}v(1)=0 \tag{35}\] and the loss function in Eq. (5) is modified to include the two synthetic detector data points at the boundaries of the slab: \[\begin{split}\mathcal{L}(\mathbf{\theta},\mathbf{\omega}_{\theta})& =\mathcal{L}_{int}(\mathbf{\theta},\mathbf{\omega}_{\theta};\mathcal{N}_{ int})+\mathcal{L}_{b}(\mathbf{\theta},\mathbf{\omega}_{\theta};\mathcal{N}_{b})\\ &+\mathcal{L}_{aux}(\mathbf{\theta},\mathbf{\omega}_{\theta};\mathcal{ N}_{aux})+\mathcal{L}_{inv}(\mathbf{\theta},\mathbf{\omega}_{\theta};\mathcal{N}_{im}) \end{split} \tag{36}\] where \[\begin{split}&\mathcal{L}_{inv}(\mathbf{\theta},\mathbf{\omega}_{\theta };\mathcal{N}_{inv})=\\ &\frac{1}{|\mathcal{N}_{im}|}\sum_{(\tau,\mu)\in\mathcal{N}_{im} }\left|\left|\int_{-1}^{1}\hat{I}(\tau,\mu)d\mu-G(\tau)\right|\right|^{2}=\\ &\frac{1}{2}\left(\left|\left|\int_{-1}^{1}\hat{I}(0,\mu)d\mu-G (0)\right|\right|^{2}+\left|\left|\int_{-1}^{1}\hat{I}(1,\mu)d\mu-G(1)\right| \right|^{2}\right)\end{split} \tag{37}\] Fig. 6 displays the fast convergence of the retrieved APINN parameter \(\omega_{\theta}\) to the actual value \(\omega\). Each line corresponds to a different APINN training procedure during which the only data points added were \(G(0)\) and \(G(1)\) obtained from the Van de Hulst's tables [42], and used to minimize \(\mathcal{L}_{inv}\) during the training process. Despite the loss term with two data points was not weighted differently from the interior or boundary ones, APINN achieved a precise inversion of the parameter of interest. In fact, as displayed in Table 5, the loss function converges independently of the albedo \(\omega\) and with great precision, as displayed by the relative error between the known Figure 5: (a) and (b) APINN results displaying the temperature profile in the conductive participating medium of Eq. 33 for a temperature jump of 150K and 270K, respectively. The simulations have been conducted for four sets of values of the conduction-radiation parameter \(N_{CR}\): as \(N_{CR}\) decreases, the solution changes from the well-known Fourier temperature profile to a beyond-Fourier solution characterized by a dominant scattering contribution. Figure 6: Results showing the convergence of each value of different trainable variables \(\omega_{\theta}\) for separate APINN simulations, each of which where fed different boundary values \(G(\tau)\) for the inverse problem, while all the other parameters and PDE conditions stayed the same. As the picture shows, the neural network provided very accurate results across all simulations, training \(\omega_{\theta}\) to the true albedo value \(\omega\), especially for high scattering values. albedo and the predicted APINN albedo \(\omega_{\theta}\) shown in the last column of Table 5. Therefore, APINN retrieved the correct parameter of interest \(\omega_{\theta}\) when only two points were added during the training process. ## IV Conclusions Throughout this paper, we have described different applications of APINN for solving the radiative transfer equation, which is a Boltzmann-type transport equation. We successfully solved forward problems in a slab with both isotropic and anisotropic scattering phase functions and irrespective of the albedo. The results presented improved upon previous attempts to use physics-informed neural networks for solving the RTE in both accuracy and speed [27]. Furthermore, we presented the solution of the first coupled radiation-conduction problem in a participating medium using the APINN framework and we showed that the loss functions of coupled neural networks quickly converged to a low minimum value below \(10^{-5}\). Our findings open the possibility to utilize APINN to analyze higher dimensional systems and discover more interesting physics with applications to metamaterials and semiconductor device modeling. Finally, we solved an inverse problem following a setup that replicates an experimental setting with data points at the boundary of the system. It will be interesting in future studies to build on the APINN platform to address higher dimensional coupled, inverse coupled, and strongly scattering forward systems with applications to biomedical imaging, nanophotonics, metamaterials, and thermal modeling of semiconductor devices. ###### Acknowledgements. We acknowledge the support from the U.S. Army Research Office, RF-Center managed by Dr. J. Qiu (Grant #W911NF-22-2-0158). We thank professors Mike Kirby, Akil Narayan, and Shandian Zhe for useful discussions on this topic.
2310.17187
Explainable Gated Bayesian Recurrent Neural Network for Non-Markov State Estimation
The optimality of Bayesian filtering relies on the completeness of prior models, while deep learning holds a distinct advantage in learning models from offline data. Nevertheless, the current fusion of these two methodologies remains largely ad hoc, lacking a theoretical foundation. This paper presents a novel solution, namely an explainable gated Bayesian recurrent neural network specifically designed to state estimation under model mismatches. Firstly, we transform the non-Markov state-space model into an equivalent first-order Markov model with memory. It is a generalized transformation that overcomes the limitations of the first-order Markov property and enables recursive filtering. Secondly, by deriving a data-assisted joint state-memory-mismatch Bayesian filtering, we design a Bayesian gated framework that includes a memory update gate for capturing the temporal regularities in state evolution, a state prediction gate with the evolution mismatch compensation, and a state update gate with the observation mismatch compensation. The Gaussian approximation implementation of the filtering process within the gated framework is derived, taking into account the computational efficiency. Finally, the corresponding internal neural network structures and end-to-end training methods are designed. The Bayesian filtering theory enhances the interpretability of the proposed gated network, enabling the effective integration of offline data and prior models within functionally explicit gated units. In comprehensive experiments, including simulations and real-world datasets, the proposed gated network demonstrates superior estimation performance compared to benchmark filters and state-of-the-art deep learning filtering methods.
Shi Yan, Yan Liang, Le Zheng, Mingyang Fan, Xiaoxu Wang, Binglu Wang
2023-10-26T06:46:43Z
http://arxiv.org/abs/2310.17187v2
# Multi-level Gated Bayesian Recurrent Neural Network for State Estimation ###### Abstract The optimality of Bayesian filtering relies on the completeness of prior models, while deep learning holds a distinct advantage in learning models from offline data. Nevertheless, the current fusion of these two methodologies remains largely ad hoc, lacking a theoretical foundation. This paper presents a novel solution, namely a multi-level gated Bayesian recurrent neural network specifically designed to state estimation under model mismatches. Firstly, we transform the non-Markov state-space model into an equivalent first-order Markov model with memory. It is a generalized transformation that overcomes the limitations of the first-order Markov property and enables recursive filtering. Secondly, by deriving a data-assisted joint state-memory-mismatch Bayesian filtering, we design a Bayesian multi-level gated framework that includes a memory update gate for capturing the temporal regularities in state evolution, a state prediction gate with the evolution mismatch compensation, and a state update gate with the observation mismatch compensation. The Gaussian approximation implementation of the filtering process within the gated framework is derived, taking into account the computational efficiency. Finally, the corresponding internal neural network structures and end-to-end training methods are designed. The Bayesian filtering theory enhances the interpretability of the proposed gated network, enabling the effective integration of offline data and prior models within functionally explicit gated units. In comprehensive experiments, including simulations and real-world datasets, the proposed gated network demonstrates superior estimation performance compared to benchmark filters and state-of-the-art deep learning filtering methods. state estimation, gated recurrent neural network, Bayesian filtering ## I Introduction Bayesian filtering (BF) constructs a posterior probability density function (PDF) for the system state by leveraging available information [1], which is widely used in target tracking [2, 3, 4], navigation [5, 6], and localization [7] due to its solid theoretical foundation and effective computational design. During the filtering process, state-space models (SSMs) play a pivotal role in depicting state evolution and sensor observations. The optimality of traditional Bayesian filters depends on the correctness of prior SSMs [8], and hence their performance significantly deteriorates in the presence of model mismatches, while the complete and correct prior SSM is difficult to obtain in a complex and non-cooperative environment. Therefore, much attention has been paid to online Bayesian optimization, with representative approaches being the multi-model (MM) estimation and joint estimation identification (JEI). Its idea is the real-time inference of model parameters along with the recursive computation of density. The limited information available in online measurements necessitates certain prior conditions or assumptions for these parameters. Specifically, the MM estimation requires a prior model set and transition probability matrix [9, 10, 11]; JEI implemented by the expectation-maximization (EM) for parameter identification assumes that the estimated parameter is piecewise constant [12, 13, 14, 15]; and JEI implemented by the variational inference (VI) for covariance identification [16, 17, 18, 19] assume that the estimated covariance has a conjugate distribution. More importantly, the online Bayesian optimization approaches exclusively deal with real-time measurement data, while disregarding the abundant offline data. With the widespread deployment of sensors and advancements in simulation technologies, there has been a notable increase in the available offline data, leading to a surge in the use of deep learning (DL). By capturing the temporal regularities in state evolution through their powerful nonlinear fitting capabilities and memory iteration mechanisms, various gated recurrent neural networks (RNNs), like long short-term memory (LSTM) [20] and gated recurrent unit (GRU) [21], have demonstrated remarkable performance in handling time series data [22, 23]. Gated RNNs are utilized to establish mapping functions from measurements to states, revealing the feasibility of extracting implicit modeling information from offline data [24, 25]. Nonetheless, pure deep learning approaches do not systematically integrate prior model knowledge, which necessitates a large number of learnable parameters and a substantial amount of labeled data, often resulting in a lack of interpretability. To introduce prior model knowledge and improve interpretability, methods combining DL and BF have been widely studied in recent years. The RNN is utilized for dynamic model learning, i.e., it is integrated into the Bayesian filter as a mapping for the state transition [26, 27, 28], while this leads to the neglect of the prior dynamic model knowledge. This idea of utilizing RNN to directly learn the dynamic and measurement models of the Bayesian filter has more applications in the computer vision field [29, 30]. An improved approach employs the LSTM to correct the estimated state of a model-based Bayesian filter [31]. When the model is severely mismatched, such an ad hoc combination faces failure as the filter diverges, and the covariance is not corrected so that it is inconsistent with the corrected state. Given the significance of filter gain in balancing prediction and measurement, a recent study utilized the GRU to estimate the gain [32]. By omitting second-order moment computations, this method accelerates the computation but sacrifices the utilization of prior noise statistical information and the ability to output covariance. In general, it is essential to derive an algorithmic framework based on a well-defined model and Bayesian filtering theory when introducing DL in the filtering. This is a crucial element currently lacking in existing methods, and it has the potential to enhance interpretability and estimation performance. To this end, we propose a general state estimation problem for the non-Markov system, considering the non-Markov state evolution model, uncertain measurement model, and labeled offline data. For this problem, an underlying multi-level gated Bayesian RNN (MGBRNN) is designed. At first, it is discovered that the non-Markov SSM can be transformed into an equivalent first-order Markov model with memory through function nesting, which enables efficient recursive computation while overcoming the limitations of the first-order Markov property. Secondly, a data-assisted joint state-memory-mismatch BF framework is derived based on the transformed model, featuring three-level gated units: the memory update gate captures the temporal regularities in state evolution, and the state prediction and state update gates perform filtering while compensating for model mismatches. With its functionally explicit gated units, the framework efficiently integrates offline data and prior model knowledge with good interpretability. Considering computing efficiency, the framework is derived as a Gaussian approximation implementation. Finally, the internal neural network (NN) structure and end-to-end training method of each gated unit are designed. Notably, rather than artificially combing the DL and the Bayesian filter, the proposed MGBRNN is naturally derived from BF theory. In comprehensive experiments with benchmark simulations and real-world datasets, the MGBRNN outperforms various model-based (MB) filters and state-of-the-art filtering methods. Notation: throughout this paper, the superscript \((\cdot)^{\top}\) denotes the transpose operation; \((\cdot)\) represents identical content to that stated in the preceding parenthesis; \(\mathrm{E}\left[\cdot|\cdot\right]\) denotes the conditional expectation. ## II Problem Formulation The state estimation of dynamic systems typically involves the utilization of the following first-order Markov SSM with additive noises. ### System model: \[\mathbf{x}_{k}=f_{k}\left(\mathbf{x}_{k-1}\right)+\mathbf{w}_{k} \tag{1}\] ### Measurement model: \[\mathbf{z}_{k}=h_{k}\left(\mathbf{x}_{k}\right)+\mathbf{v}_{k} \tag{2}\] where the subscript \(k\) represents the time index; \(\mathbf{x}_{k}\) is the state vector, such as the aircraft's position and velocity; \(\mathbf{z}_{k}\) is the measurement vector, such as the radial distance and azimuth of radar observation; \(f_{k}\) and \(h_{k}\) are the nominal linear/nonlinear state-evolution and state-measurement functions, respectively; the process noise \(\mathbf{w}_{k}\) and the measurement noise \(\mathbf{v}_{k}\) are independent of each other, and their PDFs are known and always being Gaussian distrubution. The first-order Markov property of the system model in Eq. (1) has certain reasonable aspects. At first, the most recent state has the most effect on the evolution since the state evolution could be roughly described as an accumulative process. Secondly, the state transition process between adjacent frames is easy to analyze, making it possible to characterize the process with a first-order model. Finally, the first-order Markov property supports the recursive computation. The above advantages have led to the widespread application of this modeling form. In fact, the real-world state evolution may be more complex than the model in Eq. (1). In practical state estimation tasks such as target tracking and navigation, the state evolution could be related to any of the historical states. Fig. 1 shows two representative examples of target tracking. In Fig. 1 (a), during target turning motion, determining the target's state at time \(k\) necessitates not only the state at time \(k-1\) but also parameters like turning radius and turning center, which are determined from state information across multiple frames. The traditional first-order Markov model, with no consideration of historical state, is difficult to get the turning parameters, resulting in modeling errors. Moreover, the target's motion involves a combination of recurring typical motion modes, allowing for the current state's determination based on historical states due to the invariance caused by the same motion mode. As shown in Fig. 1 (b), the invariant distance allows to obtain \(\mathbf{x}_{k}\) from \(\mathbf{x}_{k-N}\), but \(N\) is unknown. Such a non-Markov property is also prevalent in natural language processing. For Fig. 1: **Examples of non-Markov state evolution model.** (a) The turning motion mode requires multiple frames of state to be recognized. (b) The current state can be obtained by analyzing historical states. instance, in a sentence, the meaning of "bank" depends on the preceding context, with interpretations varying between a financial institution and the edge of a river or lake. Obviously, the state evolution could not be accurately depicted by the first-order Markov model, and it should be modeled in a non-Markov form [33], which is described as \[\mathbf{x}_{k}=f_{k}^{\text{general}}\left(\mathbf{x}_{k-1},\mathbf{x}_{k-2}, \cdots,\mathbf{x}_{1}\right)+\mathbf{w}_{k} \tag{3}\] where the general state-evolution function \(f_{k}^{\text{general}}\) reflects the effects of previous states and cannot be given a priori due to the increasing dimensionality. Note that Eq. (1) is a particular case of Eq. (3) when the state sequence in \(f_{k}^{\text{general}}\) contains only the previous single frame. The measurement model in Eq. (2) is also uncertain in practical state estimation tasks, and the uncertainties mainly come from two aspects: 1) the model mismatch caused by observation anomalies, such as offsets or unknown rotations in the state observation function due to poor sensor calibration; 2) it is often necessary to approximate intractable complex mappings with computationally convenient functions, which causes errors, e.g., the linearization of the non-linear system. We define the actual measurement model as \[\mathbf{z}_{k}=h_{k}^{\text{general}}\left(\mathbf{x}_{k}\right)+\mathbf{v}_ {k} \tag{4}\] where the general state-measurement function \(h_{k}^{\text{general}}\) is unknown, which depicts the actual observation process. For the filtering of the uncertain non-Markov SSMs presented in (3) and (4), we also consider access to labeled offline data. The abundant regularity information about state evolution and sensing observations is implicit in the offline data, which needs to be mined using time-series DL methods. Here, the available offline data consists of some sequence of observations and their corresponding ground truth states, i.e., \[\mathcal{D}=\left\{\mathbf{x}_{1:K}^{i},\mathbf{z}_{1:K}^{i}\right\}_{i=1 \cdots I} \tag{5}\] where \(\mathbf{x}_{1:K}^{i}\) is the state ground-truth sequence obtained offline and \(\mathbf{z}_{1:K}^{i}\) is the corresponding measurement sequence; \(K\) is the duration of the system evolution; and \(I\) is the number of samples in the data set. Such an offline data set can be accumulated by collecting sensor readings or executing simulations. For instance, collecting location ground-truth and odometer readings for wheeled robots. It is quite challenging for the filtering to SSMs in Eqs. (3) and (4) with considering the offline data set \(\mathcal{D}\). On the one hand, computational cost considerations require the derivation of efficient recursive estimation frameworks for non-Markov SSMs. On the other hand, it is required to extract regularity information about state evolution and sensing observations implicit in the offline data, which is used to learn uncertain SSMs. In addition, one needs to consider the prior information that can be available while utilizing the offline data, i.e., the prior nominal model in Eqs. (1) and (2). To this end, our goal is to construct a state estimation algorithm for uncertain non-Markov SSMs by synthesizing prior model information and offline data. This algorithm should have an efficient recursive estimation framework derived from BF theory. ## III Multi-level Gated Bayesian Recurrent Neural Network The algorithm's design comprises the following three stages. At first, the non-Markov SSM is transformed into an equivalent first-order Markov model with memory. Secondly, a data-assisted joint state-memory-mismatch BF is derived based on the transformed model, leading to a multi-level gated framework. The filtering process within the gated framework is implemented using the Gaussian approximation. Finally, we design the structure of the NNs in each gated unit and the corresponding training method. ### _Problem transformation_ By introducing prior nominal models \(f_{k}\) and \(h_{k}\) in Eqs. (1) and (2), the problem of state estimation under uncertain and non-Markov models is transformed into the processing of the corresponding errors, thus we have \[\mathbf{x}_{k}= f_{k}\left(\mathbf{x}_{k-1}\right)+\underbrace{f_{k}^{\text{ general}}\left(\mathbf{x}_{k-1},\cdots,\mathbf{x}_{1}\right)-f_{k}\left( \mathbf{x}_{k-1}\right)}_{\Delta_{k}^{f}}+\mathbf{w}_{k} \tag{6}\] \[\mathbf{z}_{k}= h_{k}\left(\mathbf{x}_{k}\right)+\underbrace{h_{k}^{\text{ general}}\left(\mathbf{x}_{k}\right)-h_{k}\left(\mathbf{x}_{k}\right)}_{ \Delta_{k}^{h}}+\mathbf{v}_{k} \tag{7}\] where \(\Delta_{k}^{f}\) and \(\Delta_{k}^{h}\) are the corresponding state-dependent evolution mismatch error and observation mismatch error, respectively. In Eq. (6), the non-Markov error \(\Delta_{k}^{f}\) is difficult to recognize directly since it continues to change as the states accumulate. Here, a two-layer nested function is constructed to approximate \(\Delta_{k}^{f}\), which is described as \[\Delta_{k}^{f}=f_{k}^{\Delta}\left(\underbrace{g_{k}^{\Delta}\left(\mathbf{x} _{1},\cdots,\mathbf{x}_{k-1}\right)}_{\mathbf{c}_{k}}\right) \tag{8}\] where \(g_{k}^{\Delta}\) encapsulates the effects of historical states, representing a regular memory pattern in state evolution, and hence denoted as memory \(\mathbf{c}_{k}\), which exhibits non-Markov characteristics; and \(f_{k}^{\Delta}\) is an output function. In complex state evolution, \(\mathbf{c}_{k}\) is essentially a hidden variable that is difficult to explicitly construct into a physical meaning, while the extraction regularity of the memory is implicit in a large amount of offline data. For the memory \(\mathbf{c}_{k}\), considering the evolutionary regularities implicit in the states at different instants are similar, we also use the idea of nested functions to deal with it. Specifically, \(\mathbf{c}_{k}\) is approximated through the following nested function: \[\mathbf{c}_{k}=\underbrace{g^{e}(g^{e}(g^{e}(\cdots),\mathbf{x}_{k-3}), \mathbf{x}_{k-2}),\mathbf{x}_{k-1})}_{k\text{ times}} \tag{9}\] where, at each instant, \(g^{e}\) selectively retains information distilled from historical states and introduces information about new states. In fact, the function nesting in Eq. (9) reveals the idea of memory (or hidden variable) iteration in the LSTM [20]. Such a nested form constructs an iterative update of \(\mathbf{c}_{k}\), which is equivalently expressed as \[\mathbf{c}_{k}=g^{c}\left(\mathbf{c}_{k-1},\mathbf{x}_{k-1}\right) \tag{10}\] For the state-dependent observation mismatch error \(\Delta_{k}^{h}\), we construct the mapping relation as \[\Delta_{k}^{h}=h^{\Delta}\left(\mathbf{x}_{k}\right) \tag{11}\] Through the above function approximation, we discover that the non-Markov system model can be equivalently transformed into a first-order Markov model with memory iteration. In this context, the recursion of memory is affected by the state, while the evolution of the state is also affected by the memory. If \(\mathbf{c}_{k}\) is considered an extended state, the new state composed of \(\mathbf{x}_{k}\) and \(\mathbf{c}_{k}\) remains Markov, demonstrating that non-Markov systems can be equivalently represented using the first-order Markov system with an appropriately extended state dimension. Such a model preserves historical state information while supporting recursive computation. Considering the offline data, the estimation of the model mismatch errors is also transformed into the learning of the functions \(f^{\Delta}\), \(g^{c}\) and \(h^{\Delta}\) from \(\mathcal{D}\), which is equivalent to learning the corresponding conditional PDFs. Unlike the traditional Bayesian filtering framework, a triple PDF recursive framework with state, memory, and mismatch is required for this model. ### _Bayesian multi-level gated framework design_ By introducing the offline data set \(\mathcal{D}\), we derive the joint state-memory-mismatch Bayesian filtering as shown in Theorem 1. **Theorem 1**.: _(Joint state-memory-mismatch Bayesian filtering) For the SSM in Eqs. (6) - (8), (10), and (11), given the previous measurements \(\mathbf{z}_{1:k-1}\), the offline data set \(\mathcal{D}\), and the previous joint state-memory-mismatch posterior density \(p\left(\mathbf{x}_{k-1},\mathbf{c}_{k-1}\left|\mathbf{z}_{1:k-1},\mathcal{D}\right.\right)\), the joint state-memory density prediction is_ \[p\left(\mathbf{x}_{k},\mathbf{c}_{k}\left|\mathbf{z}_{1:k-1}, \mathcal{D}\right.\right)\] \[=\iint P_{k}^{1}p\left(\mathbf{x}_{k-1},\mathbf{c}_{k-1}\left| \mathbf{z}_{1:k-1},\mathcal{D}\right.\right)d\mathbf{x}_{k-1}d\mathbf{c}_{k-1} \tag{12}\] _with_ \[P_{k}^{1}= \int p\left(\mathbf{x}_{k}\left|\mathbf{x}_{k-1},\Delta_{k}^{f} \right.\right)P_{k}^{2}d\Delta_{k}^{f} \tag{13}\] \[P_{k}^{2}= p\left(\Delta_{k}^{f}\left|\mathbf{c}_{k},\mathcal{D}\right. \right)p\left(\mathbf{c}_{k}\left|\mathbf{x}_{k-1},\mathbf{c}_{k-1},\mathcal{ D}\right.\right) \tag{14}\] _The joint state-memory density update is_ \[p\left(\mathbf{x}_{k},\mathbf{c}_{k}\left|\mathbf{z}_{1:k}, \mathcal{D}\right.\right)= \frac{\int p\left(\mathbf{z}_{k}\left|\Delta_{k}^{h},\mathbf{x}_ {k}\right.\right)p\left(\Delta_{k}^{h}\left|\mathbf{x}_{k},\mathcal{D}\right. \right)d\Delta_{k}^{h}}{p\left(\mathbf{z}_{k}\left|\mathbf{z}_{1:k-1}, \mathcal{D}\right.\right)}\] \[\times p\left(\mathbf{x}_{k},\mathbf{c}_{k}\left|\mathbf{z}_{1:k-1}, \mathcal{D}\right.\right) \tag{15}\] Proof.: See Appendix A. The probabilistic transfer of the joint state-memory-mismatch BF is shown in Fig. 2, and its iteration process contains three gated units: 1) the memory update gate (MUG) determines the current memory based on the previous state, previous memory, and offline data; 2) the state prediction gate (SPG) determines the joint state-memory prediction PDF; 3) the state update gate (SUG) determines the joint update PDF of the state and memory. To get the state prediction and posterior PDFs, the outputs of the state prediction and update gates are computed as \[p\left(\mathbf{x}_{k}\left|\mathbf{z}_{1:k-1},\mathcal{D}\right. \right)= \int p\left(\mathbf{x}_{k},\mathbf{c}_{k}\left|\mathbf{z}_{1:k-1}, \mathcal{D}\right.\right)d\mathbf{c}_{k} \tag{16}\] \[p\left(\mathbf{x}_{k}\left|\mathbf{z}_{1:k},\mathcal{D}\right. \right)= \int p\left(\mathbf{x}_{k},\mathbf{c}_{k}\left|\mathbf{z}_{1:k}, \mathcal{D}\right.\right)d\mathbf{c}_{k} \tag{17}\] Such a multi-level gated framework utilizes prior models in the recursive filtering process while integrating offline data for learning the unknown PDFs, including the memory update density \(p(\mathbf{c}_{k}\left|\mathbf{x}_{k-1},\mathbf{c}_{k-1},\mathcal{D}\right.)\), the evolution mismatch density \(p(\Delta_{k}^{f}\left|\mathbf{c}_{k},\mathcal{D}\right.)\), and the observation mismatch density \(p(\Delta_{k}^{h}\left|\mathbf{x}_{k},\mathcal{D})\). It is required to design NN modules for the learning of these unknown distributions from offline data, while the analytical implementation of the filtering process can be derived separately in the case that these distributions are known. To fully introduce the proposed gated framework, the filtering implementation is first derived, with the corresponding network module to be designed in the next subsection. The filtering process of the gated framework has various implementation methods, such as Monte Carlo sampling [34] and Gaussian approximation [35]. The gated framework of our MGBRNN is implemented by Gaussian approximation, considering that it is a fast and stable implementation method. In fact, constructing the internal weights or the output of the network in the form of a Gaussian distribution is also widespread in the field of Bayesian NNs [36, 37]. The assumptions required to perform the Gaussian approximation are given as follows. Fig. 2: Diagram of the joint state-memory-mismatch Bayesian filtering Assumption 1. The process noise \(\mathbf{w}_{k}\) and the measurement noise \(\mathbf{v}_{k}\) obey Gaussian distributions as \(\mathbf{w}_{k}\sim N\left(0,\mathbf{Q}_{k}\right)\) and \(\mathbf{v}_{k}\sim N\left(0,\mathbf{R}_{k}\right)\), respectively. Assumption 2. The measurement prediction PDF is a Gaussian distribution with first- and second-order moments of \(\mathbf{\hat{z}}_{k|k-1}\) and \(\mathbf{P}_{k|k-1}^{x}\), respectively, namely, \[p\left(\mathbf{z}_{k}\left|\mathbf{z}_{1:k-1},\mathcal{D}\right)=N\left( \mathbf{z}_{k};\mathbf{\hat{z}}_{k|k-1},\mathbf{P}_{k|k-1}^{x}\right) \tag{18}\] Assumption 3. The state posterior PDF is a Gaussian distribution with first- and second-order moments of \(\mathbf{\hat{x}}_{k|k}\) and \(\mathbf{P}_{k|k}\) respectively, namely, \[p\left(\mathbf{x}_{k}\left|\mathbf{z}_{1:k},\mathcal{D}\right)=N\left( \mathbf{x}_{k};\mathbf{\hat{x}}_{k|k},\mathbf{P}_{k|k}\right) \tag{19}\] Assumption 4. \(\mathbf{c}_{k}\) obeys a Gaussian distribution with first- and second-order moments of \(\mathbf{\hat{c}}_{k}\) and \(\mathbf{P}_{k}^{c}\), respectively, namely, \[p\left(\mathbf{c}_{k}\left|\mathbf{x}_{k-1},\mathbf{c}_{k-1}, \mathcal{D}\right)=N\left(\mathbf{c}_{k};\mathbf{\hat{c}}_{k},\mathbf{P}_{k}^ {c}\right) \tag{20}\] Assumption 5. \(\Delta_{k}^{f}\) obeys a Gaussian distribution with first- and second-order moments of \(\hat{\Delta}_{k}^{f}\) and \(\mathbf{P}_{k}^{f}\), respectively; and \(\Delta_{k}^{h}\) obeys a Gaussian distribution with first- and second-order moments of \(\hat{\Delta}_{k}^{h}\) and \(\mathbf{P}_{k}^{h}\), respectively, namely, \[p\left(\Delta_{k}^{f}\left|\mathbf{c}_{k},\mathcal{D}\right)=N \left(\Delta_{k}^{f};\hat{\Delta}_{k}^{f},\mathbf{P}_{k}^{f}\right) \tag{21}\] \[p\left(\Delta_{k}^{h}\left|\mathbf{x}_{k},\mathcal{D}\right. \right)=N\left(\Delta_{k}^{h};\hat{\Delta}_{k}^{h},\mathbf{P}_{k}^{h}\right) \tag{22}\] _Remark 1:_General Gaussian filtering without mismatch usually assumes that \(\mathbf{w}_{k}\), \(\mathbf{v}_{k}\), \(p\left(\mathbf{z}_{k}\left|\mathbf{z}_{1:k-1},\mathcal{D}\right)\) and \(p\left(\mathbf{x}_{k}\left|\mathbf{z}_{1:k},\mathcal{D}\right)\) are Gaussian [35], which corresponds to the Assumptions 3, 4, and 5. The Gaussian approximation implementation of the filtering process in the proposed multi-level gated framework is shown in Theorem 2. **Theorem 2**.: _(Gaussian approximation implementation) Under Assumptions 1-5, the state and covariance prediction are_ \[\mathbf{\hat{x}}_{k|k-1}= \int f_{k}\left(\mathbf{x}_{k-1}\right)P_{k-1}^{x+}d\mathbf{x}_{k -1}+\hat{\Delta}_{k}^{f} \tag{23}\] \[\mathbf{P}_{k|k-1}= \int f_{k}\left(\mathbf{x}_{k-1}\right)[f_{k}\left(\mathbf{x}_{k -1}\right)]^{\top}P_{k-1}^{x+}d\mathbf{x}_{k-1}+\mathbf{P}_{k}^{f}\] \[- \mathbf{\hat{x}}_{k|k-1}\mathbf{\hat{x}}_{k|k-1}^{\top}+\mathbf{Q }_{k} \tag{24}\] _and the state and covariance update are_ \[\mathbf{\hat{x}}_{k|k}= \mathbf{\hat{x}}_{k|k-1}+\mathbf{P}_{k|k-1}^{xz}\left(\mathbf{P} _{k|k-1}^{z}\right)^{-1}\left(\mathbf{z}_{k}-\mathbf{\hat{z}}_{k|k-1}\right) \tag{25}\] \[\mathbf{P}_{k|k}= \mathbf{P}_{k|k-1}-\mathbf{P}_{k|k-1}^{xz}\left(\mathbf{P}_{k|k -1}^{z}\right)^{-1}\left(\mathbf{P}_{k|k-1}^{xz}\right)^{\top} \tag{26}\] _where_ \[\mathbf{\hat{z}}_{k|k-1}= \int h_{k}\left(\mathbf{x}_{k}\right)P_{k}^{x-}d\mathbf{x}_{k}+ \hat{\Delta}_{k}^{h} \tag{27}\] \[\mathbf{P}_{k|k-1}^{z}= \int h_{k}\left(\mathbf{x}_{k}\right)\left(h_{k}\left(\mathbf{x}_{k }\right)\right)^{\top}P_{k}^{x-}d\mathbf{x}_{k}+\mathbf{P}_{k}^{h}\] \[- \mathbf{\hat{z}}_{k|k-1}\mathbf{\hat{z}}_{k|k-1}^{\top}+\mathbf{R }_{k}\] (28) \[\mathbf{P}_{k|k-1}^{xz}= \int\mathbf{x}_{k}(h_{k}\left(\mathbf{x}_{k}\right))^{\top}P_{k}^{ x-}d\mathbf{x}_{k}-\mathbf{\hat{x}}_{k|k-1}\mathbf{\hat{z}}_{k|k-1}^{\top}\] (29) \[P_{k-1}^{x+}= N(\mathbf{x}_{k-1};\mathbf{\hat{x}}_{k-1|k-1},\mathbf{P}_{k-1|k-1})\] \[P_{k}^{x-}= N(\mathbf{x}_{k};\mathbf{\hat{x}}_{k|k-1},\mathbf{P}_{k|k-1})\] Proof.: See Appendix B. In the above implementation process, Gaussian-weighted integrals are crucial. There are various methods for fast calculation of integrals in Gaussian approximate filtering [35]. Here, we give the computational process under the first-order Taylor expansion. Let \(\mathbf{F}_{k}\) and \(\mathbf{H}_{k}\) be the Jacobian matrices of \(f_{k}\) and \(h_{k}\), respectively. Based on the idea of function approximation used in extended KF (EKF) [38], Eqs. (23) and (24) are replaced by: \[\mathbf{\hat{x}}_{k|k-1}= f_{k}\left(\mathbf{\hat{x}}_{k-1|k-1}\right)+\hat{\Delta}_{k}^{f} \tag{30}\] \[\mathbf{P}_{k|k-1}= \mathbf{F}_{k}\mathbf{P}_{k|k-1}\mathbf{F}_{k}^{\top}+\mathbf{Q}_{ k}+\mathbf{P}_{k}^{f} \tag{31}\] and the Eqs. (27)-(29) are replaced by: \[\mathbf{\hat{z}}_{k|k-1}= h_{k}\left(\mathbf{\hat{x}}_{k|k-1}\right)+\hat{\Delta}_{k}^{h} \tag{32}\] \[\mathbf{P}_{k|k-1}^{z}= \mathbf{H}_{k}\mathbf{P}_{k|k-1}\mathbf{H}_{k}^{\top}\text{ + }\mathbf{R}_{k}+\mathbf{P}_{k}^{h}\] (33) \[\mathbf{P}_{k|k-1}^{xz}= \mathbf{P}_{k|k-1}\mathbf{H}_{k}^{\top} \tag{34}\] Under the Gaussian approximation, the learning of the unknown distributions is transformed into the estimation of their corresponding first- and second-order moments. It is necessary to construct the corresponding mappings by learning from offline data to realize the estimation. In the following, we design the corresponding NN structure for each gated unit in the three-level gated framework and train them as the corresponding estimation mappings via offline data. ### _Gated network structure design_ The overall structure of the proposed network is shown in Fig. 3, which contains six NN modules in its three gated units for estimating the first- and second-order moments of memory and model mismatch errors, respectively. The prior model information is introduced through the filtering formulas, and the offline data is used for the learning of the NN, while such a structure is rigorously derived based on the BF theory. Benefiting from this, the network modules in each gated unit do not need complex structures. Therefore, we construct the same network with a conventional form for these network modules, i.e., a two-layer NN with the hyperbolic tangent activation function, which is described as a function \(F\): \[F\left(\mathbf{i},j\right)=\omega^{j2}\left(\tanh\left(\omega^{j1}\mathbf{i}+ \mathbf{b}^{j1}\right)\right)+\mathbf{b}^{j2} \tag{35}\] where \(\mathbf{i}\) is the input vector and \(j\) is the index; \(\omega\) and \(\mathbf{b}\) are the weight and bias of the NN, respectively, and \(\omega,\mathbf{b}\in\mathbf{\Phi}\); and tanh denotes the hyperbolic tangent activation function. The inputs to the NN modules of each gating unit are introduced as follows, with descriptions of some of the involved notations provided here: \(\sigma\) denotes the sigmoid function, \(con[\mathbf{a},\mathbf{b}]\) denotes the concatenation of vectors \(\mathbf{a}\) and \(\mathbf{b}\), flat denotes the flattening of the matrix into vectors, and \(\Psi\) denotes the maximal normalization operation. The normalization, flattening, and other operations we conducted are standard procedures in DL. #### Iii-C1 Input to the NN in MUG In the MUG, NN modules are utilized for the estimation of \(\mathbf{\hat{c}}_{k}\) and \(\mathbf{P}_{k}^{c}\). Therefore, based on the conditions of PDF \(p\left(\mathbf{c}_{k}\left|\mathbf{x}_{k-1},\mathbf{c}_{k-1},\mathcal{D}\right)\), the corresponding input vector is constructed as \(\mathbf{\hat{l}}_{k}^{c}=\text{con}\left[\sigma\left(\text{con}\left[\mathbf{ \hat{c}}_{k-1},\text{flat}\left(\mathbf{P}_{k-1}^{c}\right)\right]\right), \Psi\left(\mathbf{\hat{x}}_{k-1|k-1}\right)\right]\). #### Iii-C2 Input to the NN in SPG In the SPG, NN modules are utilized for the estimation of \(\hat{\Delta}_{k}^{f}\) and \(\mathbf{P}_{k}^{f}\). Therefore, based on the conditions of the PDF \(p(\Delta_{k}^{f}\,|\,\mathbf{c}_{k},\mathcal{D})\), the corresponding input vector is constructed as \(\mathbf{i}_{k}^{\mathbf{f}}=\sigma\left(\text{con}\left[\mathbf{\hat{c}}_{k}, \text{flat}\left(\mathbf{P}_{k}^{\mathbf{c}}\right)\right]\right)\). #### Iii-C3 Input to the NN in SUG In the SUG, NN modules are utilized for the estimation of \(\hat{\Delta}_{k}^{h}\) and \(\mathbf{P}_{k}^{h}\). Therefore, based on the conditions of the PDF \(p\left(\Delta_{k}^{h}\,|\,\mathbf{x}_{k},\mathcal{D}\right)\), the corresponding input vector is constructed as \(\mathbf{i}_{k}^{\mathbf{i}}=\Psi\left(\mathbf{\hat{x}}_{k|k-1}\right)\). Based on the structures and inputs of the gated units described above, their internal NN modules are constructed as in Tab. I. Obviously, each gated unit has its own specified function, and the errors caused by model mismatches are targeted to be compensated. Compared to the existing algorithmic frameworks that incorporate gated RNNs like LSTM and GRU into Bayesian filters, MGBRNN is an underlying gated RNN tailored for state estimation and designed based on BF theory. The gated units in MGBRNN possess finely partitioned functionality, rendering them physically interpretable and potentially reducing the demand for learnable parameters, thus diminishing the need for a large amount of training data. Despite the extensive research on task-specific underlying gated RNNs in recent years [39, 40, 41, 42], gated RNNs tailored specifically for state estimation remain largely unexplored, with MGBRNN introducing a novel perspective in this research direction. ### _Algorithm training_ As depicted in Fig. 3, in a supervised manner, the gated network within MGBRNN undergoes end-to-end training by extracting the underlying regularities governing state evolution and observation from \(\mathcal{D}\). Despite the fact that the NN computes intermediate parameters instead of directly generating estimated states, we employ the loss function computed from the estimated states and their corresponding ground-truth in \(\mathcal{D}\) to simultaneously train all the learnable parameters within MGBRNN. This training approach has been demonstrated to be viable in [32]. In line with the commonly used minimum mean square error (MMSE) criterion in BF, we employ the mean square error (MSE) loss function with the addition of L2 regularization for training MGBRNN. Consider the offline data set described in Eq. (5), the MSE loss is described as \[l_{i}\left(\Phi\right)=\frac{1}{K}\sum_{k=1}^{K}\left\|\mathbf{\hat{x}}_{k|k} ^{i}\left(\Phi\right)-\mathbf{x}_{k}^{i}\right\|^{2}+\tau\left\|\Phi\right\|^ {2} \tag{36}\] Fig. 3: **The overall structure of the MGBRNN and its training process. The multi-level gated structure with the memory update gate, the state prediction gate, and the state update gate is rigorously derived from Bayesian filtering theory and integrates prior model knowledge and offline data efficiently.** where \(\tau\) is a coefficient used to adjust the proportion of the regular term; \(i\in\{1,2,\cdots,I\}\) represents the index of the training sample; and \(\Phi\) is the learnable parameter set. A variation of mini-batch stochastic gradient descent is utilized to optimize \(\Phi\). Specifically, for each batch indexed by \(n\), we select \(J<I\) trajectories denoted as \(i_{1}^{n},i_{2}^{n},\ldots,i_{J}^{n}\). The mini-batch loss is then computed as follows: \[L_{n}\left(\Phi\right)=\frac{1}{J}\sum_{j=1}^{J}l_{j^{-}_{\tau}}\left(\Phi\right) \tag{37}\] Given that MGBRNN features a recursive architecture, the backpropagation through time (BPTT) algorithm [43] is utilized for its training, which is a technique commonly used in training RNNs. The BPTT algorithm efficiently captures temporal dependencies by unfolding the network over time and computing gradient estimates in both forward and backward directions, making it effective for handling sequential data. Concretely, we utilize shared network parameters to unfold MGBRNN over time and calculate the forward and backward gradient estimations across the network. ## IV Experiments In this section, we comprehensively evaluate the MGBRNN in four state estimation tasks, which encompass two benchmark simulation scenarios and two real-world data sets. At first, we conduct an ablation experiment on a real-world data set to illustrate the functions and effectiveness of each gated unit in the MGBRNN. Subsequently, we compared the MGBRNN with MB- and DL-based representative methods across all four tasks. This comparison showcases the outstanding performance and the lightweight parameter scale of the MGBRNN. Throughout the experiment, we employ two units to quantify estimation errors: MSE in [dB], commonly used in signal processing, is utilized for simulation scenarios to narrow down the range of values; and root MSE (RMSE), a standard metric in target tracking and navigation, is utilized for the real-world data sets. Here, we describe the calculation for these two units. The MSE of the estimated state is calculated as \[M_{\mathbf{x}}=\frac{1}{KN}\sum_{i=1}^{N}\sum_{k=1}^{K}\left(\mathbf{x}_{i,k}- \mathbf{\hat{x}}_{i,k|k}\right)\left(\mathbf{x}_{i,k}-\mathbf{\hat{x}}_{i,k|k }\right)^{\top} \tag{38}\] where \(N\) is the number of test samples and \(K\) is the time duration. The MSE in [dB] is calculated as \(10\times\log_{10}\left(M_{\mathbf{x}}\right)\) and the RMSE is calculated as \(\sqrt{M_{\mathbf{x}}}\). ### _Ablation Experiment_ The Michigan NCLT data set is used to evaluate each gated unit of MGBRNN in the ablation experiment. The labeled trajectory data of the wheeled robots is gathered in the NCLT data set, which contains the robots' ground-truth locations and noisy sensor readings (e.g., GPS and odometer). We follow the setup in [32] to perform robot localization using measurements from these noisy readings. Our specific goal is to track the two-dimensional position using only odometry data, which means that the observations come from noisy velocity readings while modeling information is not available in the dataset. Odometer-based localization is available in locations with weak GPS signals or dense obstructions, such as inside or in canyons, but sensor reading drift and the inability to directly monitor positions make it difficult. **Experimental setups.** In the NCLT data set, the trajectory at 2012-01-22 with outliers removed is segmented into 48 trajectories, each containing a sequence of ground-truth positions and corresponding noisy velocity readings with \(K=100\) and a sampling frequency of \(1\mathrm{\,Hz}\). In these trajectories, we set 34 for training (\(71\%\)), 9 for validation (\(19\%\)), and 5 for testing (\(10\%\)). The state vector is \(\mathbf{x}_{k}=[x_{k},y_{k},\dot{x}_{k},\dot{y}_{k}]^{\top}\) with \([x_{k},y_{k}]^{\top}\) and \([\dot{x}_{k},\dot{y}_{k}]^{\top}\) being the position and velocity, respectively, and the measurement is the noisy velocity. This data set contains only state ground-truth and corresponding measurements, so one need to construct the nominal SSM manually. The prior nominal state-evolution matrix \(\mathbf{F}^{\text{prior}}\) is a constant velocity (CV) model with the sampling interval \(\Delta t=1\), and the nominal state-measurement matrix \(\mathbf{H}^{\text{prior}}\) is a linear model, i.e., \[\mathbf{F}^{\text{prior}}=\begin{bmatrix}1&0&\Delta t&0\\ 0&1&0&\Delta t\\ 0&0&1&0\\ 0&0&0&1\end{bmatrix},\mathbf{H}^{\text{prior}}=\begin{bmatrix}0&0&1&0\\ 0&0&0&1\end{bmatrix}^{\top}\] The process noise covariance and measurement noise covariance are computed as \[\mathbf{Q}=q^{2}\mathbf{I}_{d_{x}},\quad\mathbf{R}=r^{2}\mathbf{I}_{d_{x}} \tag{39}\] where we set nominal values of \(q=0.1\) and \(r=1\). To evaluate the effectiveness of each gated unit, we set four schemes by masking the different gated units in MGBRNN: 1) full MGBRNN with three gated units; 2) MGBRNN without the MUG; 3) MGBRNN without the SPG; and 4) MGBRNN without the SUG. In Scheme 2, the input of the SPG does not contain the memory but only the state estimation of the previous instant. **Experimental results and analysis** Fig. 4 depicts the convergence of localization errors on the validation set during the training process of the four schemes. MGBRNN with a full-gated structure exhibits the quickest convergence to achieve the lowest localization error. Although the scheme without the MUG converges quickly, it is constrained by the first-order Markov property, resulting in greater localization error. The scheme without the SUG cannot compensate for the observation mismatch, leading to slow convergence and a high loss. The scheme without the SPG trains the worst since learning the dynamic model is the most critical of state estimation. The localization RMSE of the four schemes on the test set is shown in Tab. II, and the localization results of a single test sample are displayed in Fig. 5. Masking out each gated unit will increase localization errors, reflecting the effectiveness of each gated unit in MGBRNN. ### _Linear System_ In this scenario, the MGBRNN is compared with the Kalman filter (KF) and LSTM under a linear SSM to evaluate its performance in response to model mismatch under linear conditions. **Experimental setups.** We follow the setup in [32] to estimate the state of a linear system as \[\mathbf{x}_{k}= \mathbf{F}\mathbf{x}_{k-1}+\mathbf{w}_{k} \tag{40}\] \[\mathbf{z}_{k}= \mathbf{H}\mathbf{x}_{k}+\mathbf{v}_{k} \tag{41}\] where \[\mathbf{F}\in \mathbb{R}_{d_{x}\times d_{x}},\quad F_{ij}=\begin{cases}1,& \text{if }i=j\text{ or }i=1\\ 0,&\text{else}\end{cases} \tag{42}\] \[\mathbf{H}\in \mathbb{R}_{d_{x}\times d_{z}},\quad H_{ij}=\begin{cases}1,& \text{if }i=d_{x}-j+1\text{ or }i=1\\ 0,&\text{else}\end{cases} \tag{43}\] with \(d_{x}\times d_{z}=2\times 2\) and \(K=20\). In the filtering process, our MGBRNN only acquires the mismatched model, i.e., the rotated state evolution matrix \(\mathbf{F}_{\theta}\) and the rotated state observation matrix \(\mathbf{H}_{\theta}\) with \(\theta=10^{\circ}\), which are described as \[\mathbf{H}_{\theta}=\mathbf{T}_{\theta}\mathbf{H},\quad\mathbf{F}_{\theta}= \mathbf{T}_{\theta}\mathbf{F},\quad\mathbf{T}_{\theta}=\left[\begin{array}{ cc}\cos\theta&-\sin\theta\\ \sin\theta&\cos\theta\end{array}\right] \tag{44}\] The process noise covariance and the measurement noise covariance are calculated as Eq. (39), and the same \(q\) and \(r\) are used for data generation and filtering. Under several inverse observation noise levels as \(\frac{1}{r^{2}}\left[dB\right]\in\{-10,0,10,20\}\), we compare the MGBRNN with three methods: a single-layer LSTM directly estimates \(\mathbf{x}_{k}\) by input \(\mathbf{z}_{k}\); a KF with the accurate model; and a KF with the mismatched model. **Experimental results and analysis.** The test result is shown in Fig. 6. When the model is mismatched, the KF without learning capability causes an extreme estimation error. Although LSTM learns state estimation by mining offline data, it lacks a specific learning architecture and cannot introduce prior models, leading to its poor estimated performance. The effect of the model on the estimation performance is particularly significant at lower observation noise, at which time the estimation performance of the LSTM is degraded. The estimation error of MGBRNN is close to MMSE (KF with the accurate model), demonstrating that it effectively compensates for model mismatches by learning from offline data. ### _Lorenz Attractor_ The Lorenz attractor is a chaotic system generated by a set of differential equations used to simulate atmospheric convection, characterized by ever-changing three-dimensional trajectories. In this scenario, the tracking ability of the MGBRNN in complex and highly nonlinear settings under model mismatch is validated. **Experimental setups.** The Lorentz attractor scenario here has the same parameter settings as in [32] and [44]. The Lorenz attractor is mathematically described by a system of three coupled ordinary differential equations, and the noiseless state-evolution of the continuous time process Fig. 4: **Training loss on the validation set.** The absence of each gate affects the convergence speed and final convergence result of MGBRNN training. Fig. 5: **Localization results on test data with different ablation schemes.** The absence of each gate affects the localization performance of MGBRNN. Fig. 6: Test results for linear systems \(\left[x_{t}^{1},x_{t}^{2},x_{t}^{3}\right]^{\top}\) is \[\frac{\partial\mathbf{x}_{t}}{\partial t}=\mathbf{A}\left(\mathbf{x}_{t}\right) \mathbf{x}_{t},\mathbf{A}\left(\mathbf{x}_{t}\right)=\left[\begin{array}{ccc} -\sigma&\sigma&0\\ \beta&-1&-x_{t}^{1}\\ 0&x_{t}^{1}&-\rho\end{array}\right] \tag{45}\] where \(\sigma=10\), \(\rho=8/3\), and \(\beta=28\) are parameters governing the system's dynamics. We follow the processing in [32] to get a discrete-time state-evolution model, and the resulting discrete-time evolution process is \(\mathbf{x}_{k+1}=\mathbf{F}\left(\mathbf{x}_{k}\right)\mathbf{x}_{k}\), where \(\mathbf{x}_{k}=\left[x_{k}^{1},x_{k}^{2},x_{k}^{3}\right]^{\top}\) is a discrete-time state vector, and the discrete-time state-evolution matrix \(\mathbf{F}\left(\mathbf{x}_{k}\right)\) is obtained by the Taylor series expansion and a finite series approximation (with \(J\) coefficients). The covariance of the process noise and the measurement noise is computed as in Eq. (39). Similar to the linear system scenario, we consider both evolution and observation model mismatches. Here, the observation model is an identity matrix rotated by merely \(\theta=10^{\circ}\), and the evolution model is \(\mathbf{F}\left(\mathbf{x}_{k}\right)\) with \(J=1\) while the actual data is generated by \(\mathbf{F}\left(\mathbf{x}_{k}\right)\) with \(J=5\). Under different noise levels of \(1/r^{2}\left[\text{dB}\right]\in\left\{-10,0,10\right\}\), our MGBRNN is compared with several benchmark nonlinear filters, i.e., the EKF, unscented KF (UKF), and particle filter (PF). **Experimental results and analysis.** The tracking MSE in [dB] of each method is shown in Tab. III. MGBRNN exhibits the lowest estimation error, highlighting its capacity to significantly improve performance in scenarios with severe nonlinearities through offline learning. Other MB nonlinear filters all degrade in performance under model mismatch, especially under lower measurement noise. The tracking trajectories of each method for a noise level of \(1/r^{2}=0\text{[dB]}\) are shown in Fig. 7, with the trajectory estimated by MGBRNN being more closely fitting the ground-truth. ### _Arceraft trajectory tracking_ In this experiment, our goal is to track the real trajectories of civil aircraft landing at the airport. The tracking of landing aircraft is an important aspect of airspace surveillance, which is critical to flight safety and aircraft scheduling. Due to their complex maneuvers, tracking airborne targets presents a challenging state estimation task. Here, we focus on compensation for uncertain motion modes. **Experimental setups.** The civil aviation trajectory data comes from [45], which contains the flight records covering Jan-Mar 2006 in Northern California TRACON. We extracted the trajectories of aircraft landing in the east direction on a designated runway and performed cubic spline interpolation on the trajectories to achieve a fixed sampling interval of \(\Delta t=4\). The trajectory length is set as \(K=200\)s, and shorter trajectories are discarded or longer ones are truncated accordingly. This resulted in 260 trajectories, with 182 (\(70\%\)) for training, 52 (\(20\%\)) for validation, and 26 (\(10\%\)) for testing. We consider tracking targets in the x-y two-dimensional coordinate system, and the form of the target state is the same as that in IV-A. The measurement model used corresponds to a general radar observation, i.e., the measurement \(\mathbf{z}_{k}\!=\!\!\left[d_{k},\mu_{k}\right]^{\top}\) with the radial distance \(d_{k}\) and the azimuth angle \(\mu_{k}\), the state-to-measurement function is \[h(\mathbf{x}_{k})\!=\!\!\left[\sqrt{x_{k}^{2}+{y_{k}}^{2}},\arctan\left(\frac{y _{k}}{x_{k}}\right)\right]^{\top} \tag{46}\] and the observation noise \(\mathbf{v}=\left[v_{d},v_{\mu}\right]^{\top}\) with \(v_{d}\sim\mathcal{N}\left(v_{d};0,\sigma_{d}{}^{2}\right)\) and \(v_{\mu}\sim\mathcal{N}\left(v_{\mu};0,\sigma_{\mu}{}^{2}\right)\). Under various radar accuracy settings of \(\sigma_{\mu}\) and \(\sigma_{d}\), the MGBRNN is compared with various representative filtering methods under various radar accuracies. For setups of these methods, the MGBRNN, EKF, UKF, and PF adopt the CV model, while the model set of the IMM estimator includes one CV model and two coordinate turn (CT) models with \(\omega=\pm 3^{\circ}/s\). Another method is a combination method that employs LSTM to real-time compensate for the estimated state of EKF. The process noise covariance \(\mathbf{Q}\) is computed as Eq. (39) with \(q^{2}=1\) for IMM, and \(q^{2}=10\) for other methods. Since airport air traffic control radars are typically cooperative sensors with known accuracy, the measurement model is known, and the measurement noise of each filter is given as \(\mathbf{R}=\left[\begin{array}{cc}\sigma_{d}^{2}&0\\ 0&\sigma_{\mu}^{2}\end{array}\right]\). **Experimental results and analysis.** The mean position and velocity RMSE of each method on the test set are shown in Tabs. IV and V, respectively. It can be seen that the MGBRNN has the lowest tracking error in both position and velocity. In comparison to the MB method, MGBRNN is capable of extracting implicit state evolution modes from offline data, i.e., multiple aircraft motion modes during landing. In comparison to the combination method, the gated structure of MGBRNN is tailored to state estimation under model mismatches, which adequately compensates for tracking errors caused by model mismatches. Fig. 8 shows the tracking trajectories on some samples of the test set. MGBRNN provides accurate tracking during target maneuvering (see zoomed-in section in figure), demonstrating Fig. 7: Tracking result of Lorenz attractor under model mismatch that it effectively mines the implicit target motion regularities in the offline data. ### _Michigan NCLT Data Set_ On the Michigan NCLT data set mentioned in the ablation experiment, we compare MGBRNN with several representative filtering algorithms to demonstrate its performance and the small learnable parameter scale. **Experimental setups.** With the same data setups as the ablation experiment, we compare MGBRNN with four types of representative methods, namely, the MB KF, the pure DL method LSTM, the state-of-the-art online Bayesian optimization method variational-Bayesian-based adaptive KF (VBKF), and the state-of-the-art DL-based filtering method KalmanNet. In these methods, KF and MGBRNN use the same model and noise settings as in the ablation experiments; LSTM has a single-layer structure and directly maps velocity measurements to positions; and the settings of VBKF and KalmanNet are referenced to [17] and [32], respectively. **Experimental results and analysis.** Tab. VI shows the localization RMSE of each method on the test set. KF without learning capability has the highest localization error, and VBKF slightly outperforms KF by online inference to the covariance. KalmanNet performs offline learning while introducing prior model knowledge, but it only modifies the filter gain, making it incapable of compensating for model mismatches effectively. The localization trajectories of some test samples are shown in Fig. VI, where we can see that MGBRNN consistently maintains high localization accuracy with low termination error. In MGBRNN, each gated unit has its own explicit function, which is targeted to compensate for the model mismatch, so it achieves the lowest localization error in such a challenging real-world localization task. In Fig. 10, we present the localization RMSE results for MGBRNN and KalmanNet with varying numbers of learnable parameters. It can be seen that MGBRNN outperforms KalmanNet, achieving lower localization errors despite having Fig. 8: **Tracking results on the test data.** We show the tracking performance of different filtering methods under various radar accuracies, with these black boxes indicating the target maneuver instants. When the target undergoes maneuvers, the proposed MGBRNN responds promptly and attains high tracking accuracy. fewer learnable parameters. The MGBRNN is an underlying gated RNN with a computationally efficient gated structure, which allows it to excel in state estimation tasks while maintaining simplicity. In fact, in such a task with very limited training samples, the small parameter scale of MGBRNN confers a significant advantage. ## V Conclusion In this paper, a multi-level gated Bayesian RNN is specifically designed for state estimation under model mismatch, i.e., MGBRNN. The gated structure of MGBRNN is designed by introducing the memory mechanism and offline data into the BF theory, which provides good interpretability, low complexity, and data efficiency. Each gated unit in the multi-level gated framework has its own explicit functionality, which effectively compensates for the errors resulting from model mismatches by integrating prior models and offline data. For computational efficiency, the Gaussian approximation is used to implement the filtering process of the gated framework, along with the development of an internal neural network structure and the corresponding end-to-end training method. The MGBRNN has been verified by both simulations and real-world data sets. It is demonstrated that the proposed algorithm outperforms the state-of-the-art DL-based filtering methods and could achieve high estimation accuracy with a small number of learnable parameters. ## Appendix A Proof of the joint state-memory-mismatch BF Denote that \(p\left(\mathbf{x}_{1:K},\mathbf{c}_{1:K}\left|\mathbf{z}_{1:K},\mathcal{D}\right.\right)\) is the joint posterior density of 1 to \(K\) time states and memories. Expanding this density under the Bayesian theorem as \[p \left(\mathbf{x}_{1:K},\mathbf{c}_{1:K}\left|\mathbf{z}_{1:K}, \mathcal{D}\right.\right)\] \[=p\left(\mathbf{x}_{1:K},\mathbf{c}_{1:K}\left|\mathbf{z}_{K}, \mathbf{z}_{1:K-1},\mathcal{D}\right.\right)\] \[=\frac{p\left(\mathbf{z}_{K}\left|\mathbf{x}_{1:K},\mathbf{c}_{1 :K},\mathbf{z}_{1:K-1}\right.\right)p\left(\mathbf{x}_{1:K},\mathbf{c}_{1:K} \left|\mathbf{z}_{1:K-1},\mathcal{D}\right.\right)}{p\left(\mathbf{z}_{K} \left|\mathbf{z}_{1:K-1},\mathcal{D}\right.\right)} \tag{47}\] According to Eq. (11), the measurement is independent of the previous state given the current state. In addition, the state information contained in previous measurements has been accurately characterized by the current state. Then we have \[p\left(\mathbf{z}_{K}\left|\mathbf{x}_{1:K},\mathbf{c}_{1:K}, \mathbf{z}_{1:K-1},\mathcal{D}\right.\right)=p\left(\mathbf{z}_{K}\left| \mathbf{x}_{K},\mathcal{D}\right.\right) \tag{48}\] According to the total probability formula, we have \[p\left(\mathbf{x}_{1:K},\mathbf{c}_{1:K}\left|\mathbf{z}_{1:K-1},\mathcal{D}\right.\right)\] \[=p\left(\mathbf{x}_{K},\mathbf{c}_{K}\left|\mathbf{x}_{K-1}, \mathbf{c}_{K-1},\mathbf{z}_{1:K-1},\mathcal{D}\right.\right)\] \[\times p\left(\mathbf{x}_{1:K-1},\mathbf{c}_{1:K-1}\left|\mathbf{ z}_{1:K-1},\mathcal{D}\right.\right) \tag{49}\] Thus, (A) is further written as \[p\left(\mathbf{x}_{1:K},\mathbf{c}_{1:K}\left|\mathbf{z}_{1:K},\mathcal{D}\right.\right)\] \[=\frac{p\left(\mathbf{z}_{K}\left|\mathbf{x}_{K},\mathcal{D} \right.\right)p\left(\mathbf{x}_{K},\mathbf{c}_{K}\left|\mathbf{x}_{K-1}, \mathbf{c}_{K-1},\mathbf{z}_{1:K-1},\mathcal{D}\right.\right)}{p\left(\mathbf{z} _{K}\left|\mathbf{z}_{1:K-1},\mathcal{D}\right.\right)}\] \[\times p\left(\mathbf{x}_{1:K-1},\mathbf{c}_{1:K-1}\left|\mathbf{ z}_{1:K-1},\mathcal{D}\right.\right) \tag{50}\] For Eq. (50), the conditional independence expressed by Eqs. (6) and (10) leads to \[p\left(\mathbf{x}_{K},\mathbf{c}_{K}\left|\mathbf{x}_{K-1}, \mathbf{c}_{K-1},\mathbf{z}_{1:K-1},\mathcal{D}\right.\right)\] \[=p\left(\mathbf{x}_{K}\left|\mathbf{c}_{K},\mathbf{x}_{K-1}, \mathbf{z}_{1:K-1},\mathcal{D}\right.\right)\] \[\times p\left(\mathbf{c}_{K}\left|\mathbf{x}_{K-1},\mathbf{c}_{K-1},\mathbf{z}_{1:K-1},\mathcal{D}\right.\right)\] \[=\int p\left(\mathbf{x}_{K}\left|\mathbf{x}_{K-1},\Delta_{k}^{f}, \mathcal{D}\right.\right)P_{K-1}^{3}d\Delta_{k}^{f} \tag{51}\] Fig. 10: The localization RMSE (y-axis) comparison of MGBRNN and KalmanNet on the test set under different numbers of learnable parameters (x-axis). Fig. 9: **Localization results on the NCLT test data.** We present the localization results of the MGBRNN alongside several representative methods, which include KF, VBKF, and KalmanNet. MGBRNN demonstrates the highest accuracy with stable localization. For \(P_{K-1}^{3}\), considering the transfer relations in Eq. (8) and Eq. (6) yields \[P_{K-1}^{3}= p\left(\Delta_{k}^{f},\mathbf{c}_{K}\left|\mathbf{x}_{K-1}, \mathbf{c}_{K-1},\mathbf{z}_{1:K-1},\mathcal{D}\right.\right)\] \[= p\left(\Delta_{k}^{f}\left|\mathbf{c}_{K},\mathcal{D}\right. \right)p\left(\mathbf{c}_{K}\left|\mathbf{c}_{K-1},\mathbf{x}_{K-1},\mathbf{z }_{1:K-1},\mathcal{D}\right.\right) \tag{52}\] Based on Chapman-Kolmogorov equations for Eq. (51), the joint state-memory prediction density \(p\left(\mathbf{x}_{k},\mathbf{c}_{k}\left|\mathbf{z}_{1:k-1},\mathcal{D}\right.\right)\) can be obtained as Eqs. (12) - (14). Based on the Bayesian theorem, the joint state-memory update density can be obtained as \[p\left(\mathbf{x}_{k},\mathbf{c}_{k}\left|\mathbf{z}_{1:k}, \mathcal{D}\right.\right)=\frac{p\left(\mathbf{z}_{k}\left|\mathbf{x}_{k}, \mathcal{D}\right.\right)p\left(\mathbf{x}_{k},\mathbf{c}_{k}\left|\mathbf{z }_{1:k-1},\mathcal{D}\right.\right)}{p\left(\mathbf{z}_{k}\left|\mathbf{z}_{1 :k-1},\mathcal{D}\right.\right)} \tag{53}\] From Eq.(7) it follows that \(\mathbf{z}_{k}\) is only related to the current state \(\mathbf{x}_{k}\) and not to the memory \(\mathbf{c}_{k}\), thus \[p\left(\mathbf{z}_{k}\left|\mathbf{x}_{k},\mathcal{D}\right.\right)= p\left(\mathbf{z}_{k}\left|\mathbf{x}_{k},\mathcal{D}\right.\right)\] \[= \!\!\int p\left(\mathbf{z}_{k}\left|\Delta_{k}^{h},\mathbf{x}_{k} \right.\right)p\left(\Delta_{k}^{h}\left|\mathbf{x}_{k},\mathcal{D}\right. \right)d\Delta_{k}^{h} \tag{54}\] ## Appendix B Proof of the Gaussian approximation implementation The mean of the state prediction is calculated as: \[\mathbf{\hat{x}}_{k|k-1}= \mathrm{E}\left[\mathbf{x}_{k}\left|\mathbf{z}_{1:k-1},\mathcal{D}\right.\right]\] \[= E\left[\bar{f}_{k}\left(\mathbf{x}_{k-1}\right)+\Delta_{k}^{f}+ \mathbf{w}_{k}\left|\mathbf{z}_{1:k-1},\mathcal{D}\right.\right]\] \[= \!\!\int\!\!\!\int\!\!\!\int\left[\bar{f}_{k}\left(\mathbf{x}_{k -1}\right)+\Delta_{k}^{f}\right]P_{k}^{1}d\Delta_{k}^{f}d\mathbf{c}_{k}d \mathbf{c}_{k-1}d\mathbf{x}_{k-1} \tag{55}\] with \[P_{k}^{1}= p\left(\Delta_{k}^{f}\left|\mathbf{c}_{k},\mathcal{D}\right. \right)p\left(\mathbf{c}_{k}\left|\mathbf{x}_{k-1},\mathbf{c}_{k-1},\mathcal{D }\right.\right)\] \[\times p\left(\mathbf{x}_{k-1},\mathbf{c}_{k-1}\left|\mathbf{z}_{1:k-1 },\mathcal{D}\right.\right) \tag{56}\] and \[\int p\left(\mathbf{x}_{k-1},\mathbf{c}_{k-1}\left|\mathbf{z}_{1:k -1},\mathcal{D}\right.\right)d\mathbf{c}_{k-1}\] \[= p\left(\mathbf{x}_{k-1}\left|\mathbf{z}_{1:k-1},\mathcal{D}\right.\right)\] \[= N\left(\mathbf{x}_{k-1};\mathbf{\hat{x}}_{k-1\left|k-1}, \mathbf{P}_{k-1\left|k-1\right.}\right) \tag{57}\] Substituting \(p(\mathbf{c}_{k}\left|\mathbf{x}_{k-1},\mathbf{c}_{k-1},\mathcal{D}\right.)= N\left(\mathbf{c}_{k};\mathbf{\hat{c}}_{k},\mathbf{P}_{k}^{c}\right)\) and \(p(\Delta_{k}^{f}\left|\mathbf{c}_{k},\mathcal{D}\right.)=N(\Delta_{k}^{f}; \hat{\Delta}_{k}^{f},\mathbf{P}_{k}^{f})\) into Eq. (56), Eq. (55) can be calculated as Eq. (23). Considering the prediction residual is \(\varepsilon_{k}^{\tau}=\mathbf{x}_{k}-\mathbf{\hat{x}}_{k\left|k-1}\), the state prediction covariance is calculated as \[\mathbf{P}_{k|k-1}= \mathrm{E}\left[\varepsilon_{k}^{\tau}\varepsilon_{k}^{\tau\top} \left|\mathbf{z}_{1:k-1},\mathcal{D}\right.\right]\] \[= \!\!\int\!\!\!\int\!\!\!\int M_{k}^{f}P_{k}^{1}d\Delta_{k}^{f}d \mathbf{c}_{k}d\mathbf{c}_{k-1}d\mathbf{x}_{k-1} \tag{58}\] with \[M_{k}^{f}=\left(f_{k}\left(\mathbf{x}_{k-1}\right)+\Delta_{k}^{f}+\mathbf{w}_{ k}-\mathbf{\hat{x}}_{k\left|k-1}\right)\left(\cdot\right)^{\top} \tag{59}\] Substituting \(N(\mathbf{c}_{k};\mathbf{\hat{c}}_{k},\mathbf{P}_{k}^{c})\) and \(N(\Delta_{k}^{f};\hat{\Delta}_{k}^{f},\mathbf{P}_{k}^{f})\) into Eq. (58) while considering Eq. (57), then we have the covariance prediction as in Eq. (24). In the state update stage, we compute the state posterior according to the Bayesian rule: \[p\left(\mathbf{x}_{k}\left|\mathbf{z}_{1:k},\mathcal{D}\right.\right)=\frac{p \left(\mathbf{x}_{k},\mathbf{z}_{k}\left|\mathbf{z}_{1:k-1},\mathcal{D}\right. \right)}{p\left(\mathbf{z}_{k}\left|\mathbf{z}_{1:k-1},\mathcal{D}\right.\right)} \tag{60}\] The joint distribution of state prediction and measurement prediction is Gaussian [35], i.e., \[p\left(\mathbf{x}_{k},\mathbf{z}_{k}\left|\mathbf{z}_{1:k-1}, \mathcal{D}\right.\right)\] \[=N\left[\left(\begin{array}{c}\mathbf{\hat{x}}_{k\left|k-1}\\ \mathbf{\hat{z}}_{k\left|k-1}\end{array}\right.\right),\left(\begin{array}{c} \mathbf{P}_{k\left|k-1}&\mathbf{P}_{k\left|k-1}^{xz}\\ \left(\mathbf{P}_{k\left|k-1\right.}^{xz}\right)^{\top}&\mathbf{P}_{k\left|k-1 \right.}^{z}\end{array}\right)\right] \tag{61}\] Following the conclusions in [35], we substitute Eqs. (18) and (61) into Eq. (60) to obtain updates of the state and covariance as shown in Eqs. (25) and (26). The required \(\mathbf{\hat{z}}_{k\left|k-1\right.}\), \(\mathbf{P}_{k\left|k-1\right.}^{z}\), and \(\mathbf{P}_{k\left|k-1\right.}^{xz}\) are obtained by the following procedure. The mean value of the Gaussian measurement prediction is calculated as \[\mathbf{\hat{z}}_{k\left|k-1\right.}= \mathrm{E}\left[h_{k}\left(\mathbf{x}_{k}\right)+\Delta_{k}^{h} \left|\mathbf{z}_{1:k-1}\right.\right]\] \[= \!\!\int\!\!\int\!\!\!\int\left(h_{k}\left(\mathbf{x}_{k}\right)+ \Delta_{k}^{h}\right)\!P_{k}^{2}d\Delta_{k}^{h}d\mathbf{c}_{k}d\mathbf{x}_{k} \tag{62}\] with \[P_{k}^{2}=p\left(\Delta_{k}^{h}\left|\mathbf{x}_{k},\mathcal{D}\right.\right)p \left(\mathbf{x}_{k},\mathbf{c}_{k}\left|\mathbf{z}_{1:k-1},\mathcal{D}\right.\right) \tag{63}\] Substituting \(p\left(\Delta_{k}^{h}\left|\mathbf{x}_{k-1},\mathcal{D}\right.\right)=N( \Delta_{k}^{h};\hat{\Delta}_{k}^{h},\mathbf{P}_{k}^{h})\) into Eq. (63), Eq. (62) is computed as Eq. (27). Considering the measurement residuals is \(\sigma_{k}^{\tau}=\mathbf{z}_{k}-\mathbf{\hat{z}}_{k\left|k-1}\), the measurement prediction covariance is calculated as \[\mathbf{P}_{k\left|k-1\right.}^{z}= \mathrm{E}\left[\sigma_{k}^{z}(\sigma_{k}^{z})^{\top}\left| \mathbf{z}_{1:k-1}\right.\right]\] \[= \int\int\int M_{k}^{z}P_{k}^{2}d\Delta_{k}^{h}d\mathbf{c}_{k}d \mathbf{x}_{k} \tag{64}\] with \[M_{k}^{z}=\left(h_{k}\left(\mathbf{x}_{k}\right)+\Delta_{k}^{h}+\mathbf{v}_{k}- \mathbf{\hat{z}}_{k\left|k-1}\right.\right)\left(\cdot\right)^{\top}\]
2305.03350
Reconstructing Training Data from Multiclass Neural Networks
Reconstructing samples from the training set of trained neural networks is a major privacy concern. Haim et al. (2022) recently showed that it is possible to reconstruct training samples from neural network binary classifiers, based on theoretical results about the implicit bias of gradient methods. In this work, we present several improvements and new insights over this previous work. As our main improvement, we show that training-data reconstruction is possible in the multi-class setting and that the reconstruction quality is even higher than in the case of binary classification. Moreover, we show that using weight-decay during training increases the vulnerability to sample reconstruction. Finally, while in the previous work the training set was of size at most $1000$ from $10$ classes, we show preliminary evidence of the ability to reconstruct from a model trained on $5000$ samples from $100$ classes.
Gon Buzaglo, Niv Haim, Gilad Yehudai, Gal Vardi, Michal Irani
2023-05-05T08:11:00Z
http://arxiv.org/abs/2305.03350v1
# Reconstructing Training Data from ###### Abstract Reconstructing samples from the training set of trained neural networks is a major privacy concern. Haim et al. (2022) recently showed that it is possible to reconstruct training samples from neural network binary classifiers, based on theoretical results about the implicit bias of gradient methods. In this work, we present several improvements and new insights over this previous work. As our main improvement, we show that training-data reconstruction is possible in the multi-class setting and that the reconstruction quality is even higher than in the case of binary classification. Moreover, we show that using weight-decay during training increases the vulnerability to sample reconstruction. Finally, while in the previous work the training set was of size at most \(1000\) from \(10\) classes, we show preliminary evidence of the ability to reconstruct from a model trained on \(5000\) samples from \(100\) classes. ## 1 Introduction Understanding memorization in data-driven machine learning models is a fundamental question with implications on explainability, privacy, artistic synthesis and more. Haim et al. (2022) recently demonstrated that a large portion of the training samples are encoded in the parameters of trained neural network binary classifiers, by explicitly reconstructing samples from the training set of such Figure 1: Reconstructed training samples from a multi-class MLP classifier that was trained on \(500\) CIFAR10 images. Each column corresponds to one class and shows the \(10\) training samples (_red_) that were best reconstructed from this class, along with their reconstructed result (_blue_). models. The reconstruction method is based on consequences of the implicit bias of gradient descent, as presented by Lyu and Li (2019); Ji and Telgarsky (2020) - a homogeneous neural network trained with gradient descent will converge (in direction) to a solution of the KKT conditions of a maximum-margin problem. This dictates a set of equations that relates the parameters of the trained network and the training data. The key observation is that given a trained model (and its parameters), these relations can be leveraged to reconstruct training samples. Thus, a loss function is devised to show that by changing the inputs to the classifier (in order to minimize the loss), the inputs converge to true samples from the original training set. The work of Haim et al. (2022) had several limitations, namely: (1) Their work only showed reconstructions from binary classifiers; (2) For their reconstruction method to succeed the trained network needed to be initialized with very small weights, smaller than standard Xavier initialization (Glorot and Bengio, 2010); and (3) Their experiments consisted of only small datasets with at most \(1000\) samples. In this work we extend their results in several directions, and overcome some of the limitations while gaining new insights on this reconstruction method. Our contributions:(1) We show reconstruction of large portions of actual training samples from a trained _multi-class_ neural networks; (2) We show that the use of weight-decay enables reconstruction of samples from models trained with standard initialization schemes thus overcoming a major limitation of Haim et al. (2022); (3) We show reconstruction of models trained on datasets that are \(10\)x larger than shown in Haim et al. (2022); (4) We empirically analyze the effect of weight-decay on sample reconstruction, showing that it increases the vulnerability to such attacks. Related works.Several works have shown different privacy attacks in deep learning architectures, which aim to leak private information from trained models. For example, _Model inversion_ attacks aim at reconstructing class representatives Fredrikson et al. (2015); He et al. (2015); Yang et al. (2019). Other types of attacks target specific models, such as extracting data from _language models_ Carlini et al. (2019, 2021), which use crafted prompts; and information leakage from collaborative deep learning (federated learning) He et al. (2019); Melis et al. (2019); Huang et al. (2021); Hitaj et al. (2017). In Balle et al. (2022) a reconstruction attack is shown where the attacker knows all the training samples except for one. Recently, Carlini et al. (2023) showed extraction of actual training images from trained diffusion models. Their methods rely on generating many different images and using known membership inference attacks to determine which generated image was used as a training sample. We emphasize that their method is specific for generative models, whereas we focus on classifiers. ## 2 Preliminaries - Implicit Bias of Gradient Methods Neural networks are commonly trained using gradient methods, and when large enough, they are expected to fit the training data well. However, it is empirically known that these models converge to solutions that also generalize well to unseen data, despite the risk of overfitting. Several works pointed to the "_implicit bias_" of gradient methods as a possible explanation. One of the most prominent results in this area is by Soudry et al. (2018), who showed that linear classifiers trained with gradient descent on the logistic loss converge to the same solution as that of a hard-SVM, meaning that they maximize the margins. This result was later extended to non-linear and homogeneous neural networks by Lyu and Li (2019); Ji and Telgarsky (2020). Based on these results, Haim et al. (2022) have devised a data reconstruction scheme from trained binary classifiers (see Section 3 in Haim et al. (2022)). Below we describe an extension of the theorem about the implicit bias of homogeneous neural networks to a multi-class setup, based on theoretical results from Appendix G in Lyu and Li (2019). Formally, let \(S=\{(\mathbf{x}_{i},y_{i})\}_{i=1}^{n}\subseteq\mathbb{R}^{d}\times[C]\) be a multi-class classification training set where \(C\in\mathbb{N}\) is any number of classes, and \([C]=\{1,\ldots,C\}\). Let \(\Phi(\mathbf{\theta};\cdot):\mathbb{R}^{d}\rightarrow\mathbb{R}^{C}\) be a neural network parameterized by \(\mathbf{\theta}\in\mathbb{R}^{p}\). We denote the \(j\)-th output of \(\Phi\) on an input \(\mathbf{x}\) as \(\Phi_{j}(\mathbf{\theta};\mathbf{x})\in\mathbb{R}\). Consider a homogeneous network, minimizing the standard cross-entropy loss and assume that after some number of iterations the model correctly classifies all the training examples. Then, gradient flow will converge to a KKT point of the following maximum-margin problem: \[\min_{\mathbf{\theta}}\frac{1}{2}\left\|\mathbf{\theta}\right\|^{2}\quad\text{ s.t. }\quad\Phi_{y_{i}}(\mathbf{\theta};\mathbf{x}_{i})-\Phi_{j}(\mathbf{\theta};\mathbf{x}_{ i})\geq 1\ \ \forall i\in[n],\forall j\in[C]\setminus\{y_{i}\}\ . \tag{1}\] This KKT point is characterized by the following set of conditions: \[\mathbf{\theta}-\sum_{i=1}^{n}\sum_{j\neq y_{i}}^{c}\lambda_{i,j} \nabla_{\mathbf{\theta}}(\Phi_{y_{i}}(\mathbf{\theta};\mathbf{x}_{i})-\Phi_{j}(\mathbf{ \theta};\mathbf{x}_{i}))=\mathbf{0} \tag{2}\] \[\forall i\in[n],\forall j\in[C]\setminus\{y_{i}\}:\ \ \Phi_{y_{i}}(\mathbf{\theta};\mathbf{x}_{i})-\Phi_{j}(\mathbf{\theta};\mathbf{x}_{i})\geq 1\] (3) \[\forall i\in[n],\forall j\in[C]\setminus\{y_{i}\}:\ \ \lambda_{i,j}\geq 0\] (4) \[\forall i\in[n],\forall j\in[C]\setminus\{y_{i}\}:\ \ \lambda_{i,j}=0\text{ if }\Phi_{y_{i}}(\mathbf{\theta};\mathbf{x}_{i})-\Phi_{j}(\mathbf{ \theta};\mathbf{x}_{i})\neq 1 \tag{5}\] ## 3 Multi-Class Reconstruction We use a similar reconstruction method to Haim et al. (2022). Suppose we are given a trained classifier with parameters \(\mathbf{\theta}\), our goal is to find the set of data samples \(\{\mathbf{x}_{i}\}_{i=1}^{n}\) that the network trained on. A straightforward approach for such a loss would be to minimize the norm of the L.H.S of condition eq. (2). That is, we initialize \(\{\mathbf{x}_{i}\}_{i=1}^{m}\) and \(\{\lambda_{i,j}\}_{i\in[n],j\in[C]\setminus y_{i}}\) where \(m\) is a hyperparameter. Note that from eqs. (3) and (5), most \(\lambda_{i,j}\) zero out: the distance of a sample \(\mathbf{x}_{i}\) to its nearest decision boundary, \(\Phi_{y_{i}}-\max_{j\neq y_{i}}\Phi_{j}\), is usually achieved for a single class \(j\) and therefore (from eq. (5)) in this case at most one \(\lambda_{i,j}\) will be non-zero. For some samples \(\mathbf{x}_{i}\) it is also possible that all \(\lambda_{i,j}\) will vanish. We therefore turn to only optimizing on the distance from the decision boundary. This implicitly includes eq. (5) into the summation in eq. (2), dramatically reducing the number of summands, and simplifying the overall optimization problem. We define the following loss: \[L_{st}(\mathbf{x}_{1},...,\mathbf{x}_{m},\lambda_{1},...,\lambda_{m})=\left\| \mathbf{\theta}-\sum_{i=1}^{m}\lambda_{i}\ \nabla_{\mathbf{\theta}}[\Phi_{y_{i}}(\mathbf{x}_{i};\mathbf{\theta})-\max_{j\neq y_{ i}}\Phi_{j}(\mathbf{x}_{i};\mathbf{\theta})]\right\|_{2}^{2} \tag{6}\] Our reconstruction method is, given the parameters of a trained network \(\mathbf{\theta}\), initialize \(\mathbf{x}_{i}\) and \(\lambda_{i}\) for \(i=1,\dots,m\), and minimize equation 6. In order to make sure that eq. (4) is satisfied we optimize for \(a_{i}\) and require that \(\lambda_{i}=a_{i}^{2}\)1. This further simplifies the optimization problem compared to Haim et al. (2022) that use a separate loss function. Footnote 1: More precisely, \(\lambda_{i}=a_{i}^{2}+\lambda_{\text{min}}\), where \(\lambda_{\text{min}}\) is a hyperparameter that encourages the reconstructed samples to converge to margin-samples. Since \(n\) is unknown we set \(m\geq n\) which represents the number of samples we want to reconstruct (thus, we only need to upper bound \(n\)). We can hypothetically set \(m=C\cdot n\) and with balanced labels, this way there are enough reconstructed samples for any distribution of the labels. In practice, we set \(m\) to be slightly larger than \(n\), which is enough to get good reconstructions. The rest of the hyperparameters (including \(\lambda_{\text{min}}\)) are chosen using a hyper-parameter search. ## 4 Results ### Multiclass Reconstruction We compare between reconstruction from binary classifiers (as studied in Haim et al. (2022)) and multi-class classifiers. We conduct the following experiment: we train an MLP classifier with architecture \(D\)-\(1000\)-\(1000\)-\(C\) on \(500\) samples from the CIFAR10 (Krizhevsky et al., 2009) dataset. We use full-batch GD, and set the learning rate as \(0.5\). The model is trained to minimize the cross-entropy loss with full-batch gradient descent, once with two classes (\(250\) samples per class) and once for the full \(10\) classes (\(50\) samples per class). The test set accuracy of the models is \(77\%\)/\(32\%\) respectively, which is far from random (\(50\%\)/\(10\%\) resp.). To quantify the quality of our reconstructed samples, for each sample in the original training set we search for its nearest neighbour in the reconstructed images and measure the similarity using SSIM (Wang et al., 2004) (higher SSIM means better reconstruction). As a rule of thumb, we say that a sample was reconstructed well if its SSIM\(>0.4\) (see discussion in appendix A). In fig. 2 we plot the quality of reconstruction (in terms of SSIM) against the distance of the sample from the decision boundary \(\Phi_{y_{i}}(\mathbf{x}_{i};\boldsymbol{\theta})-\max_{j\neq y_{i}}\Phi_{j}( \mathbf{x}_{i};\boldsymbol{\theta})\). As seen, a multi-class classifier yields much more samples that are vulnerable to being reconstructed. Next, we examine the dependence between the ability to reconstruct from a model and the number of classes on which it was trained. Comparing between two models trained on different number of classes is not immediately clear, since we want to isolate the effect of the number of classes from the size of the dataset (it was observed by Haim et al. (2022) that the number of reconstructed samples decreases as the total size of the training set increases). We therefore train models on training sets with varying number of classes (\(C\in\{2,3,4,5,10\}\)) and varying number of samples per class (\(1,5,10,50\)). The results are visualized in fig. 2(a). Note that for models with same number of samples per class, the ability to reconstruct _increases_ with the number of classes, even though the total size of the training set is larger. This further validates our hypothesis that multi-class models are more vulnerable to reconstruction. We continue this study in appendix B. Another way to validate this hypothesis is by showing the dependency between the number of classes and the number of "good" reconstructions (SSIM\(>0.4\)) - shown in fig. 2(b). As can be seen, training on multiple classes yields more samples that are vulnerable to reconstruction. A possible intuitive explanation, is that multi-class classifiers have more "margin" samples. Since margin-samples are more vulnerable to reconstruction, this results in more samples being reconstructed from the model. ### Weight Decay Increases Reconstructability Another drawback of Haim et al. (2022) is that reconstruction was only shown for models whose first fully-connected layer was initialized with small (non-standard) weights. Models with standard initialization, such as Kaiming He et al. (2015) or Xavier Glorot and Bengio (2010) where each weight vector is initialized with a variance of \(\sim\frac{1}{d}\) (where \(d\) is the input's layer dimension) did not yield good reconstructed samples. Haim et al. (2022) only reconstructed from networks initialized with a variance of \(\sim\frac{1}{d^{2}}\). Set to better understand this drawback, we observed an interesting phenomenon - for models with standard initialization, using weight-decay during training enabled samples reconstruction. Moreover, for some values of weight-decay the reconstructability is _significantly higher Figure 4: Using weight-decay during training increases vulnerability to sample reconstruction Figure 2: Multi-class classifiers are more vulnerable to training-set reconstruction. For a training set of size \(500\), a multi-class model (_left_) yields much more reconstructed samples with good quality (SSIM\(>0.4\)), than a binary classification model (_right_). than what was observed for models with small-initialized-first-layer models. In fig. 4 we show the number of good reconstructed samples for different choices of the value of the weight decay (\(\lambda_{\text{WD}}\)). We show results for two models trained on \(C=2\) classes (fig. 4_left_) and \(C=10\) classes (fig. 4_right_), both trained on \(50\) samples per class. We add two baselines trained without weight-decay: model trained with standard initialization (_black_) and model with small-initialized-first-layer (_red_). By looking at the exact distribution of reconstruction quality to the distance from the margin, we observe that weight-decay (for some values) results in more training samples being on the margin of the trained classifier, thus being more vulnerable to reconstruction. This observation is shown in fig. 5 where we show the plots for all experiments from fig. 4_left_. We also provide the train and test errors for each model. It seems that the generalization (test error) does not change significantly. However, an interesting observation is that reconstruction is possible even for models with non-zero training errors (for which, the assumptions of Lyu & Li (2019) do not hold). Figure 5: Weight-Decay “pushes” more samples to the margin, thus enabling them to be reconstructed Figure 3: Evaluating effect of multiple classes on the ability to reconstruct. We show reconstructions from models trained with different number of classes and different number of samples per class. As seen, multiple classes result in more reconstructed samples. ### Reconstruction From a Larger Number of Samples One of the major limitations of Haim et al. (2022) is that they reconstruct from models that trained on a relatively small number of samples. Specifically, in their largest experiment, a model is trained with only \(1000\) samples. Here we take a step further, and apply our reconstruction scheme for a model trained on \(5000\) data samples. To this end, we trained a 3-layer MLP, where the number of neurons in each hidden layer is \(10,000\). Note that the size of the hidden layer is \(10\) times larger than in any other model we used. Increasing the number of neurons seems to be one of the major reasons for which we are able to reconstruct from such large datasets, although we believe it could be done with smaller models, which we leave for future research. We used the CIFAR100 dataset, with 50 samples in each class, for a total of \(5000\) samples. In fig. 5(a) we give the best reconstructions of the model. Note that although there is a degradation in the quality of the reconstruction w.r.t a model trained on less samples, it is still clear that our scheme can reconstruct some of the training samples to some extent. In fig. 5(b) we show a scatter plot of the SSIM score w.r.t the distance from the boundary, similar to fig. 2(a). Although most of the samples are on or close to the margin, only a few dozens achieve an SSIM\(>0.4\). This may indicate that there is a potential for much more images to reconstruct, and possibly with better quality. ## 5 Conclusions and Future Work In this paper we have shown several improvements over Haim et al. (2022). Most notably, we have shown that it is possible to reconstruct training data in a multi-class setting, compared to only a binary classification setting in the previous work. Additionally, Haim et al. (2022) showed reconstructions only from networks trained with small initialization. Here we show reconstructions from networks trained with weight decay, which is much more standard than a small initialization scale. Finally, we show it is possible to reconstruct from models trained on \(5000\) data samples, which is 5 times more than the largest trained model in Haim et al. (2022) Figure 6: Reconstruction from a model trained on \(50\) images per class from the CIFAR100 dataset (\(100\) classes, total of \(5000\) datapoints) There are a couple of future research directions that we think might be interesting. First, to extend our reconstruction scheme to more practical models such as CNN and ResNets. Second, to reconstruct from models trained on more data, such as the entire CIFAR 10/100 datasets, or different types of data such as text, time-series or tabular data. Finally, it would be interesting to find privacy schemes which could protect from reconstruction attacks by specifically protecting samples which lie on the margin. #### Acknowledgments This project received funding from the European Research Council (ERC) under the European Union's Horizon 2020 research and innovation programme (grant agreement No 788535), and ERC grant 754705, and from the D. Dan and Betty Kahn Foundation. GV acknowledges the support of the NSF and the Simons Foundation for the Collaboration on the Theoretical Foundations of Deep Learning.
2307.13909
Graph Neural Networks-based Hybrid Framework For Predicting Particle Crushing Strength
Graph Neural Networks have emerged as an effective machine learning tool for multi-disciplinary tasks such as pharmaceutical molecule classification and chemical reaction prediction, because they can model non-euclidean relationships between different entities. Particle crushing, as a significant field of civil engineering, describes the breakage of granular materials caused by the breakage of particle fragment bonds under the modeling of numerical simulations, which motivates us to characterize the mechanical behaviors of particle crushing through the connectivity of particle fragments with Graph Neural Networks (GNNs). However, there lacks an open-source large-scale particle crushing dataset for research due to the expensive costs of laboratory tests or numerical simulations. Therefore, we firstly generate a dataset with 45,000 numerical simulations and 900 particle types to facilitate the research progress of machine learning for particle crushing. Secondly, we devise a hybrid framework based on GNNs to predict particle crushing strength in a particle fragment view with the advances of state of the art GNNs. Finally, we compare our hybrid framework against traditional machine learning methods and the plain MLP to verify its effectiveness. The usefulness of different features is further discussed through the gradient attribution explanation w.r.t the predictions. Our data and code are released at https://github.com/doujiang-zheng/GNN-For-Particle-Crushing.
Tongya Zheng, Tianli Zhang, Qingzheng Guan, Wenjie Huang, Zunlei Feng, Mingli Song, Chun Chen
2023-07-26T02:18:04Z
http://arxiv.org/abs/2307.13909v1
# Graph Neural Networks-based Hybrid Framework For Predicting Particle Crushing Strength ###### Abstract Graph Neural Networks have emerged as an effective machine learning tool for multi-disciplinary tasks such as pharmaceutical molecule classification and chemical reaction prediction, because they can model non-euclidean relationships between different entities. Particle crushing, as a significant field of civil engineering, describes the breakage of granular materials caused by the breakage of particle fragment bonds under the modeling of numerical simulations, which motivates us to characterize the mechanical behaviors of particle crushing through the connectivity of particle fragments with Graph Neural Networks (GNNs). However, there lacks an open-source large-scale particle crushing dataset for research due to the expensive costs of laboratory tests or numerical simulations. Therefore, we firstly generate a dataset with 45,000 numerical simulations and 900 particle types to facilitate the research progress of machine learning for particle crushing. Secondly, we devise a hybrid framework based on GNNs to predict particle crushing strength in a particle fragment view with the advances of _state-of-the-art_ GNNs. Finally, we compare our hybrid framework against traditional machine learning methods and the plain MLP to verify its ef fectiveness. The usefulness of different features is further discussed through the gradient attribution explanation _w.r.t_ the predictions. Our data and code are released at [https://github.com/doujiang-zheng/GNN-For-Particle-Crushing](https://github.com/doujiang-zheng/GNN-For-Particle-Crushing). keywords: Graph Neural Networks, Model Explanation, Civil Engineering, Particle Crushing, Size Effect + Footnote †: journal: Journal of Computational Physics ## 1 Introduction Graph, as an abstract data structure, describes the complex relationships among various entities, such as the billions of directed links between webpages on the Internet Page et al. (1999), the chemical bonds between atoms in the chemical engineering Gilmer et al. (2017), the COVID-19 spread between people in the social networks Chang et al. (2021). Recently, with the development of deep learning techniques LeCun et al. (2015), Graph Neural Networks (GNNs) Kipf and Welling (2017); Bronstein et al. (2017) have advanced the representation learning of graphs in multiple disciplinary tasks Gilmer et al. (2017); Vlassis et al. (2020); Zhang et al. (2023) by stacking non-linear graph convolution layers over the graph topology. In civil engineering, numerical simulations usually treat a particle as a combination of several randomly tessellated particle fragments Hu et al. (2022); de Bono and McDowell (2014); Fu et al. (2017); Cheng et al. (2004); Huillca et al. (2021), and investigate the mechanical behaviors of particles under the external load based on the breakage of fragment bonds, which motivates us to handle the particle prediction tasks with the _state-of-the-art_ GNNs. In the civil engineering, particles would break into several smaller fragments under the structural loads due to the surface flaws Ma et al. (2022) or the internal flaws Ma et al. (2014); Huillca et al. (2021); Griffith (1921), leading to the degradation of mechanical properties Lade et al. (1996); Nakata et al. (1999); Ovalle et al. (2014); Cantor et al. (2017), which could cause serious consequences such as the excessive and dangerous settlement of buildings Hardin et al. (1985); McDowell and Bolton (1998); Zhu and Zhao (2019); Lade et al. (1996); Nakata et al. (1999); Ovalle et al. (2014); Nader et al. (2019). Recent research of particle crushing has largely extended the investigation of particle crushing from a single particle McDowell and Amon (2000) to particles with different mechanical properties such as particle sizes Huang et al. (2014); Huillca et al. (2021), particle shapes Fu et al. (2017); Hu et al. (2022); Zhu and Zhao (2021), and particle morphology Sun et al. (2021); Wang et al. (2021); Ma et al. (2022). These dedicated heuristics of particle properties are summarized as morphology descriptors of particles in Wang et al. (2021), which can be divided into the form descriptors, the roundness descriptors, and the sphericity descriptors. Despite the effectiveness of morphology descriptors, they are far away from the particle crushing mechanisms investigated by existing numerical simulation methods Hu et al. (2022); de Bono and McDowell (2014); Fu et al. (2017); Cheng et al. (2004); Huillca et al. (2021). These methods model a particle as a polyhedron of the connected fragments and obtain the particle states at each time step by solving the displacements of different fragments, which investigates particle crushing in a microscopic view instead of the morphology view. The simulated particle crushing process inspires us to model the particle as a connected fragment graph and advance the representation of particles from morphology descriptors to their internal mechanisms. Furthermore, unlike the machine learning community that has released various datasets, there lacks an open-source dataset of particle crushing, which significantly hinders the development of its machine learning research. Therefore, we firstly provide an open-source large-scale particle crushing dataset of 45,000 particles by simulating the crushing process of a single rockfill particle under one-dimensional (1D) compression with the Non-Smooth Contact Dynamics (NSCD) method following Hu et al. (2022). The particle crushing dataset consists of 900 different particle types, with 20 different particle diameters, 15 different particle shapes, and 3 different compression axes. Each type of particle is randomly tessellated into multiple polyhedron fragments by the Neper Kun and Herrmann (1996); Nguyen et al. (2015); Quey et al. (2011) with the specific diameter and shape. The tessellated particle is then compressed by two rigid parallel platens along the specific compression axis, following a DEM model with a three-dimensional bonded-cell method Huillca et al. (2021). The numerical model was implemented in the software LMGC90 Dubois and Mozul (2013), which is based on the non-smooth contact dynamics method Rafiee et al. (2008, 2011). Secondly, we model the particle fragments as a connected fragment graph to utilize _state-of-the-art_ machine learning tools for particle representation. The interacted fragments of a particle could be seen as a connected graph, where each fragment acts as a vertice and interacts with other fragments during the particle crushing process. The complex interaction between fragments could be learned by the emerging Graph Neural Networks (GNNs) Bronstein et al. (2017); Kipf and Welling (2017); Xu et al. (2019) with the large-scale particle crushing dataset. We are inspired by these encouraging applications of GNNs Feng et al. (2019); Chang and Cheng (2020); Schulte-Sasse et al. (2021); Ying et al. (2021); Yang et al. (2020); Zhang et al. (2021); Addanki et al. (2021); Vlassis et al. (2020) to build a GNNs-based hybrid framework to combine GNNs based on the fragment graph with MLP based on the dedicated morphology descriptors, predicting the characteristic crushing strength of particles on the newly given particles in the testing set. Finally, we have conducted experiments to examine the prediction performance of our proposed hybrid framework, the effectiveness of different components, and the attributions of the calculated features. To validate the generalization ability of different methods, we propose three kinds of testing sets to construct three different tasks, which are split by the diameter, shape, and compression axis, respectively. We have calculated geometric descriptors as described in Huang et al. (2014); Huillca et al. (2021); Fu et al. (2017); Hu et al. (2022); Zhu and Zhao (2021); Sun et al. (2021) and compared five traditional machine learning methods Pedregosa et al. (2011); Chen and Guestrin (2016); Ke et al. (2017) (denoted as non-Deep methods) against a bunch of Deep Neural Networks (DNNs) including three kinds of _state-of-the-art_ GNNs Feng et al. (2019); Xu et al. (2019); Yang et al. (2020), where GNNs are implemented using our hybrid framework. The contributions of the morphology descriptors for MLP and the node and edge features for GNNs are further verified through the ablation studies on three GNNs across three different tasks. The common and individual patterns of the three tasks are analyzed through the visualization results of feature attributions based on the gradient norms. The main contributions can be summarized as follows: * We generate a large-scale particle crushing dataset to facilitate the machine learning research of this field, comprising 45,000 numerical simulations with 900 different particle types. * We build a GNNs-based hybrid framework to model a particle with elementary cell interactions and its overall morphology descriptors for predicting the particle crushing strength across three different tasks. * We have conducted elaborate comparison experiments and ablation studies to investigate the effectiveness of GNNs, particle morphology descriptors, and features for nodes and edges. We further visualize the common and individual patterns through the saliency map of different features. ## 2 Related Works ### Graph Neural Networks Graph Neural Networks (GNNs) have shown their powerful prediction abilities on the non-grid data and have been applied to various fields such as Recommendation Ying et al. (2018), traffic flow prediction Yu et al. (2018), and molecular classification Gilmer et al. (2017); Xu et al. (2019); Yang et al. (2020); Ying et al. (2021). A graph is defined by a node set \(V=\{v_{1},\cdots,v_{n}\}\) and an associated edge set \(E=\{e_{1},\cdots,e_{m}\}\), where \(e_{1}\) connects a pair of adjacent fragments \(v_{i}\) and \(v_{j}\). The message-passing paradigm Gilmer et al. (2017) describes GNNs in a microscopic view that each node \(v_{i}\) receives the messages from its neighbors \(v_{j}\in\mathcal{N}(v_{i})\) and updates its representation based on these messages, written as: \[\begin{split}\mathbf{m}_{i}^{k}&=\sum_{v_{j}\in \mathcal{N}(v_{i})}\mathbf{M}_{k}(\mathbf{h}_{i}^{k},\mathbf{h}_{j}^{k}, \mathbf{e}_{ij}),\\ \mathbf{h}_{i}^{k+1}&=\mathbf{U}_{k}(h_{i}^{k}, \mathbf{m}_{i}^{k}),\end{split} \tag{1}\] where \(v_{i}\) updates from \(\mathbf{h}_{i}^{k}\) of the \(k\)-th layer to \(\mathbf{h}_{i}^{k+1}\) of \(k+1\)-th layer based on the message function \(\mathbf{M}_{k}\) and the update function \(\mathbf{U}_{k}\). The obtained node representation \(\mathbf{h}_{i}\) can be used for various tasks such as node classification Kipf and Welling (2017) and link prediction Ying et al. (2018). It requires a readout function to generate a representation vector for the whole graph \(G\) for graph-level tasks like molecular classification Gilmer et al. (2017); Xu et al. (2019); Yang et al. (2020); Ying et al. (2021), written as \[\mathbf{h}_{G}=\mathbf{R}(\{\mathbf{h}_{i}^{K}|v_{i}\in V\}), \tag{2}\] where \(K\) is the number of neural network layers. Furthermore, GNNs have proved their applications in various fields, such as predicting the deformation of 3D objects given the 3D meshed data points Feng et al. (2019), generating artificial building structures to alleviate the efforts of experts Chang and Cheng (2020), predicting the HOMO-LUMO energy gap of molecules given their 2D molecular graphs Schulte-Sasse et al. (2021); Ying et al. (2021); Yang et al. (2020); Zhang et al. (2021); Addanki et al. (2021), and predicting the homogenized responses of polycrystals Vlassis et al. (2020). ### Particle Crushing McDowell _et al._McDowell and Amon (2000) have found that the particle crushing strength of geometrically similar particles follows a Weibull distribution, written as \[P_{s}=\exp\left[-\left(\frac{d_{s}}{d_{0}}\right)^{3}\left(\frac{\sigma}{ \sigma_{0}}\right)^{m}\right], \tag{3}\] where \(P_{s}\) is the breakage ratios under the corresponding load, \(d_{0}\) and \(\sigma_{0}\) are the characteristic diameter and crushing strength, respectively. The survival probability of a batch of 50 particles with the same geometry is drawn in Fig. 6, sorting by the normalized particle strength, where \(m=9.690\) is the Weibull modulus and indicates the variability of the particle crushing distribution. The characteristic particle strength is thus scaled to 1.0 of the horizontal axis and corresponds to the 37% survival probability of the vertical axis. Existing particle crushing theories McDowell and Amon (2000); Sun et al. (2021); Wang et al. (2021) derive a closed-form formula to describe the size effects of particles with different diameters. However, firstly, their various theories have been proposed from different perspectives and lacked a consensus on particle crushing behaviors. Secondly, our experimental results of the non-Deep methods and DNNs in Tab. 3 reveal that particle morphology descriptors play a vital role in the generalization of predicting the particle crushing strength while existing theories are mostly based on the particle diameter. Thirdly, generalizing the predictions for more conditions like particle shapes and compression axes requires a constitutive model to describe the particle from different viewpoints. Therefore, we are motivated to model the fragment connection of the particle with Graph Neural Networks (GNNs), which offer natural modeling for the fragment graph. ## 3 Method As shown in Fig. 1, we first conduct numerical simulations for 900 particle types with different diameters, shapes, and compression axes to measure the characteristic particle crushing strength. Secondly, we build a hybrid framework to combine the _state-of-the-art_ GNNs with the MLP network to predict the strength of the Diameter, Shape, and Axis tasks and validate the generalization ability of DNNs and GNNs. Lastly, we quantitatively attribute the input contributions to the predictions and analyze the common and individual patterns of the three tasks. ### Dataset Generation To overcome the limitations of small-scale datasets of existing researches Huang et al. (2014); Huillca et al. (2021); Fu et al. (2017); Hu et al. (2022); Sun et al. (2021); Zhu and Zhao (2019b); Wang et al. (2021); Nguyen et al. (2015), we firstly generate 45,000 particles and simulate their crushing processes based on numerical simulations Hu et al. (2022); de Bono and McDowell (2014); Fu et al. (2017); Cheng et al. (2004); Huillca et al. (2021). As shown in Tab. 1, there are 900 different particle types in total, the Cartesian product of 20 different particle diameters, 15 different scale shapes in the (X, Y, Z) axes, and 3 different compression axes under one-dimensional compression. Each type contains 50 particle crushing tests McDowell and Amon (2000); Hu et al. (2022); Sun et al. (2021) to estimate the characteristic crushing strength of the specific particle type, where each test is based on a randomly tessellated particle. The comprehensive large-scale dataset can measure the generalization ability of the _state-of-the-art_ machine learning methods from the three aspects of diameter, shape, and axis, and examine the feature attributions with respect to the predictions of particle crushing strength based on the well-trained models. The top row of Fig. 1 describes the crushing process of an example particle Figure 1: The pipeline of our work consists of three parts, where the **generation** part means the large-scale dataset, the **prediction** part means the graph construction of each particle and the hybrid framework for particle crushing strength, and the **explanation** part visualizes the importance of different features w.r.t their gradient magnitudes. compressed by two plates, where the particle stress drops drastically from the peak when the particle breaks into pieces McDowell and Amon (2000); Huillca et al. (2021) as shown in the stress curve with respect to the time step. The particle strength is computed by \(\sigma=F_{c}/d^{2}\), where \(F_{c}\) is the peak stress and \(d\) is the distance between two plates, serving as a data point in a batch of particle crushing tests of a specific particle type, which is given the specific diameter, shape, and axis. As shown in the top right plot of Fig. 1, the batch of particle crushing tests fits the Weibull statistics by sorting the particle strength in an ascending order, where the particle strength is normalized by the characteristic particle strength \(\sigma_{0}\) at 37% survival probability. When increasing the particle strength, the survival probability \(P_{s}\) of the batch of particles decreases exponentially fast at \(P_{s}=\exp(-x^{9.690})\) with \(R^{2}=0.8948\), where the Weibull modulus 9.690 depicts the sharpness of the strength-probability curve. As shown in previous researches Huang et al. (2014); Huillca et al. (2021); Fu et al. (2017); Hu et al. (2022); Sun et al. (2021); Zhu and Zhao (2019); Wang et al. (2021); Nguyen et al. (2015), when individually and jointly varying the conditions of diameter, shape, and axis, different particle types exhibit distinct mechanical \begin{table} \begin{tabular}{l|l} \hline \hline Dimension & Setting \\ \hline Diameter (mm) & 11.86, 13.10, 14.35, 15.60, 16.85, 18.10, 19.34, \\ & 20.59, 21.84, 23.09, 24.34, 25.58, 26.83, _28.08_, \\ & _29.33, 30.58, 31.82, 33.07, 34.32, 35.57_ \\ \hline Scale Shape (X, Y, Z) & (1,1,1),_(1/0.95,0.95,1)_,(1/0.9,0.9,1), \\ & (1.1,1.1,1),_(1.25,1.21/1.25,1)_,(1.21/0.9,0.9,1), \\ & (1.2,1.2,1),_(1.25,1.44/1.25,1)_,(1.5,1.44/1.5,1), \\ & (1.3,1.3,1),_(1.25,1.69/1.25,1)_,(1.5,1.69/1.5,1), \\ & (1.4,1.4,1),_(1.25,1.96/1.25,1)_,(1.5,1.96/1.5,1) \\ \hline Compression Axis & X-axis, _Y-axis_, Z-axis \\ \hline \hline \end{tabular} \end{table} Table 1: Configuration of particle crushing dataset. The _italic_ font refers to the testing settings. properties. Therefore, it is of vital importance to generalize prediction models from the comprehensive training set to the unseen testing set, capturing the macroscopic properties of granular materials. In the numerical simulation of a particle compression test, a randomly tessellated particle by Neper Kun and Herrmann (1996); Nguyen et al. (2015); Quey et al. (2011) is firstly meshed by Gmsh Geuzaine and Remacle (2009) and then compressed by two rigid plates using LMGC90 Dubois and Mozul (2013) with a Non-Smooth Contact Dynamics (NSCD) Jean (1999); Rafiee et al. (2008, 2011) method. Firstly, a batch of 50 particles is randomly tessellated into fragments for a specific particle type following the Voronoi tessellation algorithm Quey et al. (2011) to simulate the fragment size distributions of realistic rockfill particles. Secondly, the numerical model implemented by LMGC90 Dubois and Mozul (2013) solves the displacements of particle fragments by computing the contact forces of each body following the Signorini-Coulomb condition Jean and Moreau (1992); Moreau (1988) and the Cohesive Zone Model (CZM) model Hu et al. (2022); Huillca et al. (2021). The simulated particle breaks into pieces when the CZM bonds of particle fragments break due to external loadings. As shown in Fig. 1, the peak force of particle crushing is recorded when a drastic drop of more than 35% of the force is observed in the time step-force curve, indicating the particle breakage phenomenon Wang et al. (2021); Huillca et al. (2021); Hu et al. (2022). Finally, we summarize the parameter settings of the particle generation process as follows. In the particle tessellation process, the number of particle fragments is initialized by 8 with a diameter of 11.86 mm and increases cubically from 8 to 216 with respect to the diameter, ensuring the constant cell density following that the internal flaws of particles increase with the increasing particle size Griffith (1921). In the particle crushing process, the friction coefficient between the rigid plates and the particle is set to 0.3 with a constant vertical velocity of the upper plate, the time step is set to \(5\times 10^{-4}\)s, and the CZM parameters of particles are calibrated by the commonly adopted Brazilian splitting test Jiang and Meng (2018); Yu and Yin (2004). To examine the generalization ability of machine learning methods, the ratios of the testing set are set to 7/20, 5/15, 1/3 in terms of different diameters, shapes, and axes, respectively. ### Problem Setup of Predicting Particle Crushing Strength Given a detailed 3D mesh of a particle and its fragments, the regression task of predicting the characteristic particle crushing strength \(\sigma_{0}\) is written as \[\operatorname*{arg\,min}_{\mathcal{F}}\sum_{\mathbf{x}\in\mathbf{X},\mathbf{y }\in\mathbf{Y}}\|\mathbf{y}-\mathcal{F}(\mathbf{x})\|_{2}+\lambda\Omega( \mathcal{F}), \tag{4}\] where \(\mathbf{x},\mathbf{y}\) are the particle and its \(\sigma_{0}\), \(\mathbf{X},\mathbf{Y}\) are the sets of input particles and their prediction labels, \(\mathcal{F}\) is a machine learning method, the task is optimized by the Mean Squared Error (MSE) loss between the labels \(\mathbf{y}\) and the predictions \(\mathcal{F}(x)\) and a regularization term \(\Omega(\mathcal{F})\) reducing the complexity of \(\mathcal{F}\), and \(\lambda\) is a tunable coefficient. Based on the 3D mesh \(\mathbf{x}\) of a particle, we follow the particle morphology descriptors of existing researches Blott and Pye (2008); Bagheri et al. (2015); Huang et al. (2020); Domokos et al. (2015); Pouranian et al. (2020); Zhao and Wang (2016); Yang et al. (2017); Zheng et al. (2021); Zhang et al. (2016), which have shown dominant impacts on the crushing strength. As summarized by Wang et al. (2021), there are thirty-five particle morphology descriptors, including nine geometric characteristics Wang et al. (2021), thirteen form descritpors Blott and Pye (2008); Bagheri et al. (2015); Huang et al. (2020); Domokos et al. (2015), three roundness descritpors Pouranian et al. (2020); Huang et al. (2020); Zhao and Wang (2016), nine sphericity descriptors Blott and Pye (2008); Pouranian et al. (2020); Yang et al. (2017); Zheng et al. (2021); Huang et al. (2020); Zhang et al. (2016), and one instability descriptor Wang et al. (2021). These particle morphology descriptors are fed into traditional machine learning methods for predicting the particle crushing strength, including Linear Regression, Ridge Regression, Random Forest (RF), XGBoost (XGB) Chen and Guestrin (2016), and LightGBM (LGB) Ke et al. (2017). The former two are linear methods, and the latter three are ensemble tree-based methods, which can capture complex patterns of morphology descriptors. We further apply a Multi-Layer Perceptron (MLP) to model the multivariate relationships of various morphology descriptors, which serves as the baseline method to verify the effectiveness of deep learning methods and Graph Neural Networks (GNNs). ### GNNs-based Hybrid Framework Despite their significant efforts, morphology descriptors mostly work based on insightful observations of researchers and hardly take the internal structure of particles into account, which plays an essential role in the particle crushing process as shown in previous literatures McDowell and Bolton (1998); Daouadji et al. (2001); Russell and Khalili (2004); Tengattini et al. (2016); Ma et al. (2022). In a numerical simulation, a particle is divided into multiple fragments randomly Quey et al. (2011) and breaks into pieces due to the breakage of the CZM bonds of fragments Hu et al. (2022). The mutual relationships of particle fragments thus influence the particle crushing behaviors significantly, which can doubtlessly help the predictions if the internal structure is considered. Let \(V=\{v_{1},\cdots,v_{n}\}\) be the fragment set of a particle, where \(v_{1}\) is one of the fragments, and \(n\) is the number of fragments. The mutual relationships of \(V\) can be well described by an edge set \(E=\{e_{1},\cdots,e_{m}\}\), where \(e_{1}\) connects a pair of adjacent fragments \(v_{i}\) and \(v_{j}\). The consequent fragment graph \(G=\{V,E\}\) describes the internal structure of a particle, which can output the latent representation of the particle using _state-of-the-art_GNNs Feng et al. (2019); Xu et al. (2019); Yang et al. (2020). As shown in Fig. 1, GNNs use the fragment graph of particles as the inputs and predict the corresponding particle crushing strength \(\sigma_{0}\) in terms of different diameters, shapes, and axes, which can be written as \[\operatorname*{arg\,min}_{\mathbf{g}}\sum_{\mathbf{x}\in\mathbf{X},\mathbf{y }\in\mathbf{Y}}\|\mathbf{y}-\mathbf{g}(\mathbf{x},G)\|_{2}+\lambda\Omega( \mathbf{g}), \tag{5}\] where \(\mathbf{g}\) is one kind of GNNs. On the one hand, GNNs can summarize the latent representations from the fragment level to the particle level by aggregating neighborhood information iteratively with the fragment graph, complementing the missing microscopic interactions of fragments of particle morphology descriptors. On the other hand, dedicated efforts for particle morphology descriptors can largely alleviate the task difficulty of predicting particle crushing strength \(\sigma_{0}\), which is verified by Fig. 2. Therefore, we build a hybrid framework of a GNN and an MLP by summing their predictions to advance the training of GNNs, written as \(\mathbf{g}^{\prime}=\mathbf{g}(\mathbf{x},G)+\mathrm{MLP}(\mathbf{x})\). We further prepare eleven node features and nine edge features for the fragment graph to characterize the internal states of particles, where a node is a particle fragment and an edge is the interaction between a pair of fragments. Following Vlassis et al. (2020), the states of a node are represented by its volume, its external area, diameter, the number of its external faces, the number of its neighborhood fragments, the 3D coordinates of its centroid, and its three Euler angles, which are computed by its mesh file generated by Neper Quey et al. (2011). Similarly, the edge states are represented by the contact area of fragments, the number of lines of the contact area, the maximum length of the contact area, the 3D coordinates of its centroid, and its three Euler angles. These node and edge features are then fed into GNNs for the latent representations of particles. ## 4 Experiment ### Performance Comparison We split different testing sets of different diameters, shapes, and axes to examine the task difficulty and generalization ability of methods. The com \begin{table} \begin{tabular}{c c c c} \hline \hline Quantile & **Diameter** (MPa) & **Shape** (MPa) & **Axis** (MPa) \\ \hline min & 5.09 & 5.54 & 5.09 \\ 25\% & 8.05 & 9.09 & 7.49 \\ 50\% & 10.13 & 11.27 & 8.80 \\ 75\% & 13.38 & 14.70 & 10.04 \\ max & 21.71 & 33.34 & 17.62 \\ \hline \hline \end{tabular} \end{table} Table 2: The distribution of particle crushing strength in the testing sets. pared methods include the _state-of-the-art_ machine learning methods (denoted as non-Deep methods) Pedregosa et al. (2011); Chen and Guestrin (2016); Ke et al. (2017) and the _state-of-the-art_ Deep Neural Networks (DNNs) Feng et al. (2019); Xu et al. (2019); Yang et al. (2020), aims at validating whether DNNs are superior to non-Deep methods and whether GNNs are superior to other DNNs. For three tasks of the Diameter, Shape, and Axis, we have tried numerous hyper-parameter settings of methods for a fair comparison of prediction ability and stability, where each setting takes 5 runs of fixed random seeds for reproducibility, as listed in Tab. C.9, Tab. C.10, and Tab. C.11. For non-Deep methods, there are 15 runs for Linear Regression, 60 runs for Ridge Regression, 675 runs for Random Forest, 5625 runs for XGBoost Chen and Guestrin (2016), and 5625 runs for LightGBM Ke et al. (2017). For DNNs, there are 225 runs for MLP, 675 runs for MeshNet Feng et al. (2019), 855 runs for GIN Xu et al. (2019), and 540 runs for ExpC Yang et al. (2020), where each setting takes 5 \begin{table} \begin{tabular}{l c c c} \hline \hline & **Diameter** & **Shape** & **Axis** \\ \hline MLP & 0.0035 & 0.0372 & 0.0531 \\ MeshNet & 0.7191 & 0.0006 & 0.9443 \\ GIN & 0.8038 & 0.3681 & 0.5929 \\ \hline \hline \end{tabular} \end{table} Table 4: The p-values of ExpC and other DNNs under two-sided t-test. \begin{table} \begin{tabular}{l c c c c c c} \hline \hline & \multicolumn{2}{c}{**Diameter**} & \multicolumn{2}{c}{**Shape**} & \multicolumn{2}{c}{**Axis**} \\ \cline{2-7} & MAE (MPa) & RMSE (MPa) & MAE (MPa) & RMSE (MPa) & MAE (MPa) & RMSE (MPa) \\ \hline Linear & \(3.961\pm 0.000\) & \(4.511\pm 0.000\) & \(2.266\pm 0.000\) & \(2.924\pm 0.000\) & \(2.693\pm 0.000\) & \(3.259\pm 0.000\) \\ Ridge & \(2.725\pm 0.000\) & \(3.290\pm 0.000\) & \(2.271\pm 0.000\) & \(2.950\pm 0.000\) & \(2.666\pm 0.000\) & \(3.223\pm 0.000\) \\ RF & \(1.084\pm 0.011\) & \(1.486\pm 0.012\) & \(1.140\pm 0.007\) & \(1.591\pm 0.013\) & \(2.434\pm 0.035\) & \(3.625\pm 0.039\) \\ XGB & \(\mathbf{0.810\pm 0.000}\) & \(\mathbf{1.084\pm 0.000}\) & \(\mathbf{1.025\pm 0.000}\) & \(1.601\pm 0.000\) & \(\mathbf{1.451\pm 0.000}\) & \(\mathbf{2.120\pm 0.000}\) \\ LGB & \(0.881\pm 0.000\) & \(1.207\pm 0.000\) & \(1.047\pm 0.000\) & \(\mathbf{1.428\pm 0.000}\) & \(1.762\pm 0.000\) & \(2.534\pm 0.000\) \\ \hline MLP & \(0.771\pm 0.023\) & \(1.032\pm 0.024\) & \(0.935\pm 0.029\) & \(\mathbf{1.316\pm 0.056}\) & \(0.814\pm 0.079\) & \(1.197\pm 0.101\) \\ MeshNet & \(0.719\pm 0.054\) & \(0.958\pm 0.048\) & \(1.027\pm 0.046\) & \(1.546\pm 0.053\) & \(0.731\pm 0.092\) & \(1.105\pm 0.122\) \\ GIN & \(0.719\pm 0.083\) & \(0.951\pm 0.070\) & \(0.910\pm 0.051\) & \(1.368\pm 0.095\) & \(0.746\pm 0.065\) & \(1.204\pm 0.054\) \\ ExpC & \(\mathbf{0.709\pm 0.025}\) & \(\mathbf{0.944\pm 0.043}\) & \(\mathbf{0.883\pm 0.036}\) & \(1.388\pm 0.047\) & \(\mathbf{0.728\pm 0.031}\) & \(\mathbf{1.079\pm 0.036}\) \\ \hline \hline \end{tabular} \end{table} Table 3: Particle crushing prediction performance. runs of fixed random seeds and 3 ablation studies of different inputs. These detailed experiments can help us dive into the model generalization ability for predicting the particle crushing strength. Overall, the generalization difficulty of both tasks and methods is examined that DNNs can overcome the difficulty of the Axis task by the non-linearity modeling, and the large prediction variances of GNNs cause its statistical in-significance among different GNNs. _The Axis task is the most difficult task for non-Deep methods, and the Shape task is the most difficult task for DNNs._ Existing researches Huang et al. (2014); Huillca et al. (2021); Fu et al. (2017); Hu et al. (2022); Zhu and Zhao (2021); Sun et al. (2021) investigate the effects of the particle crushing strength based on either of the three tasks while neglecting the difficulty comparison between different tasks. Tab. 3 presents that non-Deep methods and DNNs both achieve the least Mean Absolute Error (MAE) and Root Mean Square Error (RMSE) on the Diameter task. On the one hand, the size effect of particle crushing strength has been sufficiently investigated with morphology descriptors. On the other hand, the larger size of particles leads to the degeneration of the strength due to the increasing internal flaws Huang et al. (2014); Wang et al. (2021), as shown in Tab. 2. However, although the maximum strength of the testing set of the Axis task is nearly half of that of the Shape task as shown in Tab. 2, non-Deep methods present significantly larger MAE in the Axis task. In contrast, MLP reduces the MAE by 43.9% on the Axis task compared to XGBoost, the best non-Deep method, based solely on the morphology descriptors, indicating the effective non-linearity modeling of DNNs. ExpC further outperforms MLP by 10.5% with \(p=0.0531\) at the two-sided independent t-test, verifying the usefulness of the fragment graph modeling. The four methods of DNNs obtain higher MAE on the Shape task than that on the Axis task, which is consistent with the testing set distribution as shown in Tab. 2. It indicates that DNNs can better use input morphology descriptors and the fragment graph than non-Deep methods. _MLP outperforms non-Deep methods statistically more significantly._ Since XGBoost and LightGBM are not affected by different random seeds, MLP achieves statistical significance than them on all three tasks and reduces the MAE by 4.8% on the Diameter task, 8.8% on the Shape task, and 43.9% on the Axis task. Furthermore, MLP shares the same morphology descriptors with non-Deep methods, indicating that the particle crushing theory with respect to different conditions requires relational modeling of different aspects, including the geometric, form, roundness, and sphericity descriptors. _ExpC outperforms MLP statistically more significant, but doesn't show statistical significance of other GNNs._ Tab. 4 presents that ExpC achieves statistical significance of MLP with the help of the fragment graph and the powerful framework of GNNs. However, although ExpC performs best among GNNs, the p-values of MAE of ExpC and that of other GNNs don't show statistical significance, which is caused by the large variances of other GNNs with different random seeds. It implies a future direction to control the prediction variances of GNNs for predicting the particle crushing strength. ### Ablation Study The above analysis reveals the superiority of deep learning methods and GNNs, advancing the predictions of particle crushing strength by a large margin. The ablation study aims to investigate the effects of particle morphology descriptors (PMD) and node and edge features (NEF) for GNNs. We further Figure 2: MAE distribution of ablation studies among all parameter settings, including GNNs w/o particle morphology descriptors (PMD), GNNs w/o node and edge features (NEF), and GNNs with both PMD and NEF (Baseline). compute the largest eight distances of a particle fragment to other fragments as the features of node distance and extract the overall largest eight distances as the particle features to complement the PMD and NEF. In this way, _w/o PMD_ means removing the PMD or the PMD and the particle distances at the same time, and _w/o NEF_ means removing the NEF from GNNs, leaving the features of node distance for GNNs. In summary, PMD has dominated the prediction accuracy of GNNs due to the expert experience Blott and Pye (2008); Bagheri et al. (2015); Huang et al. (2020); Domokos et al. (2015); Pouranian et al. (2020); Zhao and Wang (2016); Yang et al. (2017); Zheng et al. (2021); Zhang et al. (2016), and NEF can further substantially reduce the prediction errors of GNNs consistently on various GNN architectures and the prediction tasks. Since GNNs exhibit larger variances under different random seeds as shown in Tab. 3, we visualize the variance ranges of GNNs under different parameter settings in Fig. 2 to evaluate the global effects of the PMD and NEF on the hyper-parameter sensitivity of different GNNs on different tasks. Firstly, Fig. 2 shows the significance of PMD that the prediction errors across three tasks increase rapidly with GNNs _w/o PMD_, and the superiority of ExpC that ExpC mostly achieves the best medium performance of the boxplot against two other \begin{table} \begin{tabular}{c c|c c|c c|c c} \hline \hline Method & Ablation Study & Diameter & Deg. (\%) & Shape & Deg. (\%) & Axis & Deg. (\%) \\ \hline \multirow{3}{*}{MeshNet} & w/o PMD & \(0.800\pm 0.044\) & -11.3 & \(1.506\pm 0.021\) & -46.6 & \(1.429\pm 0.081\) & -95.5 \\ & w/o NEF & \(0.733\pm 0.073\) & -1.9 & \(1.038\pm 0.108\) & -1.1 & \(0.815\pm 0.053\) & -11.5 \\ & Baseline & \(0.719\pm 0.054\) & - & \(1.027\pm 0.046\) & - & \(0.731\pm 0.092\) & - \\ \hline \multirow{3}{*}{GIN} & w/o PMD & \(1.425\pm 0.162\) & -98.2 & \(1.664\pm 0.122\) & -82.9 & \(2.551\pm 0.286\) & -242.0 \\ & w/o NEF & \(0.789\pm 0.028\) & -9.7 & \(1.030\pm 0.058\) & -13.2 & \(0.768\pm 0.043\) & -2.9 \\ & Baseline & \(0.719\pm 0.083\) & - & \(0.910\pm 0.051\) & - & \(0.746\pm 0.065\) & - \\ \hline \multirow{3}{*}{ExpC} & w/o PMD & \(0.759\pm 0.072\) & -7.1 & \(0.982\pm 0.039\) & -11.2 & \(1.477\pm 0.228\) & -102.9 \\ & w/o NEF & \(0.734\pm 0.033\) & -3.5 & \(0.981\pm 0.070\) & -11.1 & \(0.815\pm 0.045\) & -12.0 \\ \cline{1-1} & Baseline & \(0.709\pm 0.025\) & - & \(0.883\pm 0.036\) & - & \(0.728\pm 0.031\) & - \\ \hline \hline \end{tabular} \end{table} Table 5: The best performance comparison of ablation studies among all parameter settings, including GNNs w/o particle morphology descriptors (PMD), GNNs w/o node and edge features (NEF), and GNNs with both PMD and NEF (Baseline). The degradation percentages compared to the Baseline are listed here. methods due to its powerful expressivity Yang et al. (2020). Secondly, PMD reduces the variances of different parameter settings much more than NEF. Thirdly, GNNs equipped with NEF obtain lower MAE than GNNs _w/o NEF_ as shown in the MAE distribution, especially on the Shape and Axis tasks of ExpC. It implies that we should identify the task difficulty first and then choose the appropriate GNN architecture. The best MAE comparison of ablation studies in Tab. 5 obtains consistent results with Fig. 2 that both PMD and NEF reduce the prediction errors of GNNs across the three tasks, and PMD has a much more significant impact than NEF on the three tasks, which are quantitatively verified by the degradation percentages. In contrast to the similar performance of GNNs _w/o NEF_ and Baseline in Fig. 2, Tab. 5 provides a more detailed observation that Baseline can improve GNNs _w/o NEF_ by up to 13.2% and 12.0% on the Shape and the Axis task, indicating the effectiveness of NEF. Moreover, the best-performing ExpC benefits from NEF consistently across the three tasks. Overall, the ablation studies verified the instability of GNNs without the dedicated PMD and the effectiveness of NEF when applied to GNNs. ### Attribution Analysis The ablation studies reveal the significance and sensitivity of particle morphology descriptors (PMD) and node and edge features (NEF) with respect to different tasks and GNNs. The attribution analysis aims to understand the detailed mechanisms of PMD and NEF for particle crushing strength prediction with the common patterns and individual patterns of the feature attributions Figure 3: Gradient attribution of the first 34 particle morphology descriptors. on the three tasks. We adopt the simple yet effective gradient-based method to quantify the impacts of inputs for the predictions, which has been employed from CNNs Song et al. (2019); Feng et al. (2022) to GNNs Jing et al. (2021). We choose the ExpC with its best-performing hyper-parameters as shown in Tab. 3 and fix its random seed as 0 to obtain the trained model. Let \(\hat{\mathbf{y}}\) be the prediction strength of a particle and \(\mathbf{x}\) be the input PMD and NEF, and we average the magnitudes of gradient attributions for a specific particle type, written as \(\frac{1}{|\mathbf{X}_{type}|}\sum_{\mathbf{x}\in\mathbf{X}_{type}}|\frac{ \partial\hat{\mathbf{y}}}{\partial\mathbf{x}}|\), where \(\mathbf{X}_{type}\) is a particle type with the specific diameter, shape, and axis. The attribution distributions of PMD and NEF are visualized in Fig. 3 and Fig. 4, where the X-axis represents the true particle strength from 5.09 MPa to 38.29 MPa, including the training set, the validation set and the testing set to eliminate the differences of the testing sets of the three tasks and discover the common and individual patterns of the attribution distributions. We remove the 35-th PMD of the stability descriptor since its small attributions degrade the visualization effects, which is provided in Fig. C.9. The first 34 PMD are divided into four groups as shown in Fig. 3, _e.g._ Geometric, Form, Roundness, and Sphericity. The highlighted horizontal bars shown in Fig. 3 summarize the common patterns of the three tasks that only partial features of different groups provide impressive attributions. On the one hand, it is caused by the similarity and redundancy of different descriptors. On the other hand, the simulation particles exhibit the standard spheroidicity with specified shape factors rather than realistic particles with various shapes Wang et al. (2021); Ma et al. (2022), which limits the effectiveness of morphology descriptors. Besides the common patterns, the sparse vertical bars occur more frequently on Figure 4: Gradient attribution of node and edge features. the Shape and the Axis task than on the Diameter task, which is consistent with the task difficulty as shown in Tab. 3 that a difficult task requires more complex relationships between different descriptors. The horizontal and vertical bars can point out the effectiveness and the cooperative relationships of PMD on the three tasks. NEF contain the local descriptors of particle fragments and their interactive faces. As depicted in Fig. 4, the attribution distributions of NEF exhibit significantly smaller values than those of PMD. This difference can be attributed to the hierarchical aggregation mechanism of ExpC, which aggregates the small attributions to large attributions, and the higher significance of PMD in the hybrid framework, as shown in Tab. 5. Although the node features provide more attributions than the edge features, the node features exhibit larger attributions from the Diameter task to the Shape and Axis task, while the edge features exhibit the contrary trend. It implies that the interactions of fragments can well model the particle crushing behaviors with the _state-of-the-art_ GNNs on the more difficult tasks. It will be a promising direction to explore the interactions of fragments during particle crushing in future work. ## 5 Discussion Existing researches have developed various statistical theories like Weibull statistics \(P_{s}(V_{0})=\exp\left[-\left(\frac{\sigma}{\sigma_{0}}\right)^{m}\right]\) and machine learning methods to characterize the size effects Sun et al. (2021); Hu et al. (2022) and morphology effects Wang et al. (2021); Ma et al. (2022) of particle crushing. However, since particle crushing occurs in various civil engineering fields Xiao et al. (2020), GNNs with the fragment graph, as constitutive modeling, can largely alleviate the efforts to predict the particle crushing strength more accurately and attribute the prediction contributions more efficiently. We summarize the limitations and future works as follows. _More realistic simulations._ We generate the particle crushing dataset following Hu et al. (2022), which varies the diameter, shape, and axis as shown in Tab. 1. Nonetheless, the dataset mainly consists of particles with the standard spheroidicity, which deviate largely from the realistic particle shapes Sun et al. (2021); Wang et al. (2021); Ma et al. (2022). Besides, the uniaxial compression is employed to simplify the loading condition in the particle crushing process, while the triaxial test Hu et al. (2022) and different loading conditions can be explored in the future. _More powerful GNNs for particle crushing._ We test the generalization ability of these _state-of-the-art_ GNNs by reducing the learning difficulty of GNNs based on the dedicated PMD features Wang et al. (2021), which leaves space for improvements. For example, the interactions of fragments during loading can be modeled by GNNs to explore the detailed behaviors of particle crushing in different time steps. Besides, it is necessary to consider the external loading conditions when introducing more realistic simulations. _Quantitative attributions of features._ We explain the feature attributions based on the quantitative gradient-based methods Song et al. (2019); Jing et al. (2021); Feng et al. (2022). However, the common and individual patterns of different tasks are qualitatively summarized to highlight the contributions of different features. It requires cooperation with civil engineering researchers to iteratively identify the significant descriptors and predict the particle crushing strength with GNNs. ## 6 Conclusion In this paper, we are motivated by the lack of a large-scale dataset on particle crushing and the successful applications of GNNs to propose a method to predict particle crushing strength based on fragment connectivity. Experimental results demonstrate the effectiveness of a hybrid framework that combines MLP and GNNs, and surprisingly show the comparable performance of three different GNNs, namely MeshNet Feng et al. (2019), GIN Xu et al. (2019), and ExpC Yang et al. (2020). The significantly improved performance motivates further exploration of particle crushing under different conditions, such as variations in particle diameters, shapes, and compression axes. Our analysis reveals the importance and sensitivity of particle morphology descriptors and features of GNNs in generalizing to different tasks. Nonetheless, in everyday use of granular materials, various compression conditions require more comprehensive modeling of particle crushing. In the future, we aim to explore the use of Graph Neural Networks (GNNs) with improved connectivity to predict particle crushing based on a more comprehensive modeling approach. ## Appendix A Particle Crushing Dataset Figure 14 describes the load-displacement curve of a randomly sampled particle, where the peak force decreases drastically due to the particle breakage during the external load. We strictly follow the instructions of Hu _et al._Hu et al. (2022) to perform a batch of simulations of 45,000 particles, adopting the Non-Smooth Contact Dynamics (NSCD) method for the numerical simulations of particle crushing. The parameters of the Cohesive Zone Model (CZM) of the NSCD method are also calibrated by Hu _et al._Hu et al. (2022). After generating the comprehensive dataset, we filter particles without at least 35% decrease Wang et al. (2021); Huillca et al. (2021); Hu et al. (2022) from the peak force since these particles aren't considered to break into pieces, and compute the characteristic particle crushing strength \(\sigma_{0}\) of 900 particle types, where the particle types without more than 30 valid simulations McDowell and Amon (2000); Hu et al. (2022) of particle crushing are further removed to ensure the data sufficiency for the fitted Weibull distribution. Finally, we have obtained 40,818 valid data points and 882 particle types of particle crushing. ### Compression Test of Single Particle _Particle meshing._ The software Neper Quey et al. (2011) provides the Voronoi tessellation of a sphericity particle, whose diameter, three-dimensional scale coefficients, and rotation angles are given as the input parameters of Neper. The different diameters, shapes, and compression axes of our dataset are firstly introduced in the particle meshing process. The Voronoi tessellation divides the specified polyhedral particle into multiple convex cells, simulating the fragment distribution of the particle and the common faces of different fragments. A Voronoi cell can be defined as follows Cantor et al. (2017) \[V_{i}=\{x\in\mathbf{X}\,|\,d(x,P_{i})<d(x,P_{j})\,\forall j\neq i\},\] (A.1) where \(\mathbf{X}\) is the three-dimensional point set of the particle space, \(P_{i}\) and \(P_{j}\) are the given points of the \(i\)-th and \(j\)-th cell. The final output of Voronoi tessellation is optimized by iteratively replacing the given points \(P_{i},P_{j}\) with their new centroids \(c_{i},c_{j}\) until convergence Cantor et al. (2017). Gmsh Geuzaine and Remacle (2009) further produces a meshing of the particle based on the **geo** file generated by Neper. We have also obtained the **tess** file generated by Neper for the convenience of modelling the fragments and their contacts in a fragment graph. _Numerical simulation._ We perform numerical simulations of the NSCD method by LMGC90 Dubois and Mozul (2013) after generating the mesh files Figure A.5: The load-displacement curve in a particle compression test. \begin{table} \begin{tabular}{c c c c c c c} \hline \hline \(K_{I}\)(N/mm\({}^{3}\)) & \(K_{II}\)N/mm\({}^{3}\) & \(\sigma_{I}^{\epsilon}\)MPa & \(\sigma_{II}^{\epsilon}\)MPa & \(G_{I}\)mJ/mm\({}^{2}\) & \(G_{II}\)mJ/mm\({}^{2}\) & \(\mu\) & \(\rho\)kg/m\({}^{3}\) \\ \hline 80 & 120 & 9 & 11.5 & 900 & 1125 & 0.3 & 2650 \\ \hline \hline \end{tabular} \end{table} Table A.6: Parameters for the cohesive zone model. of 45,000 particles. The meshing particle with a specified rotation axis is assumed to be compressed along the new Z-axis by two parallel platens. The NSCD method Jean (1999); Jean and Moreau (1992); Moreau (1988) updates the displacement of each element at each time step by detecting the contacts and computing the contact forces between bodies, following the Signorini-Coulomb condition for a unilateral contact. The unilateral Signorini condition describes the non-penetrability between two objects, written as follows \[\begin{cases}v_{n}>0&\Rightarrow f_{n}=0,\\ v_{n}=0&\Rightarrow f_{n}>=0,\end{cases}\] (A.2) where \(v_{n}\) is the relative velocity between particles in the normal direction, and \(f_{n}\) is the contact force in the normal direction. The contact force \(f_{t}\) in the tangential direction obeys the Coulomb friction law, written as \[\begin{cases}v_{t}>0&\Rightarrow f_{t}=-\mu f_{n},\\ v_{t}=0&\Rightarrow-\mu f_{n}\leq f_{t}\leq\mu f_{n},\\ v_{t}<0&\Rightarrow f_{t}=\mu f_{n},\end{cases}\] (A.3) where \(\mu\) is the contact friction coefficient between particles and is set as 0.3 in our simulations. The CZM model Camacho and Ortiz (1996); Hu et al. (2022) quantifies the relationship between breakage energy and the maximum displacement of the breakage of the contact faces, whose parameters are determined based on the work of Hu et al. (2022). ### Weibull Distribution For Particle Crushing McDowell et al. (2000) have found that the particle crushing strength of geometrically similar particles follows a Weibull distribution, written as \[P_{s}=\exp\left[-\left(\frac{d_{s}}{d_{0}}\right)^{3}\left(\frac{\sigma}{ \sigma_{0}}\right)^{m}\right],\] (A.4) where \(P_{s}\) is the breakage ratios under the corresponding load, \(d_{0}\) and \(\sigma_{0}\) are the characteristic diameter and crushing strength, respectively. The survival probability of a batch of 50 particles with the same geometry is drawn in Fig. A.6, sorting by the normalized particle strength, where \(m=9.690\) is the Weibull modulus and indicates the variability of the particle crushing distribution. The characteristic particle strength is thus scaled to 1.0 of the horizontal axis, and corresponds to the 37% survival probability of the vertical axis. Existing particle crushing theories McDowell and Amon (2000); Sun et al. (2021); Wang et al. (2021) derive a close-form formula to describe the size effects of particles with different diameters. However, firstly, their various theories have been proposed from different perspectives and lacked the consensus of the particle crushing behaviors. Secondly, our experimental results of the non-Deep methods and DNNs in Tab. 3 reveal that particle morphology descriptors play a vital role on the generalization of predicting the particle crushing strength, while existing theories are mostly based on the particle diameter. Thirdly, generalizing the predictions for more conditions like the particle shapes and compression axes require a constitutive model to describe the particle from different viewpoints. Therefore, we are motivated to model the fragment connection of the particle with Graph Neural Networks (GNNs), which offer a natural modelling for the fragment graph. Figure A.6: 50 particle crushing data points and the fitting Weibull distribution of crushing strength. The particle type and the highlighted data point are both the same with Fig. A.5. ### Dataset Statistics In the particle generation stage, we have chosen 900 particle types, which is the Cartesian product of 20 particle diameters, 15 scale shapes in the (X, Y, Z) axes, and 3 compression axes, as shown in Tab. 1. We have conducted 50 numerical simulations with random Voronoi tessellation for each particle type to ensure the data sufficiency to measure the characteristic crushing strength. Firstly, we reserve the particles that can be observed at least 35% decrease Wang et al. (2021); Huillca et al. (2021); Hu et al. (2022) from the peak force to ensure the particle breakage. Secondly, we remove particle types that contain less than 30 valid simulations McDowell and Amon (2000); Hu et al. (2022) from our dataset to ensure the data quality. As stated before, we have obtained 882 particle types and 40,818 particles finally. Tab. A.7 describes that 882 particle types present smooth variations in terms \begin{table} \begin{tabular}{l c c c c c} \hline \hline & min & 25\% & 50\% & 75\% & max \\ \hline \(\sigma_{0}\) (MPa) & 5.09 & 8.65 & 11.03 & 15.06 & 38.29 \\ \(m\) & 0.69 & 3.88 & 5.54 & 6.86 & 11.60 \\ \hline \hline \end{tabular} \end{table} Table 7: The distribution of the characteristic strength (\(\sigma_{0}\)) and Weibull modulus \(m\) of the dataset. Figure 7: The characteristic particle crushing strength with respect to different diameters, shapes and compression axes. of the characteristic strength \(\sigma_{0}\) and the Weibull modulus \(m\), which is consistent with observations from Sun et al. (2021); Hu et al. (2022). Moreover, the outliers of the particle types are centered around the maximum values, where the maximum values are around two times larger than the 75% percentile of \(\sigma_{0}\) and \(m\). It poses significant challenges to the machine learning methods. Fig. A.7 visualizes the distribution of \(\sigma_{0}\) in terms of three different conditions, including the diameter, shape and compression axis. Firstly, the compression axis increases \(\sigma_{0}\) more significantly than the other two conditions, which may be attributed to that the scale coefficient of the X-axis is larger than the Y-axis and Z-axis as shown in Tab. 1. Secondly, the outliers of the 882 particle types are centered in the corner of the 3D plot, which presents small diameter, flat shape and the X-axis. We believe that the comprehensive dataset can sufficiently reveal the diversity of particle crushing behaviors and benchmark the machine learning methods for particle crushing. ### Particle Features We have calculated thirty-five Particle Morphology Descriptors (PMD) according to the work of Wang et al. (2021), as shown in Fig. A.8. The feature distributions can be roughly categorized into three kinds: the uniform distribution (_e.g._, Shortest Length), the long-tail distribution (_e.g._, Volume), and the Gaussian distribution (_e.g._, Diameter of the maximum inscribed sphere). It is noteworthy that the distributions of the flatness (Form 11) and the sphericity (Sphericity 8) are significantly different from the Gaussian distribution of that Wang et al. (2021), which is caused between the differences of simulated particles and natural particles. The diverse feature distributions also verify that it is rather difficult to predict particle crushing strength only based on the diameter feature. We have also developed eleven node features to describe each fragment of the particle and nine edge features for the connectivity between fragments, as shown in Tab. A.8. These features also present similar distributions to the PMD since they share similar definitions with PMD. The particular advantage of node features and edge features is that they can describe the microscopic behaviors of fragments beyond the overall behaviors of the particle. ## Appendix B Graph Neural Networks for Particle Crushing ### Graph Neural Networks Graph Neural Networks (GNNs) have shown its powerful prediction abilities on the non-grid data and been applied to various fields such as Recommendation Ying et al. (2018), traffic flow prediction Yu et al. (2018), and molecular classification Gilmer et al. (2017); Xu et al. (2019); Yang et al. (2020); Ying et al. (2021). A graph is defined by a node set \(V=\{v_{1},\cdots,v_{n}\}\) and an associated edge set \(E=\{e_{1},\cdots,e_{m}\}\), where \(e_{1}\) connects a pair of adjacent fragments \(v_{i}\) and \(v_{j}\). The message-passing paradigm Gilmer et al. (2017) describes GNNs in a microscopic view that each node \(v_{i}\) receives the messages from its neighbors \(v_{j}\in\mathcal{N}(v_{i})\) and updates its representation based on these messages, written as: \[\begin{split}\mathbf{m}_{i}^{k}&=\sum_{v_{j}\in \mathcal{N}(v_{i})}\mathbf{M}_{k}(\mathbf{h}_{i}^{k},\mathbf{h}_{j}^{k}, \mathbf{e}_{ij}),\\ \mathbf{h}_{i}^{k+1}&=\mathbf{U}_{k}(h_{i}^{k}, \mathbf{m}_{i}^{k}),\end{split} \tag{10}\] where \(v_{i}\) updates from \(\mathbf{h}_{i}^{k}\) of the \(k\)-th layer to \(\mathbf{h}_{i}^{k+1}\) of \(k+1\)-th layer based on the message function \(\mathbf{M}_{k}\) and the update function \(\mathbf{U}_{k}\). The obtained node representation \(\mathbf{h}_{i}\) can be used for various tasks such as node classification Kipf \begin{table} \begin{tabular}{l l} \hline \hline Features & Details \\ \hline Node Features & Volume(1), Surface Area(1), Diameter(1), Number of Faces(1), \\ & Number of Neighbors(1), Centroid Coordinates(3), Euler Angles(3) \\ \hline Edge Features & Contact Area(1), Number of Lines(1), Maximum Length of the \\ & Contact Area(1), Centroid Coordinates(3), Euler Angles(3) \\ \hline \hline \end{tabular} \end{table} Table 8: Feature components of node features and edge features, where (3) means three variables. and Welling (2017) and link prediction Ying et al. (2018). It requires a readout function to generate a representation vector for the whole graph \(G\) for graph-level tasks like molecular classification Gilmer et al. (2017); Xu et al. (2019); Yang et al. (2020); Ying et al. (2021), written as \[\mathbf{h}_{G}=\mathbf{R}(\{\mathbf{h}_{i}^{K}|v_{i}\in V\}),\] (B.2) where \(K\) is the number of neural network layers. We have adopted MeshNet Feng et al. (2019), GIN Xu et al. (2019), and ExpC Yang et al. (2020) as our baseline GNNs for particle crushing. We have also tried the powerful Graphormer Ying et al. (2021), which has achieved the first place together with ExpC Yang et al. (2020) in the PCQM4M-LSC track of KDD Cup 2021 5, but failed the memory requirements on our GPU of 24GB Titan X. These three GNNs can be summarized as follows: Footnote 5: [https://ogb.stanford.edu/kddcup2021/results/#awardees_pcqm4m](https://ogb.stanford.edu/kddcup2021/results/#awardees_pcqm4m) * MeshNet Feng et al. (2019) is called a Convolutional Neural Network for meshing files, by aggregating neighborhood information based on its spatial descriptor and structural descriptor and pooling the overall representation. The working mechanism of MeshNet Feng et al. (2019) exactly meets the definition of the message-passing paradigm Gilmer et al. (2017) and implements the readout function with a global average pooling layer. Therefore, MeshNet is considered as a variant of GNNs in this paper. * GIN Xu et al. (2019) is proposed as a more powerful GNNs to discriminate the isomorphism graph better by building an injective mapping from neighborhood message to node representations, innovatively leading a new direction of enhancing the discriminative power of GNNs. * ExpC Yang et al. (2020) improves the expressive power of GNNs beyond 1-WL test based on the innovative ExpandingConv and CombConv. Ying _et al._Ying et al. (2021) have achieved the first place in the PCQM4M LSC track of KDD Cup 2021 by combing Graphormer Ying et al. (2021) and ExpC Yang et al. (2020). ### Predicting Particle Crushing Strength The crushing behavior of a particle is closely related with the particle shape and the internal structure, as shown in previous theoretical studies McDowell and Bolton (1998); Daouadji et al. (2001); Russell and Khalili (2004); Tengattini et al. (2016). Numerical simulations of various particles have become the mostly adopted method to study the relations between the particle and its crushing strength since experimental tests are costly and unscalable Cheng et al. (2004); de Bono and McDowell (2014); Fu et al. (2017). In a numerical simulation, a particle is divided into multiple rigid polyhedral cells randomly Nguyen et al. (2015) and gets fractured during the compression test Hu et al. (2022). The crushing strength of the particle reveals its internal characteristic, benefiting for various engineering fields including geotechnical engineering, mining, chemical engineering, and so on Zhu and Zhao (2019). From the perspective of machine learning, the tessellated particle can be seen as a connected graph, where each polyhedral cell plays as a node. Formally, the cell set is denoted by \(V=\{v_{1},\cdots,v_{i},\cdots,v_{n}\}\), where \(v_{i}\) refers to a polyhedral cell and \(n\) denotes the number of cells. A node \(v_{i}\) is usually associated with a node vector \(\mathbf{v}_{i}\) to describe the node states, as listed in Tab. A.8. The edges of the _internal graph_ are formed according to the spatial proximity of each cell pair. The edge set of the internal graph is denoted by \(E=\{e_{1},\cdots,e_{m}\}\), where \(e_{1}\) connects two in-contact (adjacent) cells \(v_{i}\) and \(v_{j}\). An edge \(e_{k}\) could also carry the relational vector \(\mathbf{e}_{k}\) of the two cells, such as the contact surface areas and the angle of the contact Vlassis et al. (2020). Our task is predicting the particle crushing strength on particles of unseen types with the help of GNNs Feng et al. (2019); Xu et al. (2019); Yang et al. (2020), given the internal graph \(G=\{V,E\}\) and its associated vectors \(\mathbf{x}=\{\{\mathbf{v}_{i}|\forall v_{i}\in V\},\{\mathbf{e}_{k}|\forall e _{k}\ inE\}\}\). The problem can be formulated as \[\operatorname*{arg\,min}_{\mathbf{g}}\sum_{\mathbf{x}\in\mathbf{X},\mathbf{y}\in \mathbf{Y}}\|\mathbf{y}-\mathbf{g}(\mathbf{x},G)\|_{2}+\lambda\Omega(\mathbf{g}), \tag{10}\] where \(\mathbf{g}\) is one kind of GNNs and \(\Omega\) is the regularization term. ## Appendix C Experiment Settings We have obtained three testing sets by splitting the dataset according to the diameters, scale shapes, and compression axes to examine the generalization ability of different methods across three tasks. The testing sets are split around 1/3 as shown in Tab. 1, where 7/20 for the diameter task, 5/15 for the shape task, and 1/3 for the axis task. ### Hyper-parameters We have conducted experiments with five non-Deep methods, including Linear Regression, Ridge Regression, Random Forest, LightGBM Ke et al. (2017), \begin{table} \begin{tabular}{c l l} \hline \hline Method & Parameter & Settings \\ \hline Linear & Default & Default \\ \hline Ridge & alpha & [1e-3, 1e-2, 1e-1, 1.0] \\ \hline Random Forest & n\_estimators & [10; 25; 50; 75; 100] \\ & min\_samples\_split & [2; 8; 32] \\ & criterion & [squared\_error, absolute\_error, poisson] \\ \hline LightGBM & n\_estimators & [10; 25; 50; 75; 100] \\ & max\_depth & [4; 16; 64] \\ & reg\_alpha & [0.0, 1e-3, 1e-2, 1e-1, 1.0] \\ & reg\_lambda & [0.0, 1e-3, 1e-2, 1e-1, 1.0] \\ \hline XGBoost & n\_estimators & [10; 25; 50; 75; 100] \\ & max\_depth & [4; 16; 64] \\ & reg\_alpha & [0.0, 1e-3, 1e-2, 1e-1, 1.0] \\ & reg\_lambda & [0.0, 1e-3, 1e-2, 1e-1, 1.0] \\ \hline \hline \end{tabular} \end{table} Table 9: Grid search of parameters of machine learning methods. and XGBoost Chen and Guestrin (2016), and four DNNs, including MLP, MeshNet Feng et al. (2019), GIN Xu et al. (2019), and ExpC Yang et al. (2020). For a fair comparison, we have tried our best to grid search the hyper-parameters for non-Deep methods, as shown in Tab. C.9. The experimental results of non-Deep methods verify the effectiveness of them based on the dedicated particle morphology descriptors. Since the computation cost of DNNs is much larger than that of non-Deep methods, we firstly determine a group of parameters according to our experience as shown in Tab. C.10. Particularly, the number of ExpC layers is set to 2 to avoid the Out-Of-Memory error on our GPU. Then, we iteratively replace the default parameter with one parameter shown in Tab. C.11. We have conducted five runs for each kind of parameter combination. In summary, we have conducted at least 15 runs for Linear Regression, 60 runs for Ridge Regression, 675 runs for Random Forest, 5625 runs for LightGBM, and 5625 runs for XGBoost across three tasks. We have further performed three kinds of ablation studies for DNNs, resulting in 675 runs for MLP, 675 runs for MeshNet, 855 runs for GIN, and 540 runs for ExpC. These experiments can largely reduce the variances of different methods and ensure a fair comparison. \begin{table} \begin{tabular}{c l l l} \hline \hline Method & Default Parameters & & & \\ \hline MLP & batch\_size=128, & learning\_rate=1e-3, & hidden=128, & layers=2, \\ & dropout=1e-1 & & & \\ \hline MeshNet & batch\_size=128, & learning\_rate=1e-3, & hidden=128, & layers=2, \\ & dropout=1e-1 & & & \\ \hline GIN & batch\_size=128, & learning\_rate=1e-3, & hidden=128, & layers=2, \\ & dropout=1e-1, eps=1e-5, JK=max & & & \\ \hline ExpC & batch\_size=128, & learning\_rate=1e-3, & hidden=128, & layers=2, \\ & dropout=1e-1, head\_size=32 & & & \\ \hline \hline \end{tabular} \end{table} Table C.10: Default parameters of deep learning methods. \begin{table} \begin{tabular}{c l l} \hline \hline Method & Parameter & Settings \\ \hline \multirow{4}{*}{MLP} & batch\_size & [8, 32, 128, 512] \\ & learning\_rate & [1e-5, 1e-4, 1e-3, 1e-2] \\ & hidden & [128, 256, 512] \\ & layers & [2, 3, 4, 5] \\ \hline \multirow{4}{*}{MeshNet} & batch\_size & [8, 32, 128, 512] \\ & learning\_rate & [1e-5, 1e-4, 1e-3, 1e-2] \\ & hidden & [128, 256, 512] \\ & layers & [2, 3, 4, 5] \\ \hline \multirow{4}{*}{GIN} & batch\_size & [8, 32, 128, 512] \\ & learning\_rate & [1e-5, 1e-4, 1e-3, 1e-2] \\ & hidden & [128, 256, 512] \\ & layers & [2, 3, 4, 5] \\ \cline{1-1} & JK & [last, cat, max, lstm] \\ \hline \multirow{4}{*}{ExpC} & batch\_size & [8, 32, 128, 512] \\ & learning\_rate & [1e-5, 1e-4, 1e-3, 1e-2] \\ \cline{1-1} & hidden & [128, 256, 512] \\ \cline{1-1} & layers & [2] \\ \hline \hline \end{tabular} \end{table} Table 11: Iterative search of parameters of deep learning methods. ### More results of Attribution Analysis As shown in Fig. 9, the 35-th PMD of the stability descriptor presents the smallest attributions with respect to different particle crushing strength, resulting in low contrast of different descriptors. It can be observed from Fig. 9 that the light and dark colors differ from each other significantly across the X-axis, which can be used for feature importance directly to remove less useful descriptors. However, it poses challenges to compare the attribution analysis across the X-axis and three tasks. Figure A.8: The distribution of 35 Particle Morphology Descriptors (PMD) Wang et al. (2021), including 9 geometric characteristics Wang et al. (2021), 13 form descritors Blott and Pye (2008); Bagheri et al. (2015); Huang et al. (2020); Domokos et al. (2015), 3 roundness descritors Pouranian et al. (2020); Huang et al. (2020); Zhao and Wang (2016), 9 sphericity descriptors Blott and Pye (2008); Pouranian et al. (2020); Yang et al. (2017); Zheng et al. (2021); Huang et al. (2020); Zhang et al. (2016), and 1 instability descriptor Wang et al. (2021). Figure A.9: Gradient attribution of particle morphology descriptors.
2310.10171
On permutation symmetries in Bayesian neural network posteriors: a variational perspective
The elusive nature of gradient-based optimization in neural networks is tied to their loss landscape geometry, which is poorly understood. However recent work has brought solid evidence that there is essentially no loss barrier between the local solutions of gradient descent, once accounting for weight-permutations that leave the network's computation unchanged. This raises questions for approximate inference in Bayesian neural networks (BNNs), where we are interested in marginalizing over multiple points in the loss landscape. In this work, we first extend the formalism of marginalized loss barrier and solution interpolation to BNNs, before proposing a matching algorithm to search for linearly connected solutions. This is achieved by aligning the distributions of two independent approximate Bayesian solutions with respect to permutation matrices. We build on the results of Ainsworth et al. (2023), reframing the problem as a combinatorial optimization one, using an approximation to the sum of bilinear assignment problem. We then experiment on a variety of architectures and datasets, finding nearly zero marginalized loss barriers for linearly connected solutions.
Simone Rossi, Ankit Singh, Thomas Hannagan
2023-10-16T08:26:50Z
http://arxiv.org/abs/2310.10171v1
# On permutation symmetries in Bayesian neural network posteriors: a variational perspective ###### Abstract The elusive nature of gradient-based optimization in neural networks is tied to their loss landscape geometry, which is poorly understood. However recent work has brought solid evidence that there is essentially no loss barrier between the local solutions of gradient descent, once accounting for weight-permutations that leave the network's computation unchanged. This raises questions for approximate inference in Bayesian neural networks (BNNs), where we are interested in marginalizing over multiple points in the loss landscape. In this work, we first extend the formalism of marginalized loss barrier and solution interpolation to BNNs, before proposing a matching algorithm to search for linearly connected solutions. This is achieved by aligning the distributions of two independent approximate Bayesian solutions with respect to permutation matrices. We build on the results of Ainsworth et al. (2023), reframing the problem as a combinatorial optimization one, using an approximation to the sum of bilinear assignment problem. We then experiment on a variety of architectures and datasets, finding nearly zero marginalized loss barriers for linearly connected solutions. ## 1 Introduction Throughout the last decade, deep neural networks (dnn) have achieved significant success in a wide range of practical applications, becoming the fundamental ingredient for e.g., computer vision [e.g., 57, 25, 41, 64], language models [e.g., 24, 82, 17] and generative models [e.g., 54, 96, 97, 98, 102, 34]. Despite recent important advancements, understanding the loss landscape of dnn is still challenging. The characterization of its highly non-convex nature, its relation with architectural choices like depth and width and the connection with optimization and generalization are just some of the problems which have been the focus of extensive research in the last few years [e.g., 76, 26, 36, 32, 2, 30, 38, 79]. It is well known, for example, that one of the fundamental characteristics of deep neural networks is their ability to learn hierarchical features, and in this regards deeper networks seem to be exponentially more expressive than shallower models [e.g., 3, 5, 7, 8, 18, 109], leading the loss landscape to have many optima due to symmetries and over-parameterization [76, 26, 111, 94]. At the same time, the role of the depth of a model in relation with its width is far less understood [80], despite wide neural networks exhibiting important theoretical properties in their infinite limit behavior [e.g., 73, 23, 29, 53, 48, 37, 20]. Two notions that have been useful to shed light on the geometry of loss landscapes are that of _loss barriers_ and _mode connectivity_[36, 26]. The mode connectivity hypothesis states that given two points in the landscape, there exists a path connecting them such that the loss is constant or near constant (or, said differently, the loss barrier is null). We refer to _linear mode connectivity_ when the path connecting the two solutions is linear [32]. Recently, evidence has surfaced that stochastic gradient descent (sgd) solutions to the loss minimization problem can be linearly connected. Indeed, Entezari et al. [30] discuss the role of permutation symmetries from a loss connectivity viewpoint, conjecturing the possibility that mode connectivity is actually linear once accounting for all permutation invariances. Additionally, [2] gathers compelling empirical evidence across several network architectures and tasks, that under such a permutation symmetry the loss landscape often contains a single, nearly convex basin. In this work, we are taking a different perspective on this analysis. We are interested in the Bayesian treatment of neural networks, which results in a natural form of regularization and allows to reason about uncertainty in the predictions [101, 73, 66]. Bayesian inference for deep neural networks is notoriously challenging, as we wish to marginalize over multi-modal distributions with high dimensionality [47]. For this reason, there are various ways to approximate the posterior, involving techniques like variational inference [39, 14, 35, 62, 77], Markov chain Monte Carlo (mcmc) methods [75, 72, 27], possibly with stochastic gradients [19, 112, 33, 105, 70] and the Laplace approximation [68, 68, 84]. Indeed, fundamentally the Bayesian posterior and the loss landscapes are tightly interconnected: (i) solutions to the loss minimization problem are equivalent to maximum-a-posteriori (map) solutions, (ii) the loss landscape is equivalent to the un-normalized negative log-posterior. While in theory, given a dataset, the posterior is unique and the solution is global, many approximations will only explore local properties of the true posterior1. It's worth noting that a posterior over the parameters of the neural network induces a posterior on the functions generated by the model. Permutation symmetries play an important role in the geometry of the weight-space posterior, which are generally not reflected in function-space. While it is possible to carry out inference directly in function space, this poses a number of challenges [99, 71, 89, 61]. Fig. 1 illustrates this situation for a regression task on the Snelson dataset using a 3-layer dnn: on the left we compare two (approximate) solutions which have different weight-space posterior but similar function-space behavior. Notably, when we interpolate these two solutions (Fig. 1 on the right), we completely lose all capability of modeling the data. However, when we account for permutation symmetries in the posterior, we end up with solutions that once interpolated are still good approximations. This suggests that for any weight-space distribution, there exists a class of solutions which are functionally equivalent and linearly connected. This example motivates an informal generic statement: Footnote 1: By local properties, we mean that despite theoretical convergence guarantees of many methods like variational inference and mcmc, in practice the true posterior for deep neural networks is still highly elusive; see for instance the empirical convergence analysis of Hamiltonian Monte Carlo (hmc) in [47]. _Solutions of approximate Bayesian inference for neural networks are linearly connected after accounting for functionally equivalent permutations._ While being similar to the one in [30, 2], if this was to hold true for approximate Bayesian neural networks (bnns) it would represent an important step in further characterizing the properties of the Bayesian posterior and the effect of various approximations. We purposely leave the previous statement broadly open regarding the choice of the approximation method to allow for a more general discussion. More specifically, in this paper we will analyze and focus our discussion on the variational inference framework, making a more specific conjecture: **Conjecture 1**.: _Solutions of variational inference solutions for Bayesian inference for neural networks are linearly connected after accounting for functionally equivalent permutations._ Figure 1: **Permutation symmetries for regression on the Snelson dataset**[95]. _(Left)_ Two different solutions, with similar function-space behavior (showing \(\mu\pm 2\sigma\)). _(Right)_ Functions obtained when using two different strategies to interpolate between solutions. When we align the solutions, by taking into account the permutation symmetries, we retain the capability to model the data, indicating that there are solutions that once linearly interpolated exhibit no loss in performance. Note that, in weight space, the solution found with alignment is neither equal to solution 1 nor 2 (see the black curve which is a single function sample with fixed randomness). Contributions.With this work, we aim at studying the linear connectivity properties of approximate solutions to the Bayesian inference problem and we make several contributions. (i) We extend the formalism of loss barrier and solution interpolation to bnns. (ii) For the variational inference setting, propose a matching algorithm to search for linearly connected solutions by aligning the distributions of two independent solutions with respect to permutation matrices. Inspired by [2], we frame the problem as a combinatorial optimization problem using approximation to the linear sum assignment problem. (iii) We then experiment on a variety of architectures and datasets, finding nearly zero-loss barriers for linearly connected solutions. In Fig. 2 we present a sneak-peek and a visualization of our findings, where we show that after weight distribution alignment we can find a permutation map \(P\) of the solution \(q_{1}\) such that it can be linearly connected through high density regions to \(q_{0}\). ## 2 Preliminaries on Bayesian deep learning In this section, we review some basic notations on bnns and we review stochastic variational inference (svi), which is the main approximation method that we analyze in this paper. Let's consider a generic multilayer perceptron (mlp) with \(L\) layers, where the output of the \(l\)-th layer \(\mathbf{f}_{l}(\mathbf{\theta}_{l},\mathbf{x})\) is a vector-valued function of the previous layer output \(\mathbf{f}_{l-1}\) as follows, \[\mathbf{f}_{l}(\mathbf{\theta}_{l},\mathbf{x})=\mathbf{W}_{l}a(\mathbf{f}_{l-1}(\mathbf{\theta}_{l-1}, \mathbf{x}))+\mathbf{b}_{l} \tag{1}\] where \(a(\cdot)\) is a non-linearity, \(\mathbf{W}_{l}\) is a \(D_{l}\times D_{l-1}\) weight matrix and \(\mathbf{b}_{l}\) the corresponding bias vector. We shall refer to the parameters of the layer \(l\) as \(\mathbf{\theta}_{l}=\{\mathbf{b}_{l},\mathbf{W}_{l}\}\), and the union of all trainable parameters as \(\mathbf{\theta}=\{\mathbf{\theta}_{l}\}_{l=1}^{L}\). The objective of using Bayesian inference on deep neural networks [67; 65] involves inferring a posterior distribution over the parameters of the neural network given the available dataset \(\{\mathbf{X},\mathbf{Y}\}=\{(\mathbf{x}_{i},\mathbf{y}_{i})\}_{i=1}^{N}\). This requires choosing a likelihood and a prior [73; 74; 103]: \[p(\mathbf{\theta}\,|\,\mathbf{Y},\mathbf{X})=Z^{-1}p(\mathbf{Y}\,|\,\mathbf{\theta},\mathbf{X})p(\mathbf{ \theta}) \tag{2}\] where the normalization constant \(Z\) is the marginal likelihood \(p(\mathbf{Y}\,|\,\mathbf{X})\). As usually done, we assume that the likelihood factorizes over observations, i.e. \(p(\mathbf{Y}\,|\,\mathbf{\theta},\mathbf{X})=\prod_{i=1}^{N}p(\mathbf{y}_{i}\,|\,\mathbf{\theta}, \mathbf{x}_{i})\). Bayesian deep learning is intractable due to the non-conjugacy likelihood-prior and thus we don't have access to closed form solutions. Variational inference (vi) is a common technique to handle intractable Bayesian neural networks [12; 43; 39; 50]. Let \(\mathcal{P}(\mathbb{R}^{d})\) be the space of probability measures on \(\mathbb{R}^{d}\); vi reframes the inference problem into an optimization one, commonly by introducing a parameterized distribution \(q(\mathbf{\theta})\in\mathcal{P}(\mathbb{R}^{d})\) which is optimized to minimize the Kullback-Leibler (kl) divergence with respect to the true posterior \(p(\mathbf{\theta}\,|\,\mathbf{Y},\mathbf{X})\). In practice, this involves the maximization of the evidence lower bound (elbo) defined as \[\mathcal{L}_{\textsc{elbo}}(q)\stackrel{{\mathrm{def}}}{{=}} \int\log p(\mathbf{Y}\,|\,\mathbf{\theta},\mathbf{X})\mathrm{d}q(\mathbf{\theta})-\textsc{kl} \left[q(\mathbf{\theta})\parallel p(\mathbf{\theta})\right] \tag{3}\] whose gradients can be unbiasedly estimated with mini-batches of data [43] and the reparameterization trick [54; 55]. Despite its simple formulation, the optimization of the elbo hides several challenges, like the initialization of the variational parameters [87], the effects of over-parameterization on the quality of the approximation [88; 44; 58]. Here we are interested in how different solutions to Eq. (3) relate to each other in terms of loss barrier, which we will define formally in the following section. ## 3 Loss barriers In the context of Bayesian inference, we are interested in the loss computed by marginalization of the model parameters with respect to (an approximation of) the posterior. As such, we use the predictive Figure 2: **Permutations in multi-modal posterior. Log-posterior for MLP/CIFAR10, showing the two solutions (\(q_{0}\) and \(q_{1}\)) for which we can find a permutation map such that \(P_{\#}q_{1}\) can be linearly connected to \(q_{0}\) with low barrier (brighter regions).** likelihood, a proper scoring method for probabilistic models [83], defined as \[\log p(\mathbf{y}^{\star}\,|\,\mathbf{x}^{\star})=\log\int p(\mathbf{y}^{\star}\,|\,\mathbf{ \theta},\mathbf{x}^{\star})p(\mathbf{\theta}\,|\,\mathbf{Y},\mathbf{X})\mathrm{d}\mathbf{\theta} \approx\log\int p(\mathbf{y}^{\star}\,|\,\mathbf{\theta},\mathbf{x}^{\star})\mathrm{d}q( \mathbf{\theta}) \tag{4}\] where \(q(\mathbf{\theta})\) is an approximation of the true posterior (parametric or otherwise), \(\{\mathbf{x}^{\star},\mathbf{y}^{\star}\}\) are respectively the input and its corresponding label a data point under evaluation. To keep the notation uncluttered for the remaining of the paper, we write the predictive likelihood computed for a set of points \(\{\mathbf{x}^{\star}_{i},\mathbf{y}^{\star}_{i}\}_{i=1}^{N}\) as a functional \(\mathcal{L}:\mathcal{P}(\mathbb{R}^{d})\to\mathbb{R}\), defined as \[\mathcal{L}(q)\stackrel{{\mathrm{def}}}{{=}}\sum_{i=1}^{N}\log \int p(\mathbf{y}^{\star}_{i}\,|\,\mathbf{\theta},\mathbf{x}^{\star}_{i})\mathrm{d}q(\mathbf{ \theta}) \tag{5}\] Let's assume two models trained with vi with two different initializations, random seeds, and batch ordering. Variational inference in the classic inverse sense \(\textsc{kl}\,[q\parallel p]\) is mode seeking, thus we expect the two runs to converge to different solutions, say \(q_{0}\) and \(q_{1}\). To test the loss barrier as we interpolate between the two solutions we need to decide on the interpolation rule. We decide to interpolate the solutions following the Wasserstein geodesics between \(q_{0}\) and \(q_{1}\). First, let's start with a few definitions. Let \(q\in\mathcal{P}(\mathbb{R}^{d})\) be a probability measure on \(\mathbb{R}^{d}\) and \(T:\mathbb{R}^{d}\to\mathbb{R}^{d}\) a measurable map; we denote \(T_{\#}q\) the _push-forward measure_ of \(q\) through \(T\). Now we can introduce the _Wasserstein geodesics_, as follows. **Definition 1**.: _The Wasserstein geodesics between \(q_{0}\) and \(q_{1}\) is defined as the path_ \[q_{\tau}=\left((1-\tau)\mathrm{Id}+\tau T_{q_{0}}^{q_{1}}\right)_{\#}q_{0}, \qquad\tau\in[0,1] \tag{6}\] _where \(\mathrm{Id}\) is the identity map and \(T_{q_{0}}^{q_{1}}\) is the optimal transport map between \(q_{0}\) and \(q_{1}\), which for Brenier's theorem [16], is unique._ While we could interpolate using a mixture of the two solutions, we argue that this choice is trivial and does not fully give us a picture of the underlying loss landscape. Indeed, Eq. (6) is fundamentally different from a naive mixture path \(\tilde{q}_{\tau}=(1-\tau)q_{0}+\tau q_{1}\). In case of Gaussian distributions, when \(q_{0}=\mathcal{N}(\mathbf{m}_{0},\mathbf{S}_{0})\) and \(q_{1}=\mathcal{N}(\mathbf{m}_{1},\mathbf{S}_{1})\), \(q_{\tau}\) is Gaussian as well [100] with mean and covariance computed as follows: \[\mathbf{m}_{\tau} =(1-\tau)\mathbf{m}_{1}+\tau\mathbf{m}_{2}\] \[\mathbf{S}_{\tau} =\mathbf{S}_{1}^{-1/2}\left((1-\tau)\mathbf{S}_{1}+\tau\left(\mathbf{S}_{1}^ {1/2}\mathbf{S}_{2}\mathbf{S}_{1}^{1/2}\right)^{1/2}\right)^{2}\mathbf{S}_{1}^{-1/2} \tag{7}\] which simplifies even further when the covariances are diagonal. Now, we can define convexity along Wasserstein geodesics [4] as follows. **Definition 2**.: _Let \(\mathcal{L}:\mathcal{P}(\mathbb{R}^{d})\to\mathbb{R}\), \(\mathcal{L}\) is \(\lambda\) geodesics convex with \(\lambda>0\) if for any \(q_{0},q_{1}\in\mathcal{P}(\mathbb{R}^{d})\) it holds that_ \[\mathcal{L}(q_{\tau})\leq(1-\tau)\mathcal{L}(q_{0})+\tau\mathcal{L}(q_{1})- \frac{\lambda\tau(1-\tau)}{2}\mathcal{W}_{2}^{2}(q_{0},q_{1}) \tag{8}\] _where \(\mathcal{W}_{2}^{2}(q_{0},q_{1})\) is the Wasserstein distance defined as [51, 52, 104]_ \[\mathcal{W}_{2}^{2}(q_{1},q_{0})=\inf_{\gamma\in\Pi(q_{1},q_{0})}\int\|\mathbf{ \theta}_{1}-\mathbf{\theta}_{0}\|_{2}^{2}\mathrm{d}\gamma(\mathbf{\theta}_{1},\mathbf{ \theta}_{0}) \tag{9}\] _with \(\Pi(\cdot,\cdot)\) being the space of measure with \(q_{0}\) and \(q_{1}\) as marginals._ While mathematically proving the geodesics convexity of the predictive likelihood for arbitrary architectures and densities is currently beyond the scope of this work, we can empirically define a proxy using the _functional loss barrier_, defined as follows. **Definition 3**.: _The functional loss barrier along the Wasserstein geodesics from \(q_{0}\) and \(q_{1}\) is defined as the highest difference between the marginal loss computed when interpolating two solutions \(q_{0}\) and \(q_{1}\) and the linear interpolation of the loss at \(q_{0}\) and \(q_{1}\):_ \[\mathcal{B}(q_{0},q_{1})=\max_{\tau}\mathcal{L}(q_{\tau})-\left((1-\tau) \mathcal{L}(q_{0})+\tau\mathcal{L}(q_{1})\right) \tag{10}\] _where \(q_{\tau}\) follows the definition in Eq. (6)._ This definition is a more general than the ones in [2; 30; 32] but we can recover [30] by assuming delta posteriors \(q_{i}=\delta(\mathbf{\theta}-\mathbf{\theta}_{i})\) and we can further recover [2; 32] by also assuming \(\mathcal{L}(q_{0})=\mathcal{L}(q_{1})\). A comment on mixtures.In previous paragraphs, we argued that the mixture of distributions is not sufficient to capture the underlying complex geometry of the posterior. Now, we want to better illustrate this choice with a simple example. In Fig. 3 we plot the test likelihood with two interpolation strategies between two solutions (MLP on CIFAR10): the Wasserstein geodesics and the mixture. With mixtures, we see that the likelihood is pretty much constant during the interpolation, but this is very miss-leading: we don't see barriers not because they don't exist, but because the mixture simply re-weights the distributions, without continuously transporting mass in the parameter space. ## 4 Aligning distributions by looking for permutation symmetries In this section, we formalize the algorithm that aligns the solutions of Bayesian inference through permutation symmetries of weight matrices and biases. Let \(\mathbb{S}(d)\) be the set of valid \(d\times d\) permutation matrices. Given a generic distribution \(q(\mathbf{\theta})\), we can apply a permutation matrix \(\mathbf{P}\in\mathbb{S}(D_{l})\) to a hidden layer output at layer \(l\), and if we define \(\mathbf{\theta}^{\prime}\) to be equivalent to \(\mathbf{\theta}\) with the exception of \[\mathbf{W}^{\prime}_{l}=\mathbf{P}\mathbf{W}_{l},\quad\mathbf{b}^{\prime}_{l}=\mathbf{P}\mathbf{b}_{ l},\quad\mathbf{W}^{\prime}_{l+1}=\mathbf{W}_{l+1}\mathbf{P}^{\top}\,, \tag{11}\] then \(P_{\#}q\) is the equivalent push-forward distribution for \(\mathbf{\theta}^{\prime}\), where \(P\) is the associated permutation map. Let us define the distribution over the functional output of the model as \[q(\mathbf{f}(\mathbf{\theta},\cdot))=\int\delta\left(\mathbf{f}(\mathbf{\theta},\cdot)-\mathbf{f}( \widehat{\mathbf{\theta}},\cdot)\right)\mathrm{d}q(\widehat{\mathbf{\theta}})\,, \tag{12}\] and, equivalently, the distribution on the function using the permuted parameters as \[q(\mathbf{f}(\mathbf{\theta}^{\prime},\cdot))=\int\delta\left(\mathbf{f}(\mathbf{\theta}^{ \prime},\cdot)-\mathbf{f}(\widehat{\mathbf{\theta}}^{\prime},\cdot)\right)\mathrm{d}P _{\#}q(\widehat{\mathbf{\theta}}^{\prime})\,, \tag{13}\] where in both cases \(\delta(\cdot)\) is the Dirac function. Then, it is simple to verify that the two models are functionally equivalent for any inputs, \[q(\mathbf{f}(\mathbf{\theta},\cdot))=q(\mathbf{f}(\mathbf{\theta}^{\prime},\cdot))\,. \tag{14}\] This implies that for any weight-space distribution \(q\), there exists a class of functionally equivalent solutions \(P_{\#}q\), in the sense of Eq. (14). These same considerations can be easily extended to other layers, by considering multiple permutation matrices \(\mathbf{P}_{l}\). For our analysis, given two solutions \(q_{0}\) and \(q_{1}\) we are interested in finding the permuted distribution \(P_{\#}q_{1}\), functionally equivalent to \(q_{1}\), in such a way that once interpolating using Eq. (6) we observe similar performance to \(q_{0}\) and \(q_{1}\). Formally, we can write \[\operatorname*{arg\,min}_{P}\mathcal{D}(q_{1}(\mathbf{f}(\mathbf{\theta}^{\prime}, \cdot)),q_{0}(\mathbf{f}(\mathbf{\theta},\cdot)))=\operatorname*{arg\,min}_{P} \mathcal{D}(P_{\#}q_{1}(\mathbf{\theta}),q_{0}(\mathbf{\theta}))\,, \tag{15}\] where \(\mathcal{D}\) is a generic measure of discrepancy.2 Footnote 2: To be formally correct, the l.h.s. is a discrepancy defined on stochastic processes while the r.h.s. is defined on random vectors. Under mild assumptions on the distribution on the parameters and the architectures, \(\mathcal{D}\) is well defined in both cases [see e.g., 81]. ### Problem setup for permutation of vectors We start from a single vector of parameters, disregarding for the moment the functional equivalence constrain. We will extend these results to matrices and multiple layers later. In practice considering Figure 3: **Wasserstein geodesics and mixtures.** Test likelihood for mixture and the Wasserstein geodesics interpolation. Solutions are MLPs trained on CIFAR10. Gaussian distributions, we know that if \(q=\mathcal{N}(\mathbf{m},\mathbf{S})\), then \(P_{\#}q=\mathcal{N}(\mathbf{P}\mathbf{m},\mathbf{PS}\mathbf{P}^{\top})\) and if \(q=\mathcal{N}(\mathbf{m},\text{diag}(\mathbf{s}^{2}))\) then \(P_{\#}q=\mathcal{N}(\mathbf{P}\mathbf{m},\text{diag}(\mathbf{Ps}^{2}))\)[11]. With the kl divergence kl\([P_{\#}q_{1}\parallel q_{0}]\) it's easy to verify that it leads to just a distance between means, disregarding any covariance information. While certainly this represents a valid choice, we argue that we can find a better solution by using the Wasserstein distance. For Gaussian measures, the Wasserstein distance has analytic solution: \[\mathcal{W}_{2}^{2}(q_{1},q_{0}) =\left\lVert\mathbf{m}_{0}-\mathbf{m}_{1}\right\rVert_{2}^{2}+\mathrm{Tr }\bigg{(}\mathbf{S}_{1}+\mathbf{S}_{0}-2\left(\mathbf{S}_{1}^{1/2}\mathbf{S}_{0}\mathbf{S}_{1}^{1/ 2}\right)^{1/2}\bigg{)}=\] \[=\left\lVert\mathbf{m}_{0}-\mathbf{m}_{1}\right\rVert_{2}^{2}+\left\lVert \mathbf{S}_{0}-\mathbf{S}_{1}\right\rVert_{F}^{2}, \tag{16}\] where \(\left\lVert\cdot\right\rVert_{F}\) denotes the Frobenius norm, \(\left\lVert\mathbf{A}\right\rVert=\sum_{ij}{a_{ij}}^{2}\), and where the second line is valid only if the covariances commute (\(\mathbf{S}_{1}\mathbf{S}_{0}=\mathbf{S}_{0}\mathbf{S}_{1}\)). In our case, then, we can simplify as follows: \[\mathcal{W}_{2}^{2}(P_{\#}q_{1},q_{0})=\left\lVert\mathbf{m}_{0}-\mathbf{P}\mathbf{m}_{1} \right\rVert_{2}^{2}+\left\lVert\mathbf{s}_{0}-\mathbf{Ps}_{1}\right\rVert_{2}^{2}. \tag{17}\] To summarize, the problem now can be written as: \[\operatorname*{arg\,min}_{\mathbf{P}\in\mathbb{S}(d)}\left\lVert\mathbf{m}_{0}-\mathbf{ P}\mathbf{m}_{1}\right\rVert_{2}^{2}+\left\lVert\mathbf{s}_{0}-\mathbf{Ps}_{1}\right\rVert_{2}^{2}= \operatorname*{arg\,max}_{\mathbf{P}\in\mathbb{S}(d)}\left\langle\mathbf{P}\big{|}\bm {m}_{0}\mathbf{m}_{1}^{\top}+\mathbf{s}_{0}\mathbf{s}_{1}^{\top}\right\rangle_{F}\,, \tag{18}\] where the expression \(\left\langle\mathbf{A}|\mathbf{B}\right\rangle_{F}\) is the Frobenius inner product, \(\left\langle\mathbf{A}|\mathbf{B}\right\rangle_{F}=\sum_{ij}A_{ij}B_{ij}\). Note that the r.h.s. of Eq. (18) is a valid instantiation of the linear assignment problem (lap) [10], which can be solved in polynomial time. ### From vectors to neural network parameters Finally, we need to take into account that we have multiple layers and weight matrices, and that we are trying to find functionally equivalent solutions. For this, we decide to explicitly change our main objective by enforcing the functional equivalence constraint as follows: \[\operatorname*{arg\,min}_{\{P_{i}\}}\mathcal{W}_{2}^{2}\left(P_{1\#}q_{1}^{(1 )},q_{0}^{(1)}\right)+\mathcal{W}_{2}^{2}\left(\left(P_{2}\circ P_{1}^{\top} \right)_{\#}q_{1}^{(2)},q_{0}^{(2)}\right)+\cdots+\mathcal{W}_{2}^{2}\left( \left(P_{L-1}^{\top}\right)_{\#}q_{1}^{(L)},q_{0}^{(L)}\right)\,,\] where the notation \(\left(P_{l}\circ P_{l-1}^{\top}\right)\) represents the composition of the two permutation maps applied to rows and columns of the random weight matrices. More conveniently, this can be rewritten in terms of means and standard deviations. To leave the notation uncluttered, let's collect the means and the standard deviations for the layer \(l\) in \(\mathbf{M}^{(l)}\) and \(\mathbf{S}^{(l)}\), which are now both \(D_{l}\times D_{l-1}\) matrices, so that \(q^{(l)}=\prod_{ij}\mathcal{N}(M_{ij}^{(l)},S_{ij}^{(l)})\). Now we can write, \[\operatorname*{arg\,max}_{\{\mathbf{P}_{i}\}_{i=1}^{L}} \left\langle\mathbf{M}_{0}^{(1)}\Big{|}\mathbf{P}_{1}\mathbf{M}_{1}^{(1)} \right\rangle_{F}+\left\langle\mathbf{S}_{0}^{(1)}\Big{|}\mathbf{P}_{1}\mathbf{S}_{1}^{(1 )}\right\rangle_{F}+\left\langle\mathbf{M}_{0}^{(2)}\Big{|}\mathbf{P}_{2}\mathbf{M}_{1}^{(2 )}\mathbf{P}_{1}^{\top}\right\rangle_{F}+\left\langle\mathbf{S}_{0}^{(2)}\Big{|}\mathbf{P }_{2}\mathbf{S}_{1}^{(2)}\mathbf{P}_{1}^{\top}\right\rangle_{F}+\] \[+\cdots+\left\langle\mathbf{M}_{0}^{(L)}\Big{|}\mathbf{M}_{1}^{(L)}\mathbf{P }_{L-1}^{\top}\right\rangle_{F}+\left\langle\mathbf{S}_{0}^{(L)}\Big{|}\mathbf{S}_{1}^ {(L)}\mathbf{P}_{L-1}^{\top}\right\rangle_{F}\,.\] This optimization problem is more challenging than the one presented in Eq. (18): we are interested in finding permutation matrices to be applied concurrently to rows and columns of both means and standard deviations. This class of problems, also known as sum of bilinear assignment problems (solap), is NP-hard and no polynomial-time solutions exist. For this reason, we propose to use the setup in Ainsworth et al. [2] by extending it to our problem. In particular, by fixing all matrices with the exception of \(\mathbf{P}_{l}\), we observe that also in our case the problem can be reduced to a classic lap. \[\operatorname*{arg\,max}_{\mathbf{P}_{l}} \left\langle\mathbf{M}_{0}^{(l)}\Big{|}\mathbf{P}_{l}\mathbf{M}_{1}^{(l)}\mathbf{P }_{l-1}^{\top}\right\rangle_{F}+\left\langle\mathbf{M}_{0}^{(l+1)}\Big{|}\mathbf{P}_{(l +1)}\mathbf{M}_{1}^{(l+1)}\mathbf{P}_{l}^{\top}\right\rangle_{F}+\] \[\left\langle\mathbf{S}_{0}^{(l)}\Big{|}\mathbf{P}_{l}\mathbf{S}_{1}^{(l)}\mathbf{P }_{l-1}^{\top}\right\rangle_{F}+\left\langle\mathbf{S}_{0}^{(l+1)}\Big{|}\mathbf{P}_{(l +1)}\mathbf{S}_{1}^{(l+1)}\mathbf{P}_{l}^{\top}\right\rangle_{F}=\] \[=\operatorname*{arg\,max}_{\mathbf{P}_{l}} \left\langle\mathbf{P}_{l}\right|\mathbf{M}_{0}^{(l)}\mathbf{P}_{l-1}\left(\mathbf{M}_{1} ^{(l)}\right)^{\top}+\left(\mathbf{M}_{0}^{(l+1)}\right)^{\top}\mathbf{P}_{l+1}\mathbf{M}_ {1}^{(l+1)}+\] \[\mathbf{S}_{0}^{(l)}\mathbf{P}_{l-1}\left(\mathbf{S}_{1}^{(l)}\right)^{\top}+ \left(\mathbf{S}_{0}^{(l+1)}\right)^{\top}\mathbf{P}_{l+1}\mathbf{S}_{1}^{(l+1)}\right\rangle _{F}. \tag{19}\] As discussed in [2], going through each layer, and greedily selecting its best \(\mathbf{P}_{l}\), leads to a coordinate descent algorithm which guarantees to end in finite time. We present a pseudo-code in Algorithm 1. ## 5 Experiments Now, we present some supporting evidence to Conjecture 1. We start by training two replicas of bnns with variational inference (we refer to the Appendix for additional details on the experimental setup). We then compute the marginalized barrier as \(\mathcal{B}(q_{0},q_{1})=\max_{\tau}\mathcal{L}(q_{\tau})-((1-\tau)\mathcal{L}(q _{0})+\tau\mathcal{L}(q_{1}))\) where \(\mathcal{L}(\cdot)\) is the predictive likelihood and \(\tau\in[0,1]\), from which we take 25 evenly distributed points. In particular, we seek to understand what happens to the vi solutions first for the naive interpolation from \(q_{0}\) and \(q_{1}\), and then for the interpolation after aligning \(q_{0}\) and \(P_{\#}q_{1}\). We experiment with mlps with three layers and ResNet20 [41] with various widths on MNIST [60], Fashion-MNIST [108] and CIFAR10 [56]. All models are trained without data augmentation [106] and with filter response normalization (frn) layers instead of BatchNorm. Finally, we set the prior to be Gaussian \(\mathcal{N}(\mathbf{0},\alpha^{2}\boldsymbol{I})\), with the flexibility of choosing the variance. ### Low-barrier interpolations Fig. 4 shows the results with and without alignment. We see that regardless of the dataset and the model used, the performance degrades significantly when we move between the two solutions with the naive interpolation, showing the existence of barriers in the predictive likelihood for Gaussian vi solutions. However, with the alignment proposed in SS 4 and Algorithm 1, we recover zero barrier solutions for mlps on both MNIST and CIFAR10, and nearly-zero barrier for ResNet20 on CIFAR10. This holds both for the train and test splits, with quantifiably smaller barriers in the test set. In Fig. 5 we study the effect of the width of a neural network in relation to the loss barrier by taking an mlp and a ResNet20 with an increasing number of hidden features. We see that wider models generally provide lower barriers: for mlps this holds true with and without alignment, while for the ResNet20 this is happening only after alignment. This extends some previous analysis done on loss-optimized networks. Specifically, Enetzari et al. [30] show that barriers seem to have a double descent trend, while Ainsworth et al. [2] discuss that low barrier solutions after accounting for symmetries are easier to find in wider networks. Figure 4: **Zero barrier solutions. Comparison of loss barriers for standard vi (gray) and vi with alignment (orange). While loss barriers always appear between two solutions in the standard vi approach, in the case of vi with alignment there is no noticeable loss barrier for mlps and a nearly-zero loss barrier for ResNet20.** Figure 5: **Effect of width. After distribution alignment, wider models exhibit lower likelihood barrier.** We speculate that this might be due to the limiting behavior of Bayesian neural networks, which makes the posterior landscape Gaussian-like [48; 40]. While this does not fully explain the phenomenon observed, the existing connections between bnn and non-parametric models, like Gaussian Processes (gps) [83] and deep Gaussian processes (dgps) [22; 20; 93; 28], can provide additional insights on the role of symmetries in weight space [80]. Finally, as an additional check, we analyze the log-posterior with and without alignment by projecting the density into two dimensional slices, following the setup in [47; 36]. We study the two dimensional subspace of the parameter space supported by the hyperplane \(H=\{\mathbf{\theta}\in\mathbb{R}^{d}\,|\,\mathbf{\theta}=a\mathbf{\theta}_{a}+b\mathbf{\theta} _{b}+(1-a-b)\mathbf{\theta}_{c}\}\),, where \(a,b\in\mathbb{R}\) and \(\mathbf{\theta}_{a}\), \(\mathbf{\theta}_{b}\) and \(\mathbf{\theta}_{c}\) are the samples either from \(q_{0}\), \(q_{1}\) and \(q_{\tau}\) without alignment or from \(q_{0}\), \(P_{\#}q_{1}\) and \(P_{\#}q_{\tau}\) with alignment. With this configuration, all three samples always lie on this hyper-plane. In Fig. 6, we present the visualization of ResNet20 trained on CIFAR10. We see that the samples from \(q_{0}\) and \(P_{\#}q_{1}\) are connected by higher density regions than the ones between \(q_{0}\) and \(q_{1}\). This is in line with the results in Fig. 4, where we see that the loss barrier is lower after alignment. ### Analyzing the effect of the prior and testing the cold posterior effect In all previous experiments we used a Gaussian prior \(\mathcal{N}(\mathbf{0},\alpha^{2}\mathbf{I})\) with fixed \(\alpha^{2}\); now we study the effect of a varying prior variance \(\alpha^{2}\) on the behavior of the loss barriers. We experiment this on a mlp trained on MNIST and Fashion-MNIST and on a ResNet20 (width x8) on CIFAR10. We report the results in Fig. 7. We can appreciate two behaviors: with alignment, there is no measurable effect of using different variances in finding zero-barrier solutions; on the contrary, without alignment we see that naive vi solutions are easier to interpolate with lower barrier when the prior is more diffused. At the same time, we see that higher variances produce bigger gaps between train barriers and test barriers. We speculate that this is due to overfitting happening with more relaxed priors, which makes low-barrier (but low-likelihood) solutions easier to find. Additionally, several previous works have analyzed the effect of tempering the posterior in bnns[106; 112; 110; 47]. Specifically, we are interested in the distribution \(p_{T}(\mathbf{\theta}\,|\,\mathbf{Y})\propto(p(\mathbf{Y}\,|\,\mathbf{\theta},\mathbf{X})p(\mathbf{ \theta}))^{1/T}\), where \(T\) is known as the temperature. Note that starting from the above definition, we can write an equivalent elbo for vi which takes into account \(T\). For \(T<1\), we have cold posteriors, which are Figure 6: **Posterior density visualization.** Analysis of the log-posterior computed for ResNet20. Samples from \(q_{0}\) and \(q_{1}\) are connected by lower density regions, while \(q_{0}\) and \(P_{\#}q_{1}\) are not. Figure 7: **Effect of prior variance.** After distribution alignment, prior variance has low effect in finding zero-loss barriers, while with naive interpolation we see a decreasing trend the higher the variance is. sharper than the true Bayesian posteriors, while for \(T>1\) we have warm posterior, which are more diffused. In Fig. 8 we see that barriers for cold posteriors with alignment are marginally closer to zero than for warm posteriors. Note that cold temperatures concentrate the distribution around the map, which motivates a further comparison with a non-Bayesian approach. ### Comparison with SGD solutions Motivated by the results with cold posteriors, we also compare the behavior of barriers for vi versus map solutions obtained via sgd. Note that using the map solution we end up with the same setup of weight matching than in [2]. In Fig. 9 we report this comparison, which is carried out on ResNet20 for various width multipliers. For narrow models, we see that vi with alignment and map with weight matching both behave in a similar manner. Interestingly, as the model becomes wider, map solutions achieve marginally lower barriers than vi. We speculate that this might be due to the simple Gaussian parameterization for the approximate posterior, which doesn't completely capture the local geometry of the true posterior. ### Effect of normalization layers and data augmentation We conclude this section with a discussion on the effects of normalization layers and data augmentation on the loss barriers for Bayesian neural networks. Different normalization strategies can affect the overall geometry of the problem [30; 2]. As discussed in [49], interpolating with BatchNorm layers [45] is pathological due to _variance collapse_ of the feature representation in hidden layers. Additionally, batch-dependent normalization layers don't have a clear Bayesian interpretation, since the likelihood cannot factorize. For our experiments we choose to use the frn layer, as done in previous works [e.g., 47]. Note that frn layers are invariant to permutation units and therefore can be aligned without problems. To test the _variance collapse_ behavior, we analyze the variance of activations following the instructions in [49, SS3.1], with the sole difference that the activations are marginalized w.r.t. samples from the posterior. In Fig. 10 we can see that there isn't a pathological variance collapse after alignment. Finally, in Fig. 11 we compare another normalization layer, the LayerNorm (ln) [6]. Note that ln is also batch-independent, it has a clear Bayesian interpretation and it is invariant to permutation units. Indeed, we see that both normalization layers can be aligned, and ln exhibits lower barriers than frn. Finally, in all previous experiments we skipped data augmentation, because the random augmentations introduce stochasticity which lacks a proper Bayesian interpretation in the formulation of the likelihood function (e.g. re-weighting of the likelihood due to the increase of the effective sample size [77]). Additionally, data augmentation can contribute to spurious effects difficult to disentangle (e.g., cold posterior effect [106]). Nonetheless, during the development of the method we didn't make an Figure 8: **Effect of temperature.** After alignment, cold posteriors makes barriers marginally closer to zero Figure 9: **VI versus sgd. vi and sgd behave equivalently after permutation alignment in narrow models. For wider models, sgd solutions reach lower barriers than vi.** assumption on data augmentation and in Fig. 12 we experiment both with and without augmentation, showing that we are still able to recover similar low barrier solutions in both cases. Having said that, we advocate caution when using data augmentation in Bayesian neural networks, as it changes the shape of the posterior. ## 6 Related work In earlier sections of the paper, we already briefly discussed and reviewed relevant works on mode connectivity, symmetries in the loss landscape and connection with gradient-based optimization methods. Here we discuss some relevant works on the connection to Bayesian deep learning. The work of Garipov et al. [36] sparked several contributions on exploiting mode connectivity for ensembling models, which is akin to Bayesian model averaging. For example, in [46] the authors propose to ensemble models using curve subspaces to construct low-dimensional subspaces of parameter space. These curve subspaces are, among others, the non-linear paths connecting low-loss modes (and consequently high-posterior density) in weight space. In [31], the authors attempt to explain the effectiveness of deep ensembles [59], concluding that it is partially due to the diversity of the sgd solutions in parameter space induced by random initialization. More recently, in [9] the authors reason about mode connecting volumes, which are multi-dimensional manifolds of low loss that connect many independently trained models. These mode connecting volumes form the basis for an efficient method for building simplicial complexes for ensembling. Here, we want to highlight that these works have not taken into account the permutation symmetries. Finally, in a concurrent submission, [107] proposes an algorithm to remove symmetries in mcmc chains for tanh networks. ## 7 Conclusions By studying the effect of permutation symmetries, which are ubiquitous in neural networks, it is possible to analyze the fundamental geometric properties of loss landscapes like (linear) mode connectivity and loss barriers. While previously this was done on loss-optimized networks [2, 30, 32], in this work we have extended the analysis to Bayesian neural networks. We have studied the linear connectivity properties of approximate Bayesian solutions and we have proposed a matching algorithm (Algorithm 1) to search for linearly connected solutions, by aligning the distributions of two independent vi solutions with respect to permutation matrices. We have empirically validated our framework on a variety of experiments, showing that we can find zero barrier linearly-connected solutions for bnn trained with vi, on shallow models as well as on deep convolutional networks. This brings evidence for Conjecture 1 regarding the linear connectivity of approximate Bayesian solutions. Furthermore, we have studied the effect of various design hyper-parameters, like width, prior and temperature, and observed complex patterns of behavior, which would require additional research. In particular, the experiments raise questions regarding the relation between linear mode connectivity and the generalization of bnn, as well as the role of width with respect to limiting behaviors of non-parametric models like gps and dgp. ## Acknowledgments and Disclosure of Funding SR wants to thank David Bertrand and the AIAO team at Stellantis for their work on the software and hardware infrastructure used for this work.
2310.09434
Learning nonlinear integral operators via Recurrent Neural Networks and its application in solving Integro-Differential Equations
In this paper, we propose using LSTM-RNNs (Long Short-Term Memory-Recurrent Neural Networks) to learn and represent nonlinear integral operators that appear in nonlinear integro-differential equations (IDEs). The LSTM-RNN representation of the nonlinear integral operator allows us to turn a system of nonlinear integro-differential equations into a system of ordinary differential equations for which many efficient solvers are available. Furthermore, because the use of LSTM-RNN representation of the nonlinear integral operator in an IDE eliminates the need to perform a numerical integration in each numerical time evolution step, the overall temporal cost of the LSTM-RNN-based IDE solver can be reduced to $O(n_T)$ from $O(n_T^2)$ if a $n_T$-step trajectory is to be computed. We illustrate the efficiency and robustness of this LSTM-RNN-based numerical IDE solver with a model problem. Additionally, we highlight the generalizability of the learned integral operator by applying it to IDEs driven by different external forces. As a practical application, we show how this methodology can effectively solve the Dyson's equation for quantum many-body systems.
Hardeep Bassi, Yuanran Zhu, Senwei Liang, Jia Yin, Cian C. Reeves, Vojtech Vlcek, Chao Yang
2023-10-13T22:57:46Z
http://arxiv.org/abs/2310.09434v1
Learning nonlinear integral operators via Recurrent Neural Networks and its application in solving Integro-differential Equations ###### Abstract In this paper, we propose using LSTM-RNNs (Long Short-Term Memory-Recurrent Neural Networks) to learn and represent nonlinear integral operators that appear in nonlinear integro-differential equations (IDEs). The LSTM-RNN representation of the nonlinear integral operator allows us to turn a system of nonlinear integro-differential equations into a system of ordinary differential equations for which many efficient solvers are available. Furthermore, because the use of LSTM-RNN representation of the nonlinear integral operator in an IDE eliminates the need to perform a numerical integration in each numerical time evolution step, the overall temporal cost of the LSTM-RNN-based IDE solver can be reduced to \(O(n_{T})\) from \(O(n_{T}^{2})\) if a \(n_{T}\)-step trajectory is to be computed. We illustrate the efficiency and robustness of this LSTM-RNN-based numerical IDE solver with a model problem. Additionally, we highlight the generalizability of the learned integral operator by applying it to IDEs driven by different external forces. As a practical application, we show how this methodology can effectively solve the Dyson's equation for quantum many-body systems. ## 1 Introduction Integro-differential equations (IDEs) arise in many scientific applications ranging from nonequilibrium quantum dynamics [1, 2, 3, 4], the dynamics of non-Markovian colloidal particles [5, 6, 7, 8] the modeling of dispersive waves [9, 10] and electronic circuits [11]. One particularly important example is the application of the Kadanoff-Baym equation [1, 3, 12] for the time evolution of quantum correlators. This equation describes the propagation in time of non-equilibrium Green's functions, and finding efficient methods of solving this equation is of extreme importance in the study of driven quantum systems. A general type of IDEs can be written as: \[\frac{d}{dt}G(t)=F(G(t),t)+\int_{0}^{t}K(G(t-s),s)G(s)ds \tag{1}\] where both \(F\) and the integral kernel \(K\) are functions of and \(t\) and \(G(t)\). An IDE is computationally challenging to solve due to the presence of the integral term in (1). A numerical time evolution scheme typically requires performing a numerical integration of the integral term at each time step. If \(n_{T}\) time steps are taken to evolve the numerical solution of (1) to time \(T\), the overall computational complexity in time is proportional to at least \(n_{T}^{2}\), which can be high for a large \(n_{T}\). Several techniques have been recently developed to reduce the temporal complexity of solving (1). One technique is based on constructing and updating a compact representation of \(G(t)\) and \(K(G(t-s),s)\)[13]. Another technique uses snapshots of the solution to (1) within a small time window to construct a reduced order model that can be used to extrapolate the long-time dynamics of \(G(t)\)[14, 4]. In this paper, we present yet another approach to reducing the computational cost of solving (1). The basic idea of this approach is to turn an IDE such as (1) into an ordinary differential equation (ODE) of the form \[\frac{d}{dt}G(t)=F(G(t),t)+I(G(t),t), \tag{2}\] where \(I(G(t),t)\) is a functional of \(G(t)\) and \(t\) that can be evaluated with a constant cost, i.e., without performing numerical integration. A standard ODE scheme can then be applied to solve (2) with a temporal complexity of \(O(n_{T})\). In principle, the mapping from \(G(t)\) to \(I(G(t),t)\), which is implicitly defined by the integral \(\int_{0}^{t}K(G(t-s),s)G(s)ds\) always exists, although its (memoryless) analytical form is generally unknown. In this work, we seek to represent and learn such a mapping by training a recurrent neural network (RNN) using snapshots of the numerical solution of (1) within a small time window. Hence our approach falls into the category of operator learning methods, which encompasses recently developed machine-learning methodologies such as DeepONet[15] and the Fourier neural operator[16, 17]. In an operator learning method, we view the solution to a given ODE or partial differential equation (PDE) as the output of a neural network parameterized operator that maps between function spaces. For instance, solving an initial value problem for a given PDE can be reformulated as searching for a neural network parameterized operator, denoted as \(S:u(x,0)\to u(x,t)\). Carefully designed neural networks, such as those employed in DeepONet and the Fourier neural operator, can approximate this operator \(S\). By applying the learned operator \(S\) to the initial condition \(u(x,0)\) we can readily obtain the solution to the PDE. One notable advantage of the operator learning approach lies in the generalizability of the trained neural network model. Once the approximation to the operator is obtained, it can be applied to other initial conditions or inputs to the model. In this work, we adopt an operator-learning perspective and choose to use a long-short term memory (LSTM)-based RNN[18] to learn the mapping between \(G(t)\) and \(I(G(t),t)\). Instead of a simple feed-forward neural network (FFNN), we utilize RNNs because they can better preserve the causality of both \(G(t)\) and \(I(G(t),t)\). Furthermore, instead of learning the operator that yields the solution to the IDE (1) directly, we choose to learn the mapping between \(G(t)\) and \(I(G(t),t)\) for the following reasons. First of all, although the solution of (1) depends on both \(F(G(t),t)\) (referred to as the _streaming term_) and \(I(G(t),t)\) (referred to as the _memory integral_ or _collision integral_), the cost of evaluating the memory term typically far exceeds that of the streaming term. Secondly, when the streaming term \(F(G(t),t)\) is time-dependent and creates atypical dynamics outside of the training window (see e.g. Figure 6), it is difficult to directly learn a solution operator using short-time data. Consequently, the extrapolated prediction of the solution of (1) for large \(t\) can be poor. On the other hand, in many physically relevant scenarios, the integral kernel in (1) is well behaved. As a result, we expect the mapping between \(G(t)\) and \(I(G(t),t)\), which is independent of the solution \(G(t)\) itself, can be learned more easily. Furthermore, in addition to increasing the time window and training the RNN with different initial conditions, we can augment the training data by considering solutions of (1) with different streaming terms within a small time window. We will refer to this type of training as multi-trajectory training in section 3. This type of training is important for learning an operator that maps from one function space to another. Once the integral operator \(I(t)\) is well approximated by a properly trained RNN, the solution of the IDE can be obtained using any standard ODE solver with \(I(t)\) evaluated by the RNN. Furthermore, transferability of the learning algorithm is clearly achievable. Once the integral operator with a fixed integral kernel \(K\) is learned via an LSTM-based RNN, it can be used to solve the IDEs (1) associated with different streaming forces \(F(G(t),t)\) by using a standard ODE solver. The approach presented in this work is similar in spirit to other developments in using machine learning (ML) techniques and neural networks (NN) to solve forward and inverse problems defined by ODEs and PDEs. The most prominent example is the physics-informed neural network (PINN)[19, 20] and its generalizations. In the PINN approach, an NN serves as a solver that takes the spatial-temporal coordinate \(x,t\) as the input and outputs the approximate solutions to the differential equation. The whole network is trained using the loss function that is defined in terms of the underlying differential equation. More recent members within the PINN family include sparse physics-informed neural network (SPINN)[21] and parareal physics-informed neural network (PPINN)[22]. Another representative approach is the neural ordinary differential equation (NeuralODE)[23] and it is particularly useful for solving the inverse problem of differential equations. In this approach, an NN is used to approximate the derivatives of the state variables, i.e. the "right-hand side" of a differential equation. After the recovery of the derivatives, solutions to the differential equations can be obtained using a standard numerical solver for ODEs and PDEs. Recent developments in the NeuralODE family include NeuralSDE[24, 25], Neural Jump SDE[26], NeuralSPDE[27], Neural Operators[28], infinitely deep Bayesian neural networks[29], _etc_. What distinguishes the approach presented in this work from other existing neural-network-based differential equation solver is that we do not use the RNN to solve the IDEs directly. Instead, we use it to approximate the time dependent nonlinear integral operator that is costly to evaluate. We combine the RNN based operator learning with a standard ODE solver to obtain numerical solutions to the IDEs. This paper is organized as follows. In Section 2, we first introduce the basic architecture of RNN and the LSTM model, then we customize a specific RNN model designed to approximate the integral functional \(I(t)\) and introduce two training methods for the RNN model. In Section 3, we use a nonlinear, complex-valued IDE for \(2\times 2\) matrix \(G(t)\) as an example to demonstrate the effectiveness of using RNN to learn the integral operator and how this can be used to extrapolate the dynamics of the IDE. Importantly, we showcase the remarkable ability of using the same integral operator to solve IDEs driven by different streaming terms, thus affirming its generalizability. In Section 4, we will consider a specific physical application of the introduced methodology. Here, we underscore the practical utility of the RNN model in solving the Dyson's equation, offering further insights into its applicability. The primary findings and conclusions of this paper are succinctly summarized in Section 5. ## 2 Methods ### Recurrent Neural Network Recurrent neural networks (RNN) and their various adaptations have become prevalent tools to analyze and forecast the patterns in time series data[30, 31, 32] across a wide range of domains and scenarios[33, 34]. In this section, we will introduce the basic RNNs model, as well as the LSTM model. Basic RNN modelThe workflow of the RNN model is illustrated in Figure 1 (Top), which comprises several key components: including inputs, hidden states, and an RNN cell. The hidden states are calculated recursively within the RNN cell, utilizing sequential inputs. These hidden states play an important role in capturing temporal dependencies and facilitating the propagation of information over time within sequential data. Furthermore, these hidden states can be employed to model time-dependent quantities of interest, such as the memory integral \(I(G(t),t)\), which is the main focus of our paper. Specifically, consider a time series dataset \(\Xi=\{\xi_{0},\xi_{1},\xi_{2},\ldots,\xi_{N}\}\), where \(\xi_{i}\) represents the \(i^{th}\) time index within our time series. The RNN cell, represented as a function \(R(\cdot,\cdot;\theta)\), takes the preceding hidden state and the current time data as input and produces a new hidden state as output. Namely, \(h_{t}=R(\xi_{t},h_{t-1};\theta),t=1,\cdots,N\). Here, \(h_{0}\) is initialized as a zero vector and \(\theta\) represents the set of shared and trainable parameters. Mathematically, the hidden states can be written as a composition of the RNN cells given by: \[h_{n}=R(\xi_{n},h_{n-1};\theta)=R(\xi_{n},R(\xi_{n-1},h_{n-2};\theta);\theta)= R(R(...R(\xi_{2},R(\xi_{1},h_{0};\theta);\theta),...;\theta);\theta).\] The sharing of \(\theta\) enables the RNN to learn general patterns across time and incorporate a memory effect into the model. This capability also allows RNN models to handle input sequences of varying lengths. Long-short term memory (LSTM)The LSTM model is a type of RNN that distinguishes itself by employing different gates within its LSTM cell to regulate the flow of information, as shown in Figure 1 (Bottom). Compared with the standard RNN models, LSTM models exhibit better performance in capturing long-range dependencies and mitigating the vanishing gradient issue[18]. Their gated structure allows them to effectively preserve information across longer sequences. As a result, LSTM models have gained widespread applications in dynamics modeling tasks[35, 36]. In our specific context, we will employ an LSTM model to model the memory integral of the IDE. The LSTM cell features two distinct states: the cell state, denoted as \(C_{t}\), and the hidden state, represented as \(h_{t}\). The cell state serves as a repository for long-term memory, capable of retaining and propagating information throughout different time steps. On the other hand, the hidden state captures current information, serving as the foundation for predictions made at each time step. To regulate the flow of state information, three pivotal gates are employed: the input gate, the forget gate, and the output gate. The forget gate is responsible for determining which information from the previous cell state should be retained in the current cell state, while the input gate governs the incorporation of new information into the current cell state. Concurrently, the output gate controls the outward transmission of information from the cell state. Let \(i_{t}\), \(f_{t}\), and \(o_{t}\) represent the input, forget, and output gates at time \(t\). Each of these gates employs a nonlinear activation function, such as \(\sigma(x)=\frac{1}{1+e^{-x}}\), in conjunction with learnable parameters to govern the selection of information to be incorporated into the state updates. This can be expressed as follows: \[i_{t}=\sigma(\xi_{t},h_{t-1};\theta_{input}),\quad f_{t}=\sigma(\xi_{t},h_{t- 1};\theta_{forget}),\quad o_{t}=\sigma(\xi_{t},h_{t-1};\theta_{output}),\] Here, \(\theta_{input}\), \(\theta_{forget}\), and \(\theta_{output}\) are parameter sets within total collection of shareable parameters \(\theta\). Using these gates, the current cell state is updated according to: \[C_{t}=f_{t}\cdot C_{t-1}+i_{t}\cdot\hat{C}_{t},\] which combines both long-term memory (e.g., \(C_{t-1}\)) and new information (e.g., \(\xi_{t}\) used in the computation of \(\hat{C}_{t}=tanh(\xi_{t},h_{t-1};\theta_{c})\)). Here, \(\theta_{c}\in\theta\) is the parameter set. Finally, we compute the current hidden state \(h_{t}\) as: \[h_{t}=o_{t}\cdot\tanh(C_{t}).\] The hidden state \(h_{t}\) can subsequently undergo further trainable transformations, such as a linear transformation, to predict the specific quantity of interest. Figure 1: **(Top) The workflow of a basic RNN model.** The model processes the inputs \(\{\xi_{1},\xi_{2},\cdots,\xi_{n}\}\) one by one in sequence and produces a corresponding sequence of hidden states \(\{h_{1},h_{2},\cdots,h_{n}\}\). The same set of model parameters, \(\theta\), is employed in the RNN cell (i.e., \(R(\cdot,\cdot;\theta)\)) to calculate each \(h_{i}\), \(i=1,\cdots,n\). **(Bottom) An LSTM cell**. The update of the cell state \(C_{t}\) and the hidden state \(h_{t}\) relies on the current time input \(\xi_{t}\) and the preceding states, \(h_{t-1}\) and \(C_{t-1}\), through several information gates. ### RNN customized for learning time-dependent nonlinear integral operator Having introduced the basic architecture of RNN and the integro-differential equation we aim to solve, in this section, we customize a specific RNN model that enables us to efficiently learn the integral operator of an IDE within a short time window and use that to predict its long-time dynamics. As mentioned in the introduction, the RNN we seek should learn a map \(I:G(t)\to I(t)\) for any given function \(G(t)\). Since \(I(t)\) depends on all the history values of \(G(t)\), to capture this memory effect, we propose to use the LSTM cells as the basic modeling modules to build the RNN model. This leads to a _learning-predicting_ diagram as illustrated in Figure 2. Model architecture and dynamics extrapolationThe RNN in Figure 2 consists of an LSTM model and a linear transformation layer attached to it that maps the output of LSTM cells into the shape of the target time series. For our model, the NN takes the discretized \(G(t)\) in a time grid \(t=i\Delta t\) as the input and produces an approximated solution of the collision integral \(\hat{I}(t)\) for \(t=i\Delta t\) as the output. The RNN model is trained using a sufficiently accurate numerical solution to the IDE within a time window \(t\in[0,T]\). After the training is done, in the extrapolation phase, we can use an efficient and accurate forward propagation scheme to generate long-time trajectories. As an example, if we employ the forward Euler scheme to solve the differential equation, then for IDE (2), we have \[G(T+(i+1)\Delta t)=G(T+i\Delta t)+\Delta t[F(T+i\Delta t,G(T+i\Delta t))+\hat{I }(T+i\Delta t)],\qquad i\geq 0,\] where \(\hat{I}(T+i\Delta t)\) is the output of the RNN generated recursively by feeding in the input \(G(T+i\Delta t)\) as illustrated in Figure 3. The forward scheme for any multi-step method can be similarly derived. The specific model parameters, such as the hidden size of each layer, will be discussed in Section 3 per IDE considered. Data preparation and Loss functionsTo generate the training data, we solve the IDE numerically using an Adams-Bashforth third-order method (AB3) and Simpson's rule to approximate the collision integral \(I(t)\). This generates a time series data that is recorded in an interval of \([0,T]\), discretized by \(\Delta t\), eventually forming a dataset consisting of \(\{(G(i\Delta t),I(i\Delta t))_{i=0}^{T}\) pairs. For the complex-values IDEs that are considered in our applications, we will further split the real and imaginary parts of \(G(t)\) and \(I(t)\) when we generate the input sequence and compare \(\hat{I}(t)\) with \(I(t)\). This has to be done since most popular ML frameworks such as PyTorch[37] can only do real-valued arithmetics when training the NN. The parameters of the network, denoted by \(\theta\), are randomly initialized. The Adam optimizer[38], which is a first-order method that uses gradient-based optimization, is chosen to adjust the parameter Figure 2: Learning and predicting diagram of the RNN model. In the training phase, the input sequence \(\{G(0),G(\Delta t),G(2\Delta t),...,G(T)\}\) is fed into the model to generate predictions \(\{\hat{I}(0),\hat{I}(\Delta t),\hat{I}(2\Delta t),...,\hat{I}(T)\}\), using the parameters \(\theta\). From here, we can use the final output \(\hat{I}(T)\) to produce numerically extrapolated dynamics using the procedure outlined in _Model Architecture_ and illustrated in Figure 3. values to minimize the mean-squared error (MSE) function: \[f(I,\hat{I};\theta):=\frac{1}{N}\sum_{i=0}^{N}(I(i\Delta t)-\hat{I}(i\Delta t))^ {2}, \tag{3}\] where \(\hat{I}(i\Delta t)\) is the predicted collision integral generated by the RNN and \(I(i\Delta t)\) is the ground truth. The parameters are learned by propagating the gradients of each hidden state's inputs. Training methodAs we mentioned before, for all the numerical simulations considered in this paper, the RNN training is performed in a small time window (\(T\) relatively small), and the trained model is used for long-time (\(T_{f}\)) extrapolation in which \(T_{f}\gg T\), see Figure 3. We employ two training strategies to learn the integral operator \(I(t)\): 1. (_Single trajectory training_) For this case, the RNN is trained using a _single_ trajectory dataset \(\{(G(i\Delta t),I(i\Delta t))_{i=0}^{T}\). The numerical advantages of employing single trajectory training stem from its relatively low computational cost throughout the optimization process. Accordingly, since the single trajectory data corresponds to a _specific_ choice of the steaming term \(F(G(t),t)\), the optimized RNN normally yields bad _generalization_ result if we use the learned RNN to solve an IDE with different \(F(G(t),t)\) term. 2. (_Multi-trajectory training_) In contrast with the first case, the RNN can also be trained using batch training techniques, where the input of the neural network are _multiple_ trajectories generated by choosing different steaming terms \(F(G(t),t)\). The training cost is obviously higher but the obtained RNN model has greater generalizability and hence can be used to predict dynamics for IDE with new steaming terms. From the operator-learning point of view, the multi-trajectory training method is preferred since the enlarged dataset contains different input-output \(G(t)\) and \(I(t)\), which essentially provides more test functions for learning the mapping \(I:G(t)\to I(t)\). In accordance with these two training strategies, we also use two validation methods to detect and avoid overfitting. For the single trajectory training case, we can split the dataset \(\{(G(i\Delta t),I(i\Delta t))_{i=0}^{T}\) into two parts: \(\{(G(i\Delta t),I(i\Delta t))_{i=0}^{K}\}\) and \(\{(G(i\Delta t),I(i\Delta t))_{i=K+1}^{T}\), and then using the first time series measure training loss used for optimization of the RNN and the second part to measure the validation error. For the multiple trajectory training, the validation error is calculated using a new dataset \(\{(G(i\Delta t),I(i\Delta t))_{i=0}^{T}\) obtained by solving the IDE with streaming terms \(F(G(t),t)\) that are different from those ones in the training dataset. The minimized validation error normally indicates the generalizability of the obtained RNN model. For the first case, the generalizability is reflected in the predictability of long-time dynamics. For the second case, it is also reflected in the predictability of the dynamics for IDE with new steaming terms. Figure 3: Extrapolation of dynamics using the RNN model. The training phase will output predictions \(\{\hat{I}(i\Delta t)\}_{i=0}^{T}\). Using \(\hat{I}(T)\), we can use a forward numerical method to obtain the numerically extrapolated \(G(T+\Delta t)\). From here, we can recursively feed the numerically extrapolated \(G(T+\Delta t)\) into the model to obtain the prediction for \(\hat{I}(T+\Delta t)\). We repeat this until the final time, \(T_{f}\). Computational costAll computations are performed using the Perlmutter cluster. The login node has one AMD EPYC 7713 as the CPU and one 40GB NVIDIA A100 as the GPU. For Eqn (4), a typical training with input sequence length 2000 across 750 epochs for an RNN with 2 LSTM layers and hidden size 64 would take approximately 2 hours for the multi-trajectory training and 30 minutes for the single trajectory training. Under the same setting, for Eqn (5), it would take approximately 30 minutes for a multi-trajectory training and approximately 15 minutes for a single trajectory training. After the training, in the extrapolation phase, the computational time would be spent on the evaluation of the multi-step forward scheme and for RNN to generate new output \(I(T+i\Delta t)\). Detailed runtime statistics for the numerical examples considered in this paper will be tabulated in the Results section. Generally speaking, since the RNN is made of multi-fold function compositions, the generation of the output sequence is immediate. This ensures the total computational cost in the extrapolation phase scales as of \(O(T)\), in contrast with the \(O(T^{2})\) scaling for a normal IDE numerical solver. As a result, the entire computational cost is greatly reduced for long-time simulations. ## 3 Numerical results To demonstrate our method, we first consider a nonlinear complex-valued IDE given by: \[\frac{d}{dt}G(t)=A(t)G(t)+\int_{0}^{t}K(t-s)G(s)ds. \tag{4}\] Here we take: \[A(t)=-i\begin{bmatrix}-\beta e^{\frac{-(t-\alpha_{1})^{2}}{\sigma}}&1\\ 1&\beta e^{\frac{-(t-\alpha_{2})^{2}}{\sigma}}\end{bmatrix},\qquad G(0)= \begin{bmatrix}i&0\\ 0&i\end{bmatrix},\qquad K(t-s)=\cos(0.25(G(t-s)G(t-s))).\] Figure 4: Sample trajectories of \(G_{00}(t),I_{00}(t)\), selected from the database created by solving Eqn (4) with \(\alpha_{1},\alpha_{2}\in[1,20]\times[1,20]\), \(\sigma\in\{1,2,3,4,5\}\), and \(\beta=1\). Subsequently, we use the same database to do multi-trajectory training of the RNN model. For Eqn (4), we will employ both the single trajectory training and multi-trajectory training approaches to approximate the integral operator \(I(t):=\int_{0}^{t}K(t-s)G(s)ds\) and then combine the learned \(I(t)\) and AB3 as the ODE solver to obtain long-time trajectories. Before we present the training details, we note in advance that the RNN training results are benchmarked in three ways: 1. We compare the learned and extrapolated \(G(t)\) with a highly accurate numerical solution of IDE (4) and show the accuracy in the fitting region and RNN's predictability of the future dynamics. Due to the fact that the RNN is designed to learn the integral operator \(I(t)=\int_{0}^{t}K(G(t-s))G(s)ds\), we also expect this predictability to be generally valid for IDE (4) with different \(A(t)\) terms in the multi-trajectory case. 2. We further compare our learning strategy, i.e. learning the map \(I(t)=\int_{0}^{t}K(t-s)G(s)ds\), with two existing dynamics extrapolation methods. For the first one, we consider a direct learning strategy that uses an RNN with the same architecture while the output now changes to be the next timestep \(G((i+1)\Delta t)\) value. Accordingly, we modify the loss function (3) as: \[f(G,G_{RNN};\theta):=\frac{1}{N}\sum_{i=0}^{N}(G(i\Delta t)-G_{RNN}(i\Delta t ))^{2}.\] and other settings are the same. Secondly, we also compare our results with what was obtained using the dynamical mode decomposition (DMD) [4, 14, 39, 40, 41, 42] approach. With these comparisons, one can clearly see the better generalizability of our RNN model. 3. We calculate the runtime of our simulation and compare it with what was obtained using a standard integro-differential equation solver. This would demonstrate the numerical speedup we gain using the RNN to approximate the collision integral \(I(t)\). Figure 5: Single trajectory learning of IDE (4) where the RNN is trained on \(\alpha_{1}=10,\alpha_{2}=15\), \(\sigma=2\) and \(\beta=1\) and tested by extrapolating the dynamics up to \(T=120\) into the future. The shaded window represents the training regime. The black curve represents the true dynamics. The red curve represents the simulated dynamics using the learned \(\hat{I}(t)\) produced by the RNN. Training detailsFor single trajectory training, we fix the modeling parameters in Eqn (4) to be \(\alpha_{1}=10,\alpha_{2}=15,\sigma=2,\) and \(\beta=1\). The RNN is trained by feeding in \(\{G(i\Delta t)\}_{i=1}^{N}\) for \(\Delta t=0.01\) and \(N=2000\), and then we generate the extrapolated trajectory of \(G(t)\) up to \(T=120\) (10000 timesteps into the future). For multi-trajectory training, the batch dataset is generated by solving IDE (4) with different parameters \(\alpha_{1},\alpha_{2},\sigma,\beta\). Specifically, we prepare a dataset by choosing \(\alpha_{1},\alpha_{2}\) from the lattice grid \([1,20]\times[1,20]\), \(\sigma\in\{1,2,3,4,5\}\) and \(\beta=1\). This results in 2000 different trajectories. Plotted in Figure 4 is a reference of our input data \(G(t)\) and targets \(I(t)\). The displayed result is the first component of the 2 x 2 matrices \(G(t)\) and \(I(t)\). The dynamic difference between different matrix components is minimal. The RNN model contains 2 LSTM layers where the hidden size for each layer is 64. The input is an 8-dimensional vector that consists of the flattened \(2\times 2\) matrix \(G(t)\) decomposed into the real and imaginary parts. Similarly, the output is 8-dimensional, consisting of the real and imaginary parts of the \(2\times 2\) matrix collision integral \(I(t)\). The Adam optimizer has an initial learning rate set to be 0.01, with an adaptive cosine learning rate that decays accordingly with respect to total epochs used for training. This is designed to help us converge closer to the optimal solution as we progress in our optimization by taking smaller steps. The RNN is trained over 750 epochs and a batch size of 128 is chosen when we perform multi-trajectory training. Results discussionThe training and testing results are summarized in Figure 5-7. The single trajectory training result is displayed in Figure 5. We see that the RNN model is able to accurately predict the dynamics of the system using only \(\frac{1}{6}\) of the total trajectory for training. In particular, the modes and amplitudes of the oscillations match well with the ground truth dynamics. The multi-trajectory training results are shown in Figures 6. The batch training data are obtained by varying the parameters of Eqn (5) to be \(\alpha_{1},\alpha_{2}\in[1,20]\times[1,20],\sigma\in\{1,2,3,4,5\},\) and \(\beta=1\) Figure 6: Multi-trajectory learning of IDE (4) where the RNN is trained on \(\alpha_{1},\alpha_{2}\in[1,20]\times[1,20]\), \(\sigma\in\{1,2,3,4,5\}\), \(\beta=1\) and tested on \(\alpha_{1}=45,\alpha_{2}=45\), \(\sigma=5\) and \(\beta=1\) (**First column**) and \(\alpha_{1}=45,\alpha_{2}=35\), \(\sigma=2\) and \(\beta=14\) (**Second column**). The shaded window represents the training regime. The black curve represents the true dynamics. The red curve represents the simulated dynamics using the learned \(\hat{I}(t)\) produced by the RNN model. In the first column of Figure 6, the learned integral operator \(I(t)\) is used to solve IDE (4) for a new set of parameters: \(\alpha_{1}=45,\alpha_{2}=45,\sigma=5\), and \(\beta=1\), which is _outside_ of the parameter range of the training dataset. We see that our RNN model is still able to accurately predict the dynamics of this test trajectory, despite the highly oscillatory regime of the test trajectory appearing much later, which is never seen in the dataset. This result is further highlighted in the second column of Figure 6 where the test trajectory corresponds to \(\alpha_{1}=45,\alpha_{2}=35,\sigma=5\), and \(\beta=14\), and a large chirp oscillation is created after the training regime. The RNN predicting result still matches well with the true dynamics. These two test examples clearly demonstrate the generalizability of the RNN model as an integral operator. The result of integral operator learning is further compared with what was obtained using the direct learning approach and the DMD method. The testing results are summarized in Figure 7. As we introduced before, the direct learning approach used the same RNN architecture and training dataset to learn the solution map \(G(i\Delta t)\to G((i+1)\Delta t)\). The DMD method can only do time extrapolation for a single trajectory therefore the training data is just the \(G(t)\), \(t\in[0,20]\) for fixed parameter values \(\alpha_{1}=45,\alpha_{2}=45\), \(\sigma=5\) and \(\beta=1\). We can see clearly from Figure 7 that the integral operator learning strategy significantly outperforms other approaches. Lastly, we comment on the computational cost reduction brought by the RNN integral operator learning. In Table 1, we record the wall-clock runtimes used to generate different lengths of \(G(t)\) in the extrapolating regime for our approach and a regular IDE solver. As we mentioned in _Data preparation and Loss functions_, the AB3+RNN is used to generate the extrapolated trajectory. For comparison, we employ an IDE numerical solver which consists of an Euler scheme for time integration, and Simpson's Rule for approximating the collision integral \(I(t)\) (FE+SR). We see from Table 1 that the computational cost of querying the RNN and running AB3 is significantly lower than Figure 7: Multi-trajectory learning of IDE (4) where the RNN is trained on \(\alpha_{1},\alpha_{2}\in[1,20]\times[1,20]\), \(\sigma\in\{1,2,3,4,5\}\), \(\beta=1\) and tested on \(\alpha_{1}=45,\alpha_{2}=45\), \(\sigma=5\) and \(\beta=1\). The shaded window represents the training regime. The black curve represents the true dynamics. The red curve represents the simulated dynamics using the learned \(I(t)\) produced by the RNN model. The green curve in the top row represents the simulated dynamics using the RNN model that directly predicts \(G(t)\). The green curve in the bottom row represents the DMD extrapolation result. running FE+SR. Moreover, the overall scaling limit of our approach is of the order \(O(T)\), in contrast with the \(O(T^{2})\) using FE+SR. We also note that for both the RNN and the FE + SR methods in Table 1 use \(\Delta t=0.01\). ## 4 Application in quantum dynamics simulation In this section, we apply the RNN model to numerically solve and extrapolate the dynamics of Dyson's equation, which is a special class of complex IDEs that is fundamentally important for the study of quantum many-body systems [1]. To benchmark our result, we consider an equilibrium Dyson's equation for hopping electrons in the Bethe lattice [13, 43]. When \(t>0\), the equation of motion reads: \[i\partial_{t}G^{R}(t)=hG^{R}(t)+\int_{0}^{t}c^{2}G^{R}(t-s)G^{R}(s)ds \tag{5}\] In the context of quantum many-body theory, the time-dependent quantity \(G^{R}(t)\) is called the retarded Green's function, which contains important physical information such as the single-particle energy spectrum of the physical system. The memory kernel \(K(t-s)=c^{2}G^{R}(t-s)\) is the self-energy of the system. \(h,c\) are the modeling parameters that will be varied when we do multi-trajectory training. Throughout this section, the initial condition \(G^{R}(0)=-i\) is chosen. According to the analysis by Kaye et al. [13], Eqn (5) admits analytical solution: \[G^{R}(t)=-ie^{-iht}\frac{J_{1}(2ct)}{ct},\qquad t>0\] where \(J_{1}(t)\) is the Bessel function of the first kind. We will use this analytical solution to benchmark the extrapolation results generated by RNN. The training procedures are almost the same as the previous example. The slight differences are summarized in the following paragraph: Training detailsFor IDE (5), we use an RNN model with 2 layers of LSTM cells and the hidden state size for each layer is 128. The input and output are the same as it was for IDE (4). For the single trajectory training case, we set \(h=-1\) and \(c=1\) to build the dataset. For the multi-trajectory training, we made a slight modification to the training procedure. We first randomly sample \(h\) from the domain \([1,10]\) for 2000 times, while keeping \(c=1\). This yields a total of 2000 trajectories as the database for the subsequent RNN training. Then for each epoch, we randomly choose a batch of 10 data pairs \(\{G(i\Delta t),I(i\Delta t)\}_{i=1}^{N}\) from the whole database (possibly with replacement) to optimize the RNN. In this fashion, we create a more robust model since for each epoch, the data pair \(\{G(i\Delta t),I(i\Delta t)\}_{i=1}^{N}\) used in optimization is different. Results discussionAll the training and testing results are summarized in Figure 8. In the first row, we show the single trajectory training result where the data is collected for \(t\in[0,10]\) and we use the RNN to extrapolate the same trajectory up to \(T=40\) (3000 timesteps into the future). The second row shows the multi-trajectory training results where the parameters for the test trajectory are set to be \(h=8,c=1\). Note that \(h\) is chosen from the sampling domain \([1,10]\) but is chosen as a parameter to be used in the training database. The third row is for the same multi-trajectory training while showing an out-of-sampling domain example where \(h=11.5,c=1\). As we can see, both the single trajectory training and the multi-trajectory training yield precise predictions of the future-time dynamics of the Dyson's equation. Moreover, the RNN also predicts the correct asymptotic behavior \begin{table} \begin{tabular}{c c c} Total simulation time & AB3 + RNN & FE + SR \\ \hline \hline 20 & 0.8684s & 60.3825s \\ 40 & 1.5028s & 166.0921s \\ 80 & 2.5220s & 475.0468s \\ 160 & 4.7412s & 1602.8664s \\ \end{tabular} \end{table} Table 1: Comparison of wall-clock time using the RNN method and a regular IDE solver to extrapolate dynamics with \(\Delta t=0.01\) for both methods. Here, total simulation time refers to the final time \(T\) used in solving the IDE. of \(G(t)\), i.e., \(G(t)\to 0\) as \(t\rightarrow\infty\). All these findings are consistent with what we found in the previous example. In comparison, we also see more accurate and robust results in the multi-trajectory case, both visually and in terms of the error plots. Since we have used many trajectories in training, the RNN is able to learn a more concrete mapping from \(G(t)\to I(t)\). This leads to better predictability of the RNN on unseen dynamics, as well as greater generalizability to unseen system parameters, as shown in the final row, where \(h=11.5\not\in[1,10]\). Nevertheless, we find in all cases that our RNN method makes accurate predictions for the dynamics well past the training regime. ## 5 Conclusion In this paper, we introduced an RNN-based machine-learning technique that uses LSTM as the basic modeling module to learn the nonlinear integral operator in an IDE. Such a learning scheme allows us to turn an IDE to an ODE that can be solved efficiently by a standard ODE solver for a large \(t\). We showed that a more effective way to learn a nonlinear integral operator is to include multiple training trajectories generated from different the solution of IDEs defined by different streaming terms within a small time window in the training data. The effectiveness of this approach was demonstrated with two test examples. The generalizability of the learned operator was demonstrated by using the learned map to predict the dynamics of a new IDE that is driven by a completely different streaming term that is outside of the parameter range of the training data. Moreover, since the RNN consists of layers of function composition, it is almost immediate to generate a next timestep collision integral \(I(t)\) given the input. Figure 8: RNN training and extrapolating results for the Dyson’s equation (5). The first row displays the single trajectory training result for \(h=-1,c=1\). The second row is the multi-trajectory training results where the RNN is trained for \(h\in[1,10],c=1\), and tested on \(h=8,c=1\). The third row uses the same multi-trajectory model, but tests on \(h=11.5,c=1\). This leads to an overall \(O(T)\) scaling of computational cost (the same as an ODE solver) when we use the RNN to solve the IDE, in contrast with the \(O(T^{2})\) scaling of a regular IDE solver. Due to the scalability of the RNN architecture, we expect that the methodology can be generalized and used to solve high-dimensional IDEs, such as the Kadanoff-Baym equations in nonequilibrium quantum many-body theory. ## 6 Acknowledgement This material is based upon work supported by the U.S. Department of Energy, Office of Science, Office of Advanced Scientific Computing Research and Office of Basic Energy Sciences, Scientific Discovery through Advanced Computing (SciDAC) program under Award Number DE-SC0022198. This research used resources of the National Energy Research Scientific Computing Center, a DOE Office of Science User Facility supported by the Office of Science of the U.S. Department of Energy under Contract No. DE-AC02-05CH11231 using NERSC award BES-ERCAP0020089.
2304.06840
Structured Pruning for Multi-Task Deep Neural Networks
Although multi-task deep neural network (DNN) models have computation and storage benefits over individual single-task DNN models, they can be further optimized via model compression. Numerous structured pruning methods are already developed that can readily achieve speedups in single-task models, but the pruning of multi-task networks has not yet been extensively studied. In this work, we investigate the effectiveness of structured pruning on multi-task models. We use an existing single-task filter pruning criterion and also introduce an MTL-based filter pruning criterion for estimating the filter importance scores. We prune the model using an iterative pruning strategy with both pruning methods. We show that, with careful hyper-parameter tuning, architectures obtained from different pruning methods do not have significant differences in their performances across tasks when the number of parameters is similar. We also show that iterative structure pruning may not be the best way to achieve a well-performing pruned model because, at extreme pruning levels, there is a high drop in performance across all tasks. But when the same models are randomly initialized and re-trained, they show better results.
Siddhant Garg, Lijun Zhang, Hui Guan
2023-04-13T22:15:47Z
http://arxiv.org/abs/2304.06840v1
# Structured Pruning for Multi-Task Deep Neural Networks ###### Abstract Although multi-task deep neural network (DNN) models have computation and storage benefits over individual single-task DNN models, they can be further optimized via model compression. Numerous structured pruning methods are already developed that can readily achieve speedups in single-task models, but the pruning of multi-task networks has not yet been extensively studied. In this work, we investigate the effectiveness of structured pruning on multi-task models. We use an existing single-task filter pruning criterion and also introduce an MTL-based filter pruning criterion for estimating the filter importance scores. We prune the model using an iterative pruning strategy with both pruning methods. We show that, with careful hyper-parameter tuning, architectures obtained from different pruning methods do not have significant differences in their performances across tasks when the number of parameters is similar. We also show that iterative structure pruning may not be the best way to achieve a well-performing pruned model because, at extreme pruning levels, there is a high drop in performance across all tasks. But when the same models are randomly initialized and re-trained, they show better results. ## 1 Introduction Multi-task learning (MTL) addresses multiple machine learning tasks simultaneously by creating a single multi-task deep neural network (DNN) [39]. Due to parameter sharing, a multi-task DNN model is more computation and memory efficient compared to multiple single-task models. The MTL framework is extremely useful for resource-constrained devices like smartphones, wearables, and self-driving cars that host AI-powered applications but have low memory resources and strict latency requirements. For example, in self-driving cars, the model needs to recognize traffic lights, objects, and lanes based on the input signal [37]. On the other hand, network pruning [26, 11, 24] is a long-standing and effective method to compress DNNs. It aims to detect the importance of model parameters and remove the ones that tend to have the least significance on the performance. Approaches for network pruning can be classified as unstructured pruning methods [24, 11] that mask individual weights in the network, and structured pruning methods [26, 36] that remove complete filters and directly lead to efficient deep neural models without requiring specialized hardware for sparse structures. Network pruning is studied rigorously in literature for single-task models and there exist many pruning criteria based on weight magnitude [26, 11], connection sensitivity [10, 25], and even learning-based pruning methods [7, 19]. However, the study on the effectiveness of structured pruning methods on multi-task models is sparse. A few works like [4, 17] propose weight sharing and merging strategies for constructing a multi-task model from multiple single-task models such that there is a minimum conflict between tasks. Then the constructed multi-task model could be effectively pruned with single-task pruning methods. But these works show very similar results when comparing their proposed pipeline with the baseline single-task pruning methods. Another work [43], proposed a method to directly prune MTL networks but while pruning those models with single-task pruning baselines, they did not try different hyperparameter settings to retrain/fine-tune the pruned models. It could be possible that different hyperparameter settings would work better because different pruning methods lead to different architectures. In this work, we investigate the effectiveness of structured pruning on multi-task DNNs. We apply two structured pruning methods to prune multi-task models and show that regardless of the method used, we can obtain similar results from the pruned models with the same number of param eters. Specifically, we use an existing single-task pruning method as well as introduce another MTL-based pruning criterion. The proposed criterion is called CosPrune and it identifies and prunes the convolutional filters that have conflicts between tasks. It uses pairwise cosine similarity between the task-specific gradients that flow through the filter during back-propagation. We accumulate this similarity score for some training iterations for every filter in the multi-task model. The filters with the least accumulated scores are pruned away. In contrast, the single-task pruning method is called Taylor Pruning [36] which is a popular gradient-based pruning method. It determines the importance of the filter by looking at the increase in the loss function if that filter is removed. The Taylor pruning importance score is also accumulated over some training iterations before pruning. We start our analyses by using the iterative pruning and fine-tuning strategy which repeatedly prunes a small proportion of filters and fine-tunes the multi-task model to gain back the lost performance [11, 30]. Using this strategy we get consistently better results with CosPrune against Taylor pruning across all the tasks. The multi-task model achieved higher GFLOPs/parameter reduction with CosPrune without performance loss across all the tasks. This shows that the proposed CosPrune criterion coupled with iterative pruning is a reasonable method for pruning multi-task models. **However, when we re-train the pruned models independently with random initialization, we observe that they can give relatively better results on all the tasks when compared to the corresponding fine-tuning stage of iterative pruning.** The key is to determine good learning rates for each of the pruned models. Using the same learning rates is not the best strategy to compare different pruned architectures. This is because every model has different layer-wise configurations and so, an optimal hyper-parameter setting for one model may not be best for the other models with different architectural designs. This type of analysis is generally not done in the existing literature - the same training settings are used for the dense model as well as the pruned models. A study on single-task structured pruning [30] also shows that re-training the pruned models from random initialization can lead to better results than fine-tuning the pruned architectures in the iterative pruning setting. Furthermore, the pruned architectures from different pruning methods give similar results to each other at the same parameter level after re-training. **There are no consistent winners with respect to different pruning criteria, which is contrary to what we observe in the case of iterative pruning.** There are also some recent works [27, 29] in the context of single-task neural networks where random channel pruning is able to match the results of the dense model under appropriate settings. Similarly, another work [30] used different pruning methods on various architectures to show that randomly re-initializing the pruned models can match the performance of the respective unpruned models but they did not compare those different pruning strategies on the same model. We go beyond existing works and apply different structured pruning methods to the same multi-task model. **We emphasize that the pruned MTL model obtained from any reasonable pruning method can perform well if it is trained from random initialization with its optimal learning rate.** And we would like researchers to pay attention to the re-training comparisons with sufficient hyper-parameter tuning when they try to propose a new pruning method. ## 2 Related Works **Multi-Task Learning**: Deep MTL networks afford numerous benefits in terms of computation (storage and latency) [22], knowledge sharing between tasks [1] and improving generalization in the learned representations [35] due to which they have applications across many domains like Computer Vision [8, 13, 14, 20], Robotics [46, 50], and Reinforcement Learning [42, 45, 47, 48]. The most common MTL framework is hard parameter sharing [2, 39] where a backbone network is shared among all tasks and with individual task-specific heads. Soft parameter sharing, on the other hand, has different sets of parameters for individual tasks [35, 44] and various methods are used to effectively combine information from them [21, 34, 38] to make predictions. **Deep Neural Network Pruning**: It has long been established that the deep neural networks are highly over-parameterized [15, 16, 24, 26, 33], and more than \(90\%\) of the connections can be pruned away without losing accuracy. Unstructured pruning methods for single-task models [11, 12] can achieve high sparsity with latency improvements with accelerated hardware for sparse neural networks [51]. On the other hand, structured pruning can directly lead to computational benefits by removing whole filters in the case of convolutional layers [26]. Gradient-based metrics for estimating the importance scores of the filters have recently become popular over magnitude-based criteria [26]. For example, Taylor Pruning [36] uses the dot product between the filter weights with its gradient to approximate the change in loss function that could occur if that filter is masked. Another example is SNIP [25], which determines the connection sensitivity using a similar importance metric as Taylor Pruning but it is done only once at initialization to apply single-shot pruning. Furthermore, random channel pruning methods [27, 29] are also shown to perform well under appropriate training conditions. **Pruning Multi-task Neural Networks**: There is very limited study on pruning MTL neural networks but nonetheless it is an important problem because of its tremendous potential in deriving efficient deep learning models. At the same time, it is also a difficult problem because of the coexistence of complex task relationships in the shared parameter space and redundancy in the neural network. A recent work on MTL pruning is DiSparse [43] which aims to disentangle task relationships to find the unanimously least important filters across all the tasks and prune them. Another work called PAM [17] propose a method to merge single-task models into an MTL network such that the resulting MTL network can be safely pruned while considering the tasks' relatedness. Similarly, other works like [5, 18] propose different merging strategies for the construction of computationally efficient MTL networks. All of these existing works do baseline comparisons by using single-task pruning methods to prune their MTL networks. However, they use only the hyperparameters that are specified in the original study on single-task pruning methods irrespective of the different model architectures and sparsity ratios. But in our work, we do extensive analyses and hyperparameter tuning for both the pruning methods involved to show their true effectiveness in pruning deep MTL networks. ## 3 Pruning Methods In this section, we will define our Multi-Task Learning model and the proposed CosPrune importance score estimation method as well as review the Taylor Pruning importance score. **Multi-task framework**: Given a set of \(T\) tasks \(\mathcal{T}=\{\tau_{1},\dots,\tau_{T}\}\), an MTL dataset with inputs, \(\mathcal{X}\), and the corresponding labels \(\mathcal{Y}=\{Y_{1},\dots,Y_{T}\}\) where \(Y_{t}\) is set of labels for task \(\tau_{t}\in\mathcal{T}\), we want to learn the mapping \(f_{\Theta}:\mathcal{X}\rightarrow\mathcal{Y}\), where \(\Theta=\theta_{s}\cup\{\theta_{t}\}_{t=1}^{T}\). Here \(\theta_{s}\) is the set of model parameters that are shared by all the tasks and \(\theta_{t}\) is the set of parameters only for task \(\tau_{t}\). From now, we will denote \(\{\theta_{t}\}\) as the set of all the task-specific parameters for all the tasks collectively and omit values of \(t\) for abbreviation. The parameters \(\Theta\) are trained by minimizing the multi-task loss function given by \[\mathcal{L}(\mathcal{X},\mathcal{Y},\Theta)=\sum_{t=1}^{T}\ell_{t}\left( \mathcal{X},\mathcal{Y},\theta_{s},\theta_{t}\right) \tag{1}\] where \(\ell_{t}\left(\mathcal{X},\mathcal{Y},\theta_{s},\theta_{t}\right)\) is the loss function for the task \(\tau_{t}\). **CosPrune Importance Score Estimation**: Let \(\mathbf{W}^{k\times k\times c}\in\Theta\) be a convolutional filter with kernel size \(k\), and \(c\) channels, then the weights of this filter will be optimized using the gradient descent given by equation 2, \[\mathbf{W}\leftarrow\mathbf{W}-\eta\nabla_{\mathbf{W}}\mathcal{L}(\mathcal{X },\mathcal{Y},\Theta) \tag{2}\] where \(\eta\) is the learning rate and \(\nabla_{\mathbf{W}}\mathcal{L}(\mathcal{X},\mathcal{Y},\Theta)\) is the gradient of the total loss function with respect to \(\mathbf{W}\). Let \(\mathbf{g}_{\mathcal{T}}^{\mathbf{W}}=\nabla_{\mathbf{W}}\mathcal{L}(\mathcal{ X},\mathcal{Y},\Theta)\), then \[\mathbf{g}_{\mathcal{T}}^{\mathbf{W}}=\sum_{t=1}^{T}\mathbf{g}_{t}^{\mathbf{W}} \tag{3}\] where \(\mathbf{g}_{t}^{\mathbf{W}}=\nabla_{\mathbf{W}}\ell_{t}\left(\mathcal{X}, \mathcal{Y},\theta_{s},\theta_{t}\right)\). \(\mathbf{g}_{\mathcal{T}}^{\mathbf{W}}\) and \(\mathbf{g}_{t}^{\mathbf{W}}\) can be denoted as the total gradient and task-\(\tau_{t}\) gradient respectively with respect to the parameter \(\mathbf{W}\). Note that the total gradient is the vector sum of all the individual task gradients. These individual gradients can have high differences in magnitudes as well as they can point to different directions with negative cosine similarity between them. This can lead to conflicts between different tasks and that could be detrimental to the optimization process [49]. There have been several works like PCGrad [49], MGDA [6], CAGrad [28] that apply various methods to remove the conflicts in the optimization process. In our work, we prune the filters that have the highest degree of accumulated conflicts but optimize our MTL model with the total gradient. This helps us to achieve the highest degree of optimization in terms of computation and performance. To calculate the degree of conflict, we define the CosPrune Importance score, as the sum of pairwise cosine similarity between all the tasks for the parameter \(\mathbf{W}\). Let \(\tilde{\mathbf{g}}_{t}^{\mathbf{W}}=\frac{\mathbf{g}_{t}^{\mathbf{W}}}{\| \mathbf{g}_{t}^{\mathbf{W}}\|}\) be the normalized task gradient, and \(\{\mathbf{g}_{t}^{\mathbf{W}}\}\) be the set of all the task gradients with respect to \(\mathbf{W}\), then \(\mathcal{C}\left(\mathbf{W},\{\mathbf{g}_{t}^{\mathbf{W}}\}\right)\) can be calculated using: \[\mathcal{C}\left(\mathbf{W},\{\mathbf{g}_{t}^{\mathbf{W}}\}\right)=\sum_{(\tau_ {i},\tau_{j})\in\mathcal{T}\times\mathcal{T}}\tilde{\mathbf{g}}_{i}^{\mathbf{W }}\cdot\tilde{\mathbf{g}}_{j}^{\mathbf{W}} \tag{4}\] We only prune the shared parameters, \(\mathbf{W}\ \in\theta_{s}\), therefore \(\mathbf{g}_{t}^{\mathbf{W}}\neq\mathbf{0}\) for all \(t=1,\dots,T\). The value of \(\mathcal{C}(.,.)\) will be higher when the pairwise gradients are in agreement and it will lower if tasks are in conflict. For calculating the final importance score of a filter, we keep on adding the CosPrune scores for all the filters for a fixed number of training iterations. After that, we rank the filters according to their accumulated importance scores and prune the lowest-scoring filters. After pruning, we reset the accumulated scores to zero and fine-tune the model again along with collecting the CosPrune scores of the remaining unpruned filters. The details are provided in Algorithm 1. **Taylor Pruning [36]:** It is a structured pruning method for single-task convolution neural networks which serves as a popular baseline for modern gradient-based pruning methods. In this method, the importance score of a filter is defined by the squared change in the loss function induced by removing the filter. To make the computation efficient, the squared change is approximated by the first-order Taylor expansion which simplifies to a dot product between the filter weights and its gradient. Let the importance score for the filter \(\mathbf{W}\) be \(\mathbf{I}\), then it is given by \[\mathbf{I}=\mathbf{W}.\mathbf{g}_{\mathcal{T}}^{W} \tag{5}\] where \(\mathbf{g}_{\mathcal{T}}^{\mathbf{W}}\) is the total gradient passing through filter \(\mathbf{W}\) during backpropagation as define in equation 3. We experiment with both CosPrune and Taylor pruning methods and compare their performance in effectively pruning the MTL models. ## 4 Experiments and Results In this section, we provide the details of all the experiments and provide quantitative evidence of our claims. ### Setup **Model Architecture**: For our multi-task model, we use a hard parameter-sharing paradigm where the backbone parameters are shared across all the tasks and individual classification heads are used for each task. MTL backbone comprises of VGG-16 [41] model without the last fully-connected layers and MTL classification heads use Artrous Spatial Pyramid Pooling (ASPP) heads [3] for each task. The backbone contains approximately \(71M\) parameters and each ASPP head has approximately \(13.4M\) parameters. In all of our experiments, we only prune the backbone but all the results are reported with the total model parameters (backbone + all task heads) which are approximately \(84.12M\) parameters. **Multi-Task Learning (MTL) Dataset**: In this work, NYUv2 [40] dataset is used for all of the experiments. It is a popular Multi-Task Learning MTL dataset with densely labeled images recorded from RGB and Depth cameras of Microsoft Kinect. It contains three tasks - Semantic Segmentation, Depth Estimation, and Surface Normal Prediction whose ground truth labels are defined in [8]. **Evaluation Metrics**: Semantic segmentation is evaluated using mean Intersection over Union (mIoU) and the Pixel accuracy (both the higher the better). Depth Estimation is evaluated using absolute and relative errors calculated using the L1 loss between the ground truth and predictions (both the lower the better). For this task, we also report the relative difference between the prediction and ground truth via the percentage of \(\delta=\max\left(\frac{y_{pred}}{y_{gt}},\frac{y_{gt}}{y_{pred}}\right)\) within threshold \(1.25,1.25^{2}\), and \(1.25^{3}\)[9] (the higher the better). Surface Normal Prediction is evaluated using the Mean and Median Angle errors calculated by cosine similarity loss (the lower the better). We also report the percentage of pixels whose predictions are within \(11.25^{\circ}\), \(22.5^{\circ}\), and \(30^{\circ}\) to the ground truth (higher the better) [8]. Due to space constraints and a high number of pruned model configurations, we report Pixel Accuracy for Semantic Segmentation, relative error for Depth Estimation, and Angle Mean for Surface Normal Prediction as the main evaluation metrics, for both pruning methods. All other metrics are reported in the supplementary material **Loss Functions and Model Training**: For training on the NYUv2 dataset, the model minimizes the sum of losses from the individual tasks with equal weightage. Semantic segmentation uses cross-entropy loss, Surface Normal Prediction uses cosine similarity loss and Depth Estimation uses L1 loss as its training signals. We start with a randomly initialized MTL model with VGG-16 backbone and ASPP heads and train the model for 500 epochs. We use a batch size of \(16\), and \(0.0001\) learning rate with cosine scheduling [31]. We use AdamW [32] optimizer for the iterative pruning experiments. **Model Pruning**: After the model is trained on the NYUv2 dataset, we apply iterative pruning with different filter pruning criteria (CosPrune and Taylor pruning) to get pruned MTL models. We initialize the model with the NYUv2 trained weights and set the initial learning rate as \(10^{-5}\) with cosine scheduling for \(500\) epochs and start the pruning process. For every iteration (batch of inputs to the model), we get the individual task gradients by applying backward propagation on task losses. Then we calculate the importance score for every filter in the model. The importance scores are accumulated for 10 epochs after which 100 filters that have the lowest accumulated scores, are pruned. This completes a single pruning iteration and after it, the accumulated filter importance scores are reset to \(0\). The learning rate and scheduler are also rewinded to the initial settings and the pruning process continues. Note that the parameters of the model keep on updating using the total loss function after every iteration which marks the fine-tuning phase of the model. ### Results: Multi-Task Structure Pruning **Iterative Pruning Results**: We applied the iterative pruning strategy with both the Taylor Pruning criterion and the CosPrune importance criterion separately on the model initialized with the trained NYUv2 weights and ran \(6\) sets of experiments to accommodate for the variance in each method. We present a subset of evaluation metrics in Figure 1, where we show the best values for different task metrics (\(y\)-axis) against the number of parameters (\(x\)-axis) for both methods. We have shown plots for Pixel Accuracy (Semantic Segmentation), relative error (Depth Estimation), and Angle Mean (Normal prediction). The plots for the remaining metrics are reported in the supplementary material. From the plots in Figure 1, we can see that the CosPrune method is consistently better than the Taylor pruning method across all the tasks, i.e., it has a relatively lower Pixel Accuracy drop in the case of Semantic Segmentation, and lower error increment in case of Depth Estimation and Normal prediction tasks. We also report numerical values in Table 1 where we compare both the methods for the pruned models with a similar number of parameters. We can see that there is the highest performance gap at \(14.3M\) model parameters which is \(83\%\) parameter reduction, and Pixel Accuracy is \(\mathbf{16.39}\%\) better, Depth Estimation is \(\mathbf{15.93}\%\) better and Normal prediction is \(\mathbf{3.45}\%\) better than the Taylor pruning method. However, when with extreme pruning at \(13.4M\) parameters, the gap is significantly lesser but nonetheless still better. For \(59.9M\) parameters, the Pixel Accuracy slightly drops for CosPrune but all the metrics are very close as can also be seen from the plots in Figure 1. **Re-training the Pruned models**: So far we have observed that the CosPrune can efficiently prune the MTL model to achieve high parameter reduction within a few iterations while maintaining its performance over the baseline method. Both pruning criteria lead to pruned models with different architectural designs in terms of the number of filters in each layer of the backbone. Since there is a difference in the performance, we want to figure out the role of these different layer configurations in the model's performance for all the tasks. To do this, we take the pruned models at various iterations, randomly initialize the weights and train them to converge on the NYUv2 dataset. Initially, we were using the same hyperparameters for training all the models but saw that some models were severely affected. For example, a model with \(15M\) parameters, obtained from CosPrune could achieve only \(25.5\%\) Pixel Accuracy even after training for \(500\) epochs. But when the learning rate of \(0.0001\) was used it reached over \(42\%\), and the performance of the other two tasks was also improved. In another case, \begin{table} \begin{tabular}{c c|c c c|c c c|c c c} \hline \hline \(\#\)Params & \multicolumn{3}{c|}{Semantic Segmentation} & \multicolumn{3}{c|}{Depth Estimation} & \multicolumn{3}{c}{Surface Normal} \\ & & \multicolumn{3}{c|}{Pixel Accuracy \((\%)\uparrow\)} & \multicolumn{3}{c|}{Relative Error \(\downarrow\)} & \multicolumn{3}{c}{Angle Mean \(\downarrow\)} \\ \hline \hline \(\#(M)\) & \(\%_{R}\) & Taylor & CosPrune & \(\%\Delta\uparrow\) & Taylor & CosPrune & \(\%\Delta\downarrow\) & Taylor & CosPrune & \(\%\Delta(\downarrow)\) \\ \hline \(59.9\) & \(28.7\) & \(\mathbf{45.96}\) & \(45.91\) & \(-\)\(0.11\) & \(0.2616\) & \(\mathbf{0.2614}\) & \(-\)\(\mathbf{0.08}\) & \(18.54\) & \(\mathbf{18.37}\) & \(-\mathbf{0.92}\) \\ \(42.7\) & \(49.2\) & \(45.66\) & \(\mathbf{45.70}\) & \(+\)\(\mathbf{0.09}\) & \(\mathbf{0.2666}\) & \(0.2670\) & \(+\)\(0.17\) & \(18.35\) & \(\mathbf{18.22}\) & \(-\mathbf{0.73}\) \\ \(21.2\) & \(74.8\) & \(43.02\) & \(\mathbf{44.86}\) & \(+\)\(\mathbf{4.27}\) & \(0.2862\) & \(\mathbf{0.2777}\) & \(-\)\(\mathbf{2.98}\) & \(18.19\) & \(\mathbf{17.19}\) & \(-\mathbf{1.53}\) \\ \(17.6\) & \(79.1\) & \(41.56\) & \(\mathbf{42.98}\) & \(+\)\(\mathbf{3.41}\) & \(0.3384\) & \(\mathbf{0.2829}\) & \(-\mathbf{16.42}\) & \(18.16\) & \(\mathbf{18.03}\) & \(-\mathbf{0.71}\) \\ \(14.3\) & \(83.0\) & \(35.83\) & \(\mathbf{41.70}\) & \(+\)\(\mathbf{16.39}\) & \(0.3896\) & \(\mathbf{0.3276}\) & \(-\mathbf{15.93}\) & \(18.65\) & \(\mathbf{18.00}\) & \(-\mathbf{3.45}\) \\ \(13.4\) & \(84.0\) & \(34.88\) & \(\mathbf{36.08}\) & \(+\)\(\mathbf{3.43}\) & \(0.3928\) & \(\mathbf{0.3747}\) & \(-\)\(\mathbf{4.59}\) & \(18.82\) & \(\mathbf{18.39}\) & \(-\mathbf{2.26}\) \\ \hline \hline \end{tabular} \end{table} Table 1: Iterative pruning results at selected iterations. \(\#(M)\): _Number of model parameters in millions. \(\%_{R}\): \(\%\) parameter reduction with respect to full model. \(\%\Delta\uparrow(\downarrow)\): \(\%\) increase (decrease) with respect to Taylor pruning. \(\uparrow\): Higher the better \(\downarrow\): Lower the better_. Figure 1: Iterative pruning performance trends for different tasks for the Taylor and CosPrune methods. a model obtained from Taylor Pruning with \(14M\) parameters resulted in \(38\%\) Pixel Accuracy with \(0.0001\) learning rate, whereas the same model reached over \(44\%\) with \(0.001\) learning rate. Moreover, some pruned models gave their best results for \(0.0005\) learning rate. Therefore, to get the best possible performance from every pruned model, we trained them on \(3\) sets of learning rates which are \(0.001\), \(0.0005\), and \(0.0001\). We ran all the experiments for \(500\) epochs with cosine scheduling and used Adam [23] optimizer for training. We summarize results for a subset of models in Table 2. Each row shows the performance comparison between pruned models obtained from Taylor pruning and CosPrune which have the same number of parameters. We have also given the desired learning rate for each model. It seems that Taylor pruned models favor \(0.001\) learning rate with a few favoring \(0.0001\), and \(0.0005\). On the other hand, CosPruned models favor smaller learning rates of \(0.0001\), and \(0.0005\). The corresponding plots for the 3 tasks are shown in Figure 2. From the results in Table 2, we can see that the models obtained from different pruning methods lead to very similar performance across all the tasks when the number of parameters is roughly equal. Figure 2, also shows this similar trend where the winning method keeps on fluctuating with changing model parameters. In some cases, Taylor pruned models perform better than CosPruned models and in other cases, it is vice-versa but the results are still very close for both methods across all tasks. We have also compared the results of the individually pruned models with the results from the corresponding iterative pruning iterations in Figure 2. It can be seen that at very low parameters, the iterative pruning results become worse than the results of the models that were trained solely from scratch except in the case of normal estimation where the Angle Mean is slightly better in the case of the iterative CosPrune method. **Analyzing the Results**: We observed that if we consider the pruned models obtained from two different pruning methods, randomly initialize them and re-train them with their optimal learning rate, they give similar results for the same number of parameters. At some parameter levels, the pruned model obtained from Taylor pruning performed better but at some other parameter levels, the pruned model obtained from CosPrune gave better results. But there is only a slight difference in the results which could be in \begin{table} \begin{tabular}{c c|c c|c c|c c|c} \hline \hline \(\#\)Param & \multicolumn{2}{c|}{\(lr\) setting} & \multicolumn{2}{c|}{Semantic Segmentation} & \multicolumn{2}{c|}{Depth Estimation} & \multicolumn{2}{c}{Surface Normal} \\ & & & \multicolumn{2}{c|}{Pixel Accuracy \((\%)\uparrow\)} & \multicolumn{2}{c|}{Relative Error \(\downarrow\)} & \multicolumn{2}{c}{Angle Mean \(\downarrow\)} \\ \hline \(\#(M)\) & \(\%_{R}\) & Taylor & CosPrune & Taylor & CosPrune & Taylor & CosPrune & Taylor & CosPrune \\ \hline \(60.3\) & \(28.3\) & \(0.0005\) & \(0.0001\) & **47.82** & \(46.52\) & \(0.2688\) & **0.2525** & **17.97** & \(18.20\) \\ \(37.1\) & \(55.8\) & \(0.001\) & \(0.0001\) & **46.51** & \(46.18\) & \(0.2761\) & **0.2614** & **17.91** & \(18.21\) \\ \(29.7\) & \(64.6\) & \(0.001\) & \(0.0001\) & **46.44** & \(45.34\) & \(0.2835\) & **0.2761** & **17.85** & \(18.09\) \\ \(25.9\) & \(69.2\) & \(0.001\) & \(0.0005\) & \(46.86\) & **47.84** & \(0.2853\) & **0.2604** & **17.78** & \(17.97\) \\ \(19.1\) & \(77.3\) & \(0.001\) & \(0.0001\) & **45.54** & \(43.42\) & \(0.2874\) & **0.2570** & **17.86** & \(17.92\) \\ \(15.3\) & \(81.8\) & \(0.001\) & \(0.0001\) & \(42.86\) & **44.67** & \(0.3362\) & **0.2957** & \(18.08\) & **17.99** \\ \(14.4\) & \(82.9\) & \(0.001\) & \(0.001\) & \(41.82\) & **44.40** & \(0.3381\) & **0.3109** & \(18.10\) & **18.06** \\ \hline \hline \end{tabular} \end{table} Table 2: Results of the pruned models trained from scratch across different tasks. \(\#(M)\): _Number of model parameters in millions. \(\%_{R}\): \(\%\) parameter reduction with respect to full model. \(lr\) setting: Optimal learning rate for the respective model. \(\uparrow\): Higher the better \(\downarrow\): Lower the better._ Figure 2: Results of the pruned models, trained individually from scratch, across all the tasks for various model parameters. Solid plot lines correspond to primary results. Dashed plots correspond to the iterative pruning trends from Figure 1. duced by the randomness of the training process. By looking at these results, we can conclude that different architecture configurations with a similar number of parameters do not play a major role in the final performance across tasks as long as the models are trained with their optimal training settings. Furthermore, we saw that the structured iterative pruning was biased towards one pruning criterion over the other as Figure 1 shows that the CosPrune models outperformed Taylor pruned models at the same parameter level. But when the pruned models were re-trained from scratch, their final performances became similar and even closer to the unpruned model as seen in Figure 2. But for both methods, there was a steep drop in the performance at extreme pruning ratios, which was again mitigated by random initialization and re-training that led to better performance even at those extreme pruning ratios. This might be happening because, in the case of iterative structured pruning, the inherited trained weights from previous pruning iterations may act as bad initialization for the pruned models at successive iterations [30]. Even if those weights were optimal for the earlier unpruned model versions, they might not be good for the current version because of changes in the architecture after pruning and it can be difficult for the optimizer to find another good local minimum. ### Additional Observation for NYUv2 Dataset **Best Validation Metric**: In the case of multi-task learning, total validation loss is traditionally considered a good validation metric that implies that the model is performing well on all the tasks collectively. However, in our experiments on the NYUv2 dataset, we observed that most of the time the least total validation loss failed to achieve the best model performance. In many instances, the Pixel Accuracy was low at the epoch with the best validation loss but it reached higher at some other epochs but with a slightly higher loss. However, the results for Depth Estimation and Surface Normal Prediction were similar at these different epochs. To verify this further, we tracked the best Pixel Accuracy in a training run and also tracked the best total validation loss in a separate training run but done with the same settings of hyperparameters. We trained the model 3 times to accommodate for the variance and show these results in Table 3. We can see that all the metric values except the Angle Mean are better when the model at the highest Pixel Accuracy is considered as compared to the model at least validation loss. This is also quite reasonable because the Semantic Segmentation task is the most difficult task and the scale of its loss function is higher than the other two tasks. Therefore, for getting the best model, we considered the best Pixel Accuracy score instead of the total validation loss. ## 5 Conclusions In this work, we used two different structured pruning methods to compress deep multi-task neural networks. We are first to comprehensively analyze their effectiveness in pruning such networks. Specifically, we showed that different architectural configurations of the pruned models can give similar results regardless of the pruning method used if the number of parameters is the same. We also showed that iterative structured pruning may not be the best strategy to compress deep multi-task models. They might favor one pruning strategy over another. But regardless of the pruning strategy used, the performance of the pruned models can take a steep drop after certain iterations. However, we also showed that after random initialization and re-training those models with their respective optimal learning rates, they can give much higher performance across all the tasks.
2310.10603
Exploring the Power of Graph Neural Networks in Solving Linear Optimization Problems
Recently, machine learning, particularly message-passing graph neural networks (MPNNs), has gained traction in enhancing exact optimization algorithms. For example, MPNNs speed up solving mixed-integer optimization problems by imitating computational intensive heuristics like strong branching, which entails solving multiple linear optimization problems (LPs). Despite the empirical success, the reasons behind MPNNs' effectiveness in emulating linear optimization remain largely unclear. Here, we show that MPNNs can simulate standard interior-point methods for LPs, explaining their practical success. Furthermore, we highlight how MPNNs can serve as a lightweight proxy for solving LPs, adapting to a given problem instance distribution. Empirically, we show that MPNNs solve LP relaxations of standard combinatorial optimization problems close to optimality, often surpassing conventional solvers and competing approaches in solving time.
Chendi Qian, Didier Chételat, Christopher Morris
2023-10-16T17:31:25Z
http://arxiv.org/abs/2310.10603v1
# Exploring the Power of Graph Neural Networks in Solving Linear Optimization Problems ###### Abstract Recently, machine learning, particularly message-passing graph neural networks (MPNNs), has gained traction in enhancing exact optimization algorithms. For example, MPNNs speed up solving mixed-integer optimization problems by imitating computational intensive heuristics like strong branching, which entails solving multiple linear optimization problems (LPs). Despite the empirical success, the reasons behind MPNNs' effectiveness in emulating linear optimization remain largely unclear. Here, we show that MPNNs can simulate standard interior-point methods for LPs, explaining their practical success. Furthermore, we highlight how MPNNs can serve as a lightweight proxy for solving LPs, adapting to a given problem instance distribution. Empirically, we show that MPNNs solve LP relaxations of standard combinatorial optimization problems close to optimality, often surpassing conventional solvers and competing approaches in solving time. ## 1 Introduction Recently, there has been a surge of interest in training _message-passing graph neural networks_ (MPNNs) to imitate steps of classical algorithms, such as for shortest-path problems Cappart et al. (2021); Velickovic et al. (2020). As many of those problems can be formulated as linear optimization problems (LPs), it is natural to ask whether MPNNs could be trained to solve general LPs, at least approximately. Another recent line of research makes this question particularly intriguing. In integer linear optimization, state-of-the-art solvers all rely on the branch-and-bound algorithm, in which one must repeatedly select variables, subdividing the search space. The best-known heuristic for variable selection is known as "strong branching," which entails solving LPs to score the variables. This heuristic is, unfortunately, too computationally expensive to use in practice. However, in recent years, there has been a collection of works (Gasse et al., 2019; Gupta et al., 2020, 2022; Nair et al., 2020; Seyfi et al., 2023) that have proposed to use MPNNs to imitate strong branching, with impressive success. No theoretical explanation has ever been put forward to explain this success. However, perhaps the most straightforward explanation would be that MPNNs implicitly learn to imitate the LP solving underlying strong branching. Chen et al. (2023) provide a first step towards an explanation. In this work, the authors propose to encode LPs as bipartite graphs in the spirit of (Gasse et al., 2019) and show that MPNNs, in principle, can learn to predict the optimal solution of an LP instance up to arbitrary small \(\varepsilon\) concerning the supremum norm. They also provide some small-scale experiments suggesting that MPNNs can learn to approximate LP solutions surprisingly well. While a step in the right direction, their theoretical result heavily relies on invoking the universal approximation theorem for multi-layer perceptrons Cybenko (1992); Leshno et al. (1993), and therefore does not explain why modestly-sized MPNNs could be particularly effective LP solvers in practice. In this paper, we present instead a more specific explanation. We show that several variants of _interior-point methods_ (IPMs) Gondzio (2012); Nocedal and Wright (2006), an established class of polynomial-time algorithms for solving LPs, can be interpreted as an MPNN with a specific architecture and choice of parameters that takes as input a graph representation of the LP. Specifically, for two common IPM variants, we show that a sequence of standard MPNN steps can emulate a single iteration of the algorithm on a tripartite (rather than bipartite) graph representation of the LP. This novel theoretical result suggests several conclusions. First, it indicates that MPNNs appear successful at imitating LP solving because they might often be imitating IPMs and that there is a close connection between MPNNs and this specific LP algorithm. Secondly, although the MPNN's architecture in our theoretical result involves many MPNN layers, MPNNs are a natural choice of machine learning model for LP solving. It is likely possible to approximately solve LPs with fewer layers. To prove the last hypothesis, we train MPNNs with sev eral layers less than predicted by our theoretical results to imitate the output of a practical IPM algorithm for LP solving, resulting in the _IPM-MPNN_ architecture. Our empirical results show that IPM-MPNNs can lead to reduced solving times compared to a state-of-the-art LP solver with time constraints and competing neural network-based approaches; see Figure 0(b) for an overview of our approach. _In summary, our findings significantly contribute to the theoretical framework of data-driven exact optimization using MPNNs, and we also showcase the potential of MPNNs in serving as a light-weight proxy for solving LPs._ ### Additional related works In the following, we discuss relevant related work. **MPNNs** MPNNs (Gilmer et al., 2017; Scarselli et al., 2009) have emerged as a flexible framework for machine learning on graphs and relational data. Notable instances of this architecture include, e.g., Duvenaud et al. (2015); Hamilton et al. (2017); Velickovic et al. (2018), and the spectral approaches proposed in, e.g., Bruna et al. (2014); Defferrard et al. (2016); Kipf and Welling (2017)--all of which descend from early work in Baskin et al. (1997); Kireev (1995); Merkwirth and Lengauer (2005); Micheli (2009); Micheli and Sestito (2005); Scarselli et al. (2009); Sperduti and Starita (1997). **Machine learning for combinatorial optimization**Bengio et al. (2021) discuss and review machine learning approaches to enhance combinatorial optimization (CO). Concrete examples include the imitation of computationally intensive variable selection rules within the branch-and-cut framework (Khalil et al., 2016; Zarpellon et al., 2020), learning to run (primal) heuristics (Khalil et al., 2017; Chmiela et al., 2021), learning decompositions of large MILPs for scalable heuristic solving (Song et al., 2020), learning to generate cutting planes (Deza and Khalil, 2023) or leveraging machine learning to find (primal) solutions to stochastic integer problems quickly (Bengio et al., 2020)--see Kotary et al. (2021) for a high-level overview of recent advances. **MPNNs for CO** Many prominent CO problems involve graph or relational structures, either directly given as input or induced by the variable-constraint interactions. Recent progress in using MPNNs to bridge the gap between machine learning and combinatorial optimization is surveyed in Capppart et al. (2021). Most relevant to the present work, Gasse et al. (2019) proposed to encode the variable-constraint interaction of a mixed-integer linear optimization problem as a bipartite graph and trained MPNNs in a supervised fashion to imitate the costly strong branching heuristic, which entails solving multiple linear optimization problems, within the branch-and-cut framework (Achterberg et al., 2005). Building on that, Gupta et al. (2020) proposed a hybrid branching model using an MPNN at the initial decision point and a light multi-layer perceptron for subsequent steps, showing improvements on pure CPU machines. Subsequently, Nair et al. (2020) expanded the MPNN approach to branching by implementing a GPU-friendly parallel linear programming solver using the alternating direction method of multipliers that allows scaling the strong branching expert to substantially larger instances, also combining this innovation with a novel MPNN approach to diving. For all the above works, it remains largely unclear why MPNNs are good at (approximately) predicting strong branching scores. Moreover, Khalil et al. (2022) used MPNNs to predict the probability of variables being assigned to 0 or 1 in near-optimal solutions of binary-integer linear optimization problems. Ding et al. (2020) used MPNNs on a tripartite graph consisting of variables, constraints, and a single objective node enriched with hand-crafted node features. The target is to predict the 0-1 values of the so-called _stable variables_, i.e., variables whose assignment does not change over a set of pre-computed feasible solutions. Li et al. (2022) used MPNNs on a bipartite graph together with a pointer network (Bello et al., 2016) to reorder the variables of a given LP instance, resulting in reduced solving time. Fan et al. (2023) leveraged MPNNs to find good initial basis solutions for the Simplex algorithm. Finally Wu and Lisser (2023) expressed an LP as an ordinary differential equations system whose state solution converges to the LP's optimal solution and trained a feed-forward neural network to approximate this state solution. However, their approach hinges on the need to compute the Jacobian matrix, rendering its training phase computationally costly. ## 2 Background In the following, we describe the necessary background. **Notation** Let \(\mathbb{N}\coloneqq\{1,2,3,\dots\}\). For \(n\geq 1\), let \([n]\coloneqq\{1,\dots,n\}\subset\mathbb{N}\). We use \(\{\!\!\{\dots\}\!\}\) to denote multisets, i.e., the generalization of sets allowing for multiple instances for each of its elements. A _graph_\(G\) is a pair \((V(G),E(G))\) with _finite_ sets of _vertices_ or _nodes_\(V(G)\) and _edges_\(E(G)\subseteq\{\{u,v\}\subseteq V(G)\mid u\neq v\}\). For ease of notation, we denote the edge \(\{u,v\}\) in \(E(G)\) by \((u,v)\) or \((v,u)\). Throughout the paper, we use standard notation, e.g., we denote the _neighborhood_ of a node \(v\) by \(N(v)\), and so on; see Appendix A for details. Moreover, let \(\mathbf{x}\in\mathbb{R}^{1\times d}\), then \(\mathbf{D}(\mathbf{x})\) denotes the diagonal matrix with diagonal \(\mathbf{x}\), \(\mathbf{0}\) and \(\mathbf{1}\) denote the vector of zero and ones, respectively, with an appropriate number of entries. By default, a vector \(\mathbf{x}\in\mathbb{R}^{d}\) is a column vector. **Linear optimization problems** A _linear optimization problem_ (LP) aims at optimizing a linear function over a feasible set described as the intersection of finitely many half-spaces, i.e., a polyhedron. We restrict our attention to feasible and bounded LPs. Formally, an instance \(I\) of an LP is a tuple \((\mathbf{A},\mathbf{b},\mathbf{c})\), where \(\mathbf{A}\) is a matrix in \(\mathbb{Q}^{m\times n}\), and \(\mathbf{b}\) and \(\mathbf{c}\) are vectors in \(\mathbb{Q}^{m}\) and \(\mathbb{Q}^{n}\), respectively. We aim at finding a vector \(\mathbf{x}^{*}\) in \(\mathbb{Q}^{n}\) that minimizes \(\mathbf{c}^{\mathsf{T}}\mathbf{x}^{*}\) over the _feasible set_ \[F(I)=\{\mathbf{x}\in\mathbb{Q}^{n}\mid \mathbf{A}_{j}\mathbf{x}\leq b_{j}\text{ for }j\in[m]\text{ and } \tag{1}\] \[x_{i}\geq 0\text{ for }i\in[n]\}.\] In practice, LPs are solved using the Simplex method or polynomial-time IPMs (Nocedal and Wright, 2006). We now detail the theoretical result that motivates our approach. We first summarize both interior point methods for linear optimization and MPNNs and then prove a theorem that relates the two. **Interior-point methods for linear optimization** IPMs are algorithms for solving constrained optimization problems. They are particularly efficient for linear optimization, where they were first developed as a (polynomial-time) alternative to the Simplex methods. Variants of the algorithm differ in theoretical guarantees and empirical performance but revolve around the same core approach (Shanno, 2012). In short, the LP to solve is replaced by a perturbed family of problems where a barrier penalty has replaced hard constraints with a parameter \(\mu>0\). IPMs alternate between taking a Newton step to solve this perturbed problem and decreasing this parameter \(\mu>0\), eventually converging to the optimal solution of the original problem. For concreteness, we present two variants of the approach, an algorithm with theoretical guarantees and a practical algorithm that could be used in practice, following Nocedal and Wright (2006, Chapter 14) and Gondzio (2012), respectively. In the next section, we will show that both algorithms can be connected to MPNNs. The core idea of IPMs is as follows. First, we consider a perturbed version of the LP (1), \[\min_{\mathbf{x}\in\mathbb{Q}^{n}}\mathbf{c}^{\mathsf{T}}\mathbf{x}-\mu[\mathbf{1}^{\mathsf{T }}\log(\mathbf{A}\mathbf{x}-\mathbf{b})+\mathbf{1}^{\mathsf{T}}\log(\mathbf{x})] \tag{2}\] for some \(\mu>0\). By introducing the variables \(s_{i}=\mu/x_{i}\), \(r_{j}=\mathbf{A}_{j}x-b_{j}\) and \(w_{j}=\mu/r_{j}\), the first-order optimality conditions for (2) can be written as a system \[\mathbf{A}\mathbf{x}^{*}-\mathbf{r}^{*} =\mathbf{b}\] \[\mathbf{A}^{\mathsf{T}}\mathbf{w}^{*}+\mathbf{s}^{*} =\mathbf{c}\] \[x_{i}^{*}s_{i}^{*} =\mu i\in[n],\] \[w_{i}^{*}r_{i}^{*} =\mu j\in[m],\] with \(\mathbf{x}^{*},\mathbf{w}^{*},\mathbf{s}^{*},\mathbf{r}^{*}\geq\mathbf{0}\). Let \(\sigma\in(0,1)\) be another hyperparameter. The two algorithms start from an initial positive point \((\mathbf{x}_{0},\mathbf{w}_{0},\mathbf{s}_{0},\mathbf{r}_{0})>\mathbf{0}\), and alternate between computing the Newton step for the perturbed problem (2) at barrier parameter \(\sigma\mu\) \[\begin{bmatrix}\mathbf{A}&\mathbf{0}&\mathbf{0}&-\mathbf{I}\\ \mathbf{0}&\mathbf{A}^{\mathsf{T}}&\mathbf{I}&\mathbf{0}\\ \mathbf{D}(\mathbf{s})&\mathbf{0}&\mathbf{D}(\mathbf{x})&\mathbf{0}\\ \mathbf{0}&\mathbf{D}(\mathbf{r})&\mathbf{0}&\mathbf{D}(\mathbf{w})\end{bmatrix}\begin{bmatrix}\Delta \mathbf{x}\\ \Delta\mathbf{w}\\ \Delta\mathbf{s}\\ \Delta\mathbf{x}\end{bmatrix}=\begin{bmatrix}\mathbf{b}-\mathbf{A}\mathbf{x}+\mathbf{r}\\ \mathbf{c}-\mathbf{A}^{\mathsf{T}}\mathbf{w}-\mathbf{s}\\ \sigma\mu\mathbf{1}-\mathbf{D}(\mathbf{x})\mathbf{D}(\mathbf{s})\mathbf{1}\\ \sigma\mu\mathbf{1}-\mathbf{D}(\mathbf{w})\mathbf{D}(\mathbf{r})\mathbf{1}\end{bmatrix},\] and taking a step in that direction with length \(\alpha>0\), such that the resulting point satisfies \((\mathbf{x}^{\prime},\mathbf{w}^{\prime},\mathbf{s}^{\prime},\mathbf{r}^{\prime})>\mathbf{0}\). The above system can be simplified as follows. First, we can infer that \[\Delta\mathbf{s} =\sigma\mu\mathbf{D}(\mathbf{x})^{-1}\mathbf{1}-\mathbf{s}-\mathbf{D}(\mathbf{x})^{-1}\bm {D}(\mathbf{s})\Delta\mathbf{x}, \tag{3}\] \[\Delta\mathbf{r} =\sigma\mu\mathbf{D}(\mathbf{w})^{-1}\mathbf{1}-\mathbf{r}-\mathbf{D}(\mathbf{w})^{-1}\bm {D}(\mathbf{r})\Delta\mathbf{w}, \tag{4}\] Figure 1: Overview of our IPM-MPNN framework. which implies that \[\mathbf{A}\Delta\mathbf{x}+\mathbf{D}(\mathbf{w})^{-1}\mathbf{D}(\mathbf{r})\Delta\mathbf{w} =\mathbf{b}-\mathbf{A}\mathbf{x}+\sigma\mu\mathbf{D}(\mathbf{w})^{-1}\mathbf{1},\] \[\mathbf{A}^{\mathsf{T}}\Delta\mathbf{w}-\mathbf{D}(\mathbf{x})^{-1}\mathbf{D}(\mathbf{s}) \Delta\mathbf{x} =\mathbf{c}-\mathbf{A}^{\mathsf{T}}\mathbf{w}-\sigma\mu\mathbf{D}(\mathbf{x})^{-1}\mathbf{1}.\] Therefore, \(\Delta\mathbf{x}=\) \[\mathbf{D}(\mathbf{s})^{-1}\mathbf{D}(\mathbf{x})[\mathbf{A}^{\mathsf{T}}\Delta\mathbf{w} -\mathbf{c}+\mathbf{A}^{\mathsf{T}}\mathbf{w}+\sigma\mu\mathbf{D}(\mathbf{x})^{-1}\mathbf{1}] \tag{5}\] \[\mathbf{Q}\Delta\mathbf{w} =\mathbf{b}-\mathbf{A}\mathbf{x}+\sigma\mu\mathbf{D}(\mathbf{w})^{-1}1\] (6) \[+\mathbf{A}\mathbf{D}(\mathbf{s})^{-1}\mathbf{D}(\mathbf{x})[\mathbf{c}-\mathbf{A}^{\mathsf{ T}}\mathbf{w}-\sigma\mu\mathbf{D}(\mathbf{x})^{-1}\mathbf{1}]\] for \(\mathbf{Q}=\mathbf{A}\mathbf{D}(\mathbf{s})^{-1}\mathbf{D}(\mathbf{x})\mathbf{A}^{\mathsf{T}}+\mathbf{D}(\mathbf{ w})^{-1}\mathbf{D}(\mathbf{r})\). Thus, by solving the linear system in Equation (6), we can find \(\Delta\mathbf{w}\), then \(\Delta\mathbf{x}\), \(\Delta\mathbf{r}\), and \(\Delta\mathbf{s}\) through Equations (3)-(5). The two algorithms we consider only differ in how they compute \(\mu\) and \(\alpha\). The theoretical algorithm recomputes, at every iteration, \(\mu=(\mathbf{x}^{\mathsf{T}}\mathbf{s}+\mathbf{w}^{\mathsf{T}}\mathbf{r})/(n+m)\), and chooses \(\alpha\) to be the largest \(\alpha<1\) such that \(x_{i}^{\prime}s_{i}^{\prime}\geq\gamma(\mathbf{x}^{\mathsf{T}}\mathbf{s}^{\prime}+\bm {w}^{\mathsf{T}}\mathbf{r}^{\prime})/(n+m)\) and \(w_{i}^{\prime}r_{j}^{\prime}\geq\gamma(\mathbf{x}^{\mathsf{T}}\mathbf{s}^{\prime}+\bm {w}^{\mathsf{T}}\mathbf{r}^{\prime})/(n+m)\) for \(i\in[n]\) and \(j\in[m]\) for some hyperparameter \(\gamma\in(0,1]\)(Nocedal and Wright, 2006, Algorithm 14.2). The practical algorithm instead picks \(\mu_{0}=(\mathbf{x}_{0}^{\mathsf{T}}\mathbf{s}_{0}+\mathbf{w}_{0}^{\mathsf{T}}\mathbf{r}_{0}) /(n+m)\) initially, for \((\mathbf{x}_{0},\mathbf{w}_{0},\mathbf{s}_{0},\mathbf{r}_{0})\) the initial point, and thereafter decreases \(\mu\) as \(\mu^{\prime}=\sigma\mu\) at every iteration, while choosing \(\alpha\) to be \(\alpha=0.99\alpha^{\prime}\) for \(\alpha\) the largest \(\alpha>0\) such that \(x_{i}^{\prime}s_{i}^{\prime}>0\), \(w_{j}^{\prime}r_{j}^{\prime}>0\). The two algorithms are summarized in Algorithms 1 and 2. Algorithm 1 is guaranteed to converge to an \(\epsilon\)-accurate solution in \(\mathcal{O}((n+m)\log(1/\epsilon))\) iterations (Nocedal and Wright, 2006, Theorem 14.3), that is, to a number of iterations proportional to the problem size. Algorithm 2, in contrast, does not come with any theoretical guarantees but is typical of practical IPM algorithms, which tend to converge in an almost constant number of iterations--usually within 30-40 iterations, irrespective of problem size (Gondzio, 2012; Colombo and Gondzio, 2008). ``` 0: An LP instance \((\mathbf{A},\mathbf{b},\mathbf{c})\), a barrier reduction hyperparameter \(\sigma\in(0,1)\), a neighborhood hyperparameter \(\gamma\in(0,1]\) and initial values \((\mathbf{x}_{0},\mathbf{w}_{0},\mathbf{s}_{0},\mathbf{r}_{0})\) such that \(\mathbf{A}\mathbf{x}_{0}-\mathbf{r}_{0}=\mathbf{b}\), \(\mathbf{A}^{\mathsf{T}}\mathbf{w}_{0}+\mathbf{s}_{0}=\mathbf{c}\), \((\mathbf{x}_{0},\mathbf{w}_{0},\mathbf{s}_{0},\mathbf{r}_{0})>0\) and \(\min_{i}x_{0}w_{0i}\geq\gamma\mu_{0}\), \(\min_{i}w_{0i}r_{0i}\geq\gamma\mu_{0}\) for \(\mu_{0}=(\mathbf{x}_{0}^{\mathsf{T}}\mathbf{s}_{0}+(\mathbf{w}_{0}^{\mathsf{T}})_{0})/(n+m)\). 1:repeat 2:\(\mu\leftarrow(\mathbf{x}^{T}\mathbf{s}+\mathbf{w}^{\mathsf{T}}\mathbf{r})/(n+m)\) 3: Compute \(\Delta\mathbf{w}\) by solving the linear system \(\mathbf{Q}\Delta\mathbf{w}=\mathbf{b}-\mathbf{A}\mathbf{x}+\sigma\mu\mathbf{D}(\mathbf{w})^{-1}\mathbf{1}\) \(+\mathbf{A}\mathbf{D}(\mathbf{s})^{-1}\mathbf{D}(\mathbf{x})[\mathbf{c}-\mathbf{A}^{\mathsf{T}}\mathbf{w}- \sigma\mu\mathbf{D}(\mathbf{x})^{-1}\mathbf{1}]\) for \(\mathbf{Q}=\mathbf{A}\mathbf{D}(\mathbf{s})^{-1}\mathbf{D}(\mathbf{x})\mathbf{A}^{\mathsf{T}}+\mathbf{D}(\mathbf{w} )^{-1}\mathbf{D}(\mathbf{r})\) 4:\(\Delta\mathbf{x}\leftarrow\mathbf{D}(\mathbf{s})^{-1}\mathbf{D}(\mathbf{x})[\mathbf{A}^{\mathsf{T}} \Delta\mathbf{w}-\mathbf{c}+\mathbf{A}^{\mathsf{T}}\mathbf{w}+\sigma\mu\mathbf{D}(\mathbf{x})^{-1}\mathbf{1}]\) 5:\(\Delta\mathbf{s}\leftarrow\sigma\mu\mathbf{D}(\mathbf{x})^{-1}\mathbf{1}-\mathbf{s}-\mathbf{D}(\mathbf{x})^{ -1}\mathbf{D}(\mathbf{s})\Delta\mathbf{x}\) 6:\(\Delta\mathbf{r}\leftarrow\sigma\mu\mathbf{D}(\mathbf{w})^{-1}\mathbf{1}-\mathbf{r}-\mathbf{D}(\mathbf{w} )^{-1}\mathbf{D}(\mathbf{r})\Delta\mathbf{w}\) 7: Compute the largest \(\alpha\in(0,1)\) such that \[\min_{i,j}\{(\mathbf{x}+\alpha\Delta\mathbf{x})_{i}(\mathbf{s}+\alpha\Delta\mathbf{s})_{i},(\mathbf{w} +\alpha\Delta\mathbf{w})_{j}(\mathbf{r}+\alpha\Delta\mathbf{r})_{j}\}\] \[\geq\gamma\frac{(\mathbf{x}+\alpha\Delta\mathbf{x})^{\mathsf{T}}(\mathbf{s}+ \alpha\Delta\mathbf{s})+(\mathbf{w}+\alpha\Delta\mathbf{w})^{\mathsf{T}}(\mathbf{r}+\alpha \Delta\mathbf{r})}{n+m}.\] 8: Update \((\mathbf{x},\mathbf{w},\mathbf{s},\mathbf{r})\)\(+=\alpha(\Delta\mathbf{x},\Delta\mathbf{w},\Delta\mathbf{s},\Delta\mathbf{r})\) 9:until convergence of \((\mathbf{x},\mathbf{w},\mathbf{s},\mathbf{r})\) 10:return the point \(\mathbf{x}\), which solves 1. ``` **Algorithm 1** Theoretical IPM for LPs ``` 0: An LP instance \((\mathbf{A},\mathbf{b},\mathbf{c})\), a barrier reduction hyperparameter \(\sigma\in(0,1)\), a neighborhood hyperparameter \(\gamma\in(0,1]\) and initial values \((\mathbf{x}_{0},\mathbf{w}_{0},\mathbf{s}_{0},\mathbf{r}_{0})\) such that \((\mathbf{x}_{0},\mathbf{w}_{0},\mathbf{s}_{0},\mathbf{r}_{0})>0\) and \(\mu_{0}=(\mathbf{x}_{0}^{\mathsf{T}}\mathbf{s}_{0}+\mathbf{w}_{0}^{\mathsf{T}}\mathbf{r}_{0})/(n+m)\). 1:repeat 2: Compute \(\Delta\mathbf{w}\) by solving the linear system \(\mathbf{Q}\Delta\mathbf{w}=\mathbf{b}-\mathbf{A}\mathbf{x}+\sigma\mu\mathbf{D}(\mathbf{w})^{-1}\mathbf{1}\) \(+\mathbf{A}\mathbf{D}(\mathbf{s})^{-1}\mathbf{D}(\mathbf{x})[\mathbf{c}-\mathbf{A}^{\mathsf{T}}\mathbf{w}- \sigma\mu\mathbf{D}(\mathbf{x})^{-1}\mathbf{1}]\) for \(\mathbf{Q}=\mathbf{A}\mathbf{D}(\mathbf{s})^{-1}\mathbf{D}(\mathbf{x})\mathbf{A}^{\mathsf{T}}+\mathbf{D}(\mathbf{w})^{ -1}\mathbf{D}(\mathbf{r})\). 3:\(\Delta\mathbf{x}\leftarrow\mathbf{D}(\mathbf{s})^{-1}\mathbf{D}(\mathbf{x})[\mathbf{A}^{\mathsf{T}} \Delta\mathbf{w}-\mathbf{c}+\mathbf{A}^{\mathsf{T}}\mathbf{w}+\sigma\mu\mathbf{D}(\mathbf{x})^{-1}\mathbf{1}]\) 4:\(\Delta\mathbf{s}\leftarrow\sigma\mu\mathbf{D}(\mathbf{x})^{-1}\mathbf{1}-\mathbf{s}-\mathbf{D}(\mathbf{x})^{ -1}\mathbf{D}(\mathbf{s})\Delta\mathbf{x}\) 5:\ features, and the output of \(\mathsf{MSG}^{(t)}\) to a single vectorial representation. To adapt the parameters of the above functions, they are optimized end-to-end, usually through a variant of stochastic gradient descent, e.g., Kingma and Ba (2015), together with the parameters of a neural network used for classification or regression. In the following, we define a _message-passing step_ as the application of a message and update function. ## 3 Simulating IPMs via MPNNs We now show that there exist MPNNs, with specific architecture and choices of parameters, such that Algorithms 1 and 2 can be interpreted as inference over these MPNNs for a specific tripartite graph encoding the LP as input. **Representing LPs as graphs** Let \(I=(\mathbf{A},\mathbf{b},\mathbf{c})\) be an instance of LP. Similar to the setting of Ding et al. (2020), we model the instances with an (undirected) _weighted tripartite graph_\(G(I):=(V(I),C(I),\{o\},E(I)_{\mathrm{vc}},E(I)_{\mathrm{vo}},E(I)_{\mathrm{ co}})\). Here, the node set \(V(I):=\{v_{i}\mid i\in[n]\}\) represents the variables of \(I\), the node set \(C(I):=\{c_{i}\mid i\in[m]\}\) represents the constraints of \(I\), and the node \(o\) represents the objective. Further, the first edge set \(E(I)_{\mathrm{vc}}\) models the variable-constraint interaction, i.e., \(E(I)_{\mathrm{vc}}:=\{(v_{i},c_{j})\mid A_{ij}\neq 0\}\), where each such edge \((v_{i},c_{j})\) is annotated with the weight \(A_{ij}\). Further, the objective node \(o\) is connected to all other nodes in the graphs, i.e., \(E(I)_{\mathrm{vo}}:=\{(o,v_{i})\mid v_{i}\in V(I)\}\) and \(E(I)_{\mathrm{co}}:=\{(o,c_{i})\mid c_{i}\in C(I)\}\). Each edge \((o,v_{i})\in E(I)_{\mathrm{vo}}\) is annotated with the weight \(c_{i}\). Similarly, each edge \((o,c_{i})\in E(I)_{\mathrm{co}}\) is annotated with the weight \(b_{i}\). The resulting graph is illustrated in Figure 0(a). **Theoretical results** We now state the main results of this paper. To describe them, first notice that Algorithms 1 and 2 operate by taking an initial point \((\mathbf{x}_{0},\mathbf{w}_{0},\mathbf{s}_{0},\mathbf{r}_{0})\) and a duality measure \(\mu_{0}\), and updating them after every iteration, yielding a sequence of points \((\mathbf{x}_{t},\mathbf{w}_{t},\mathbf{s}_{t},\mathbf{r}_{t})\) and duality measure \(\mu_{t}\) for iterations \(t>0\). The following result shows that Algorithm 1 can be reproduced by a specific MPNN, in the sense that a fixed-depth MPNN can reproduce each of its iterations. **Theorem 1**.: There exists an MPNN \(f_{\mathsf{MPNN},\mathsf{IPM1}}\) composed of \(\mathcal{O}(m)\) message-passing steps that reproduces an iteration of Algorithm 1, in the sense that for any LP instance \(I=(\mathbf{A},\mathbf{b},\mathbf{c})\) and any iteration step \(f_{\mathsf{MPNN},\mathsf{IPM1}}\) maps the graph \(G(I)\) carrying \([\mathbf{x}_{t},\mathbf{s}_{t}]\) on the variable nodes and \([\mathbf{w}_{t},\mathbf{r}_{t}]\) on the constraint nodes on the variable nodes, \([\mathbf{w}_{t+1},\mathbf{s}_{t+1}]\) on the constraint nodes. This implies, by composing several instances of \(f_{\mathsf{MPNN},\mathsf{IPM1}}\), that Algorithm 1 can be simulated by an MPNN with a number of layers proportional to the number of iterations taken by the algorithm. **Proposition 2**.: There exists an MPNN \(f_{\mathsf{MPNN},\mathsf{IPM2}}\) composed of \(\mathcal{O}(m)\) message-passing steps that reproduces each iteration of Algorithm 2, in the sense that for any LP instance \(I=(\mathbf{A},\mathbf{b},\mathbf{c})\) and any iteration step \(t\geq 0\), \(f_{\mathsf{MPNN},\mathsf{IPM2}}\) maps the graph \(G(I)\) carrying \([\mathbf{x}_{t},\mathbf{s}_{t}]\) on the variable nodes, \([\mathbf{w}_{t},\mathbf{r}_{t}]\) on the constraint nodes and \([\mu_{t}]\) on the objective node to the same graph \(G(I)\) carrying \([\mathbf{x}_{t+1},\mathbf{s}_{t+1}]\) on the variable nodes, \([\mathbf{w}_{t+1},\mathbf{r}_{t+1}]\) on the constraint nodes and \([\mu_{t+1}]\) on the objective node. Similarly, this implies, by composing several instances of \(f_{\mathsf{MPNN},\mathsf{IPM2}}\), that Algorithm 2 can be simulated by an MPNN with a number of layers proportional to the number of iterations taken by the algorithm. **Implication of the theoretical results** Theorem 1 and Proposition 2 show that MPNNs are, in principle, capable of simulating modern IPMs. That is, they are capable of solving LPs to optimality. Hence, our findings shed light on the recent success of MPNN-based neural architectures by Gasse et al. (2019) and similar approaches, which use MPNNs to mimic strong branching within the branch-and-bound framework for solving mixed-integer linear optimization problems. Moreover, in the following section, we derive MPNN architectures that act as lightweight proxies for solving LPs while being able to adapt to the given problem instance distributions. We verify their effectiveness empirically on real-world LP instances stemming from relaxing mixed-integer linear formulations of well-known combinatorial optimization problems. ## 4 IPM-MPNNs: MPNNs FOR LPs Inspired by the theoretical alignment of IPMs and MPNNs derived above, we outline our IPM-MPNN framework, allowing for solving LP instances while adapting to a given problem instance distribution. Given an LP instance \(I\), we now outline an asynchronous MPNN operating on the tripartite graph \(G(I)\); see Section 3. Let \(\mathbf{h}_{c}^{(t)}\in\mathbb{R}^{d}\), \(d>0\), be the node features of a constraint node \(c\in C(I)\) at iteration \(t>0\), and let \(\mathbf{h}_{v}^{(t)}\in\mathbb{R}^{d}\) and \(\mathbf{h}_{v}^{(t)}\in\mathbb{R}^{d}\) be the node features of a variable node \(v\in V(I)\) and the objective node \(o\) at iteration \(t\), respectively. Moreover, let \(\mathbf{e}_{co},\mathbf{e}_{vc},\mathbf{e}_{vo}\) denote the edge weights. Initially, at \(t=0\), we set the node features by applying a linear mapping to the raw node features \(\mathbf{x}_{v}\), \(\mathbf{x}_{c}\) or \(\mathbf{x}_{o}\), extracted from the instance \(I\); see Section 5 for details. All three node types are updated in three separate update passes. In the first pass, we update the embeddings of constraint nodes from the embeddings of the variable nodes and of the objective node. That is, let \(c\in C(I)\) be a constraint node and let \(t>0\), then \[\mathbf{h}_{c}^{(t)}\coloneqq \mathsf{UPD}_{c}^{(t)}\Big{[}\mathbf{h}_{c}^{(t-1)},\mathsf{MSG}_{ \textnormal{o}\to\textnormal{c}}^{(t)}\Big{(}\mathbf{h}_{o}^{(t-1)},\mathbf{e}_{oc} \Big{)},\] \[\mathsf{MSG}_{\textnormal{v}\to\textnormal{c}}^{(t)}\Big{(} \big{\{}\!\{\mathbf{h}_{v}^{(t-1)},\mathbf{e}_{vc}\}\mid v\in N(c)\cap V(I)\!\}\Big{)} \Big{]}.\] Here, the parameterized message function \(\mathsf{MSG}_{\textnormal{v}\to\textnormal{c}}^{(t)}\) maps a multiset of vectors, i.e., variable node features and corresponding edge features \(\mathbf{e}_{vc}\), to a vector in \(\mathbb{R}^{d}\). Similarly, the parameterized function \(\mathsf{MSG}_{\textnormal{o}\to\textnormal{c}}\) maps the current node features of the objective node and edge features \(\mathbf{e}_{oc}\) to a vector in \(\mathbb{R}^{d}\). Finally, the parameterized function \(\mathsf{UPD}_{c}^{(t)}\) maps the constraint node's previous features, the outputs of \(\mathsf{MSG}_{\textnormal{o}\to\textnormal{c}}^{(t)}\) and \(\mathsf{MSG}_{\textnormal{v}\to\textnormal{c}}^{(t)}\) to vector in \(\mathbb{R}^{d}\). Next, similarly to the above, we update the objective node's features depending on variable and constraint node features, \[\mathbf{h}_{\textnormal{o}}^{(t)}\coloneqq \mathsf{UPD}_{\textnormal{o}}^{(t)}\Big{[}\mathbf{h}_{o}^{(t-1)}, \mathsf{MSG}_{\textnormal{c}\to\textnormal{o}}^{(t)}\Big{(}\big{\{}\!\{\mathbf{h} _{c}^{(t)},\mathbf{e}_{co}\mid c\in C(I)\!\}\Big{)}\!\Big{\}},\] \[\mathsf{MSG}_{\textnormal{v}\to\textnormal{o}}^{(t)}\Big{(}\big{\{} \!\{\mathbf{h}_{v}^{(t-1)},\mathbf{e}_{vo}\mid v\in V(I)\!\}\Big{)}\Big{]}.\] Finally, analogously to the update of the constraint nodes' features, we update the representation of a variable node \(v\in V(I)\) from the constraints nodes and objective node, \[\mathbf{h}_{v}^{(t)}\coloneqq \mathsf{UPD}_{\textnormal{v}}^{(t)}\Big{[}\mathbf{h}_{v}^{(t-1)}, \mathsf{MSG}_{\textnormal{o}\to\textnormal{v}}^{(t)}\Big{(}\mathbf{h}_{o}^{(t)}, \mathbf{e}_{ov}\Big{)},\] \[\mathsf{MSG}_{\textnormal{c}\to\textnormal{v}}^{(t)}\Big{(} \big{\{}\!\{\mathbf{h}_{c}^{(t)},\mathbf{e}_{cv}\mid c\in N(v)\cap V(C)\!\}\big{\}} \Big{)}\Big{]}.\] The entire process is executed asynchronously, in that the nodes updated later incorporate the most recent features updates from preceding nodes. We map each variable node feature \(\mathbf{h}_{v}^{(t)}\) to \(\mathsf{MLP}(\mathbf{h}_{v}^{(t)})\in\mathbb{R}\), where \(\mathsf{MLP}\) is a multi-layer perceptron, and concatenate the resulting real numbers over all variable nodes column-wise, resulting in the final prediction \(\mathbf{z}^{(t)}\in\mathbb{R}^{n}\). In the experiments in Section 5, we probe various message-passing layers to express the various message and update functions. Concretely, we leverage the GCN (Kipf and Welling, 2017), GIN (Xu et al., 2019), and GEN (Li et al., 2020) MPNN layers, respectively; see Appendix C for details. We train the above IPM-MPNN architecture, i.e., adapt its parameters, in a supervised fashion. Below, we outline the three components constituting our training loss function. To that, let \((\mathbf{A},\mathbf{b},\mathbf{c})\) be an LP instance. **Variable supervision** As discussed above, our IPM-MPNN aims to simulate the solving steps provided by a standard IPM. Thus, aligned with Theorem 1 and Proposition 2, a perfectly parameterized MPNN is expected to follow the steps without deviation for all \(T\) iterations. We maintain the intermediate outputs \(\mathbf{z}^{(t)}\in\mathbb{R}^{n}\) of each MPNN layer and calculate the mean squared error (MSE) loss between every pair of the expert solution \(\mathbf{y}^{(t)}\in\mathbb{R}^{n}\) and MPNN prediction \(\mathbf{z}^{(t)}\). Moreover, we introduce a step decay factor \(\alpha\in[0,1]\) so that early steps play a less important role, resulting in the following loss function, \[\mathcal{L}_{\textnormal{var}}\coloneqq\frac{1}{N}\sum_{i=1}^{N} \sum_{t=1}^{T}\alpha^{T-t}\|\mathbf{y}_{i}^{(t)}-\mathbf{z}_{i}^{(t)}\|_{2}^{2}, \tag{7}\] where \(N\) denotes the number of training samples. **Objective supervision** We use regularization on the prediction regarding the ground-truth objective values at every step. Empirically, this regularization term helps with convergence and helps finding more feasible solutions that minimize the objective in case the LP instance has multiple solutions. Note that we do not predict the objective directly with our MPNNs but calculate it via \(\mathbf{c}^{\mathsf{T}}\mathbf{z}^{(t)}\) instead. Suppose the ground-truth values are given by \(\mathbf{c}^{\mathsf{T}}\mathbf{y}^{(t)}\), we have \[\mathcal{L}_{\textnormal{obj}}\coloneqq\frac{1}{N}\sum_{i=1}^{N} \sum_{t=1}^{T}\alpha^{T-t}\Big{[}\mathbf{c}^{\mathsf{T}}\big{(}\mathbf{y}_{i}^{(t)}- \mathbf{z}_{i}^{(t)}\big{)}\Big{]}^{2}. \tag{8}\] **Constraint supervision** Finally, we aim for the IPM-MPNN to predict an optimal solution regarding the objective value while satisfying all the constraints. To that, we introduce a regularization penalizing constraint violations, i.e., \[\mathcal{L}_{\textnormal{cons}}\coloneqq\frac{1}{N}\sum_{i=1}^{N} \sum_{t=1}^{T}\alpha^{T-t}\|\mathsf{ReLU}(\mathbf{A}_{i}\mathbf{z}_{i}^{(t)}-\mathbf{b}_{i} )\|_{2}^{2}. \tag{9}\] Finally, we combine the above three loss terms into the loss function \[\mathcal{L}\coloneqq w_{\textnormal{var}}\mathcal{L}_{\textnormal{var}}+w_{ \textnormal{obj}}\mathcal{L}_{\textnormal{obj}}+w_{\textnormal{cons}}\mathcal{L }_{\textnormal{cons}}, \tag{10}\] where we treat \(w_{\textnormal{var}},w_{\textnormal{obj}}\), and \(w_{\textnormal{cons}}>0\) as hyperparamters. At test time, given an LP instance \(I\), we construct the tripartite graph \(G(I)\) as outlined above and use the trained MPNN to predict the variables' values. ## 5 Experimental Study Here, we empirically evaluate the ability of IPM-MPNNs to predict the optimal solutions of LPs. In particular, we aim to answer the following questions. **Q1** Can MPNNs properly imitate the performance of IPM solvers in practice? **Q2** How is MPNNs' performance compared with competing neural-network-based solutions? **Q3** What advantage does our MPNN architecture hold compared with traditional IPM solvers? **Q4** Do MPNNs generalize to instances larger than seen during training? Our experimental results are reproducible with the code available at [https://github.com/chendiqian/IPM_MPNN](https://github.com/chendiqian/IPM_MPNN). **Datasets** We obtain LP instances from mixed-integer optimization instances by dropping the integrality constraints over variables. Following Gasse et al. (2019), we use four classes of problems, namely _set covering_, _maximal independent set_, _combinatorial auction_, and _capacitated facility location_. For each problem type, we generate small- and large-size instances. We describe the datasets and our parameters for dataset generation in Appendix D. From each LP instance \(I=(\mathbf{A},\mathbf{b},\mathbf{c})\), we generate a tripartite graph \(G(I)\), following Section 3, and construct initial node and edge features as follows. We indicate the \(i\)th row of the constraint matrix \(\mathbf{A}\) as \(\mathbf{A}_{i}\) and the \(j\)th column as \(\mathbf{A}_{\cdot,j}\). For a given variable node \(v_{j}\in V(I)\), its initial node features are set to the mean and standard deviation of the column vector \(\mathbf{A}_{\cdot,j}\), resulting in two features. Analogously, for a constraint node \(c_{i}\in C(I)\), we derive initial features from the statistical properties of the row vector \(\mathbf{A}_{i}\). For the objective node \(o\), the features are characterized in a corresponding manner using the vector \(\mathbf{c}\). In the supervised learning regime, it is mandatory to have ground truth labels to guide the model predictions. For our IPM-MPNNs, the outputs of each layer \(t\) are the prediction of the variables' value \(\mathbf{z}^{(t)}\). Consequently, we utilize the intermediate variable values \(\mathbf{y}^{(t)}\), as provided by the solver, to serve as our ground truth. However, to prevent the MPNN from becoming excessively deep, we sample the ground truth steps, i.e., we adopt an equidistant sampling strategy for the solver's steps, ensuring that the number of sampled steps aligns with the depth of the corresponding MPNN. We split the graph datasets into train, validation, and test splits with ratios \(0.8,0.1\), and \(0.1\). We conducted the experiments by evaluating each dataset multiple times, performing three independent runs with distinct random seeds. The reported results represent the average numbers over the test set across these runs and the corresponding standard deviations. We executed all experiments on a single NVIDIA A100 80GB GPU card--see Appendix E for training-related hyperparameters. **IPM-MPNNs' ability to solve LPs (Q1)** We collect and organize the results of our MPNN method in Table 1. We report the numbers on the four types of relaxed MILP instances, each with small and large sizes. As explained in Section 4, we leverage three types of MPNN layers, GCN (Kipf and Welling, 2017), GIN (Xu et al., 2019), and GEN (Li et al., 2020), as the backbone of our MPNN architectures. We split the table into two main parts, namely the mean absolute relative objective gap \[\frac{1}{N}\sum_{i=1}^{N}\left|\frac{\mathbf{c}^{\mathsf{T}}\big{(}\mathbf{y}_{i}^{(T )}-\mathbf{z}_{i}^{(T)}\big{)}}{\mathbf{c}^{\mathsf{T}}\mathbf{y}_{i}^{(T)}}\right| \times 100\] of the last step \(T\) over the test set, and the mean absolute constraint violation of the last step \[\frac{1}{N}\sum_{i=1}^{N}\frac{1}{m_{i}}\|\mathsf{reLU}(\mathbf{A}_{i}\mathbf{z}_{i}^ {(T)}-\mathbf{b}_{i})\|_{1},\] where the normalization term \(m_{i}\) is the number of constraints of the \(i\)th instance. As seen, our IPM-MPNN architectures consistently align with the IPM solver \begin{table} \begin{tabular}{c c c c c c c c c c} \hline \hline \multicolumn{2}{c}{} & \multirow{2}{*}{Th.} & \multirow{2}{*}{MPNN} & \multicolumn{2}{c}{**Small instances**} & \multicolumn{4}{c}{**Large instances**} \\ \cline{4-10} \multicolumn{1}{c}{} & & & \multicolumn{2}{c}{**Index**} & \multicolumn{2}{c}{**Case**} & \multicolumn{2}{c}{**Face**} & \multicolumn{2}{c}{**Index**} & \multicolumn{2}{c}{**Case**} & \multicolumn{2}{c}{**Face**} \\ \hline \multirow{4}{*}{**PNN**} & \multirow{4}{*}{✓} & GEN & **0.319\(\pm\)0.020** & 0.119\(\pm\)0.000 & **0.612\(\pm\)0.049** & **0.549\(\pm\)0.121** & 0.629\(\pm\)0.048 & 0.158\(\pm\)0.033 & **0.306\(\pm\)0.047** & **0.747\(\pm\)0.038** \\ & & GCN & 0.418\(\pm\)0.008 & **0.103\(\pm\)0.006** & 0.682\(\pm\)0.029 & 0.578\(\pm\)0.015 & **0.420\(\pm\)0.047** & **0.049\(\pm\)0.005** & 0.407\(\pm\)0.038 & 0.914\(\pm\)0.141 \\ & & GIN & 0.478\(\pm\)0.038 & 0.146\(\pm\)0.011 & 0.632\(\pm\)0.036 & 0.810\(\pm\)0.227 & 0.711\(\pm\)0.15 & 0.126\(\pm\)0.027 & 0.378\(\pm\)0.052 & 0.911\(\pm\)0.127 \\ \cline{2-10} & & GEN & 8.310\(\pm\)1.209 & 0.735\(\pm\)0.022 & 1.417\(\pm\)0.029 & 2.976\(\pm\)0.013 & 1.517\(\pm\)0.541 & 0.320\(\pm\)0.008 & 0.51\(\pm\)0.122 & 2.531\(\pm\)0.025 \\ & & \multirow{2}{*}{✓} & GEN & 5.523\(\pm\)0.133 & 0.639\(\pm\)0.000 & 1.350\(\pm\)0.001 & 3.031\(\pm\)0.003 & 6.092\(\pm\)0.044 & 0.298\(\pm\)0.000 & 0.766\(\pm\)0.003 & 2.535\(\pm\)0.034 \\ & & GIN & 5.592\(\pm\)0.1179 & 0.634\(\pm\)0.012 & 1.202\(\pm\)0.146 & 2.996\(\pm\)0.031 & 5.835\(\pm\)1.177 & 2.909\(\pm\)0.006 & 0.810\(\pm\)0.140 & 2.660\(\pm\)0.002 \\ \hline \multirow{4}{*}{**PNN**} & \multirow{4}{*}{✓} & GEN & **0.002\(\pm\)0.0002** & 0.000\(\pm\)0.0000 & 0.003\(\pm\)0.0002 & 0.002\(\pm\)0.001 & 0.009\(\pm\)0.001 & 0.001\(\pm\)0.003 & **0.0004\(\pm\)0.0002** & 0.002\(\pm\)0.001 \\ & & \multirow{2}{*}{✓} & GCN & 0.002\(\pm\)0.001 & **0.0003\(\pm\)0.0001** & 0.002\(\pm\)0.0007 & **0.002\(\pm\)0.000** & 0.001\(\pm\)0.000 & **0.0005\(\pm\)0.0004** & 0.001\(\pm\)0.0005 & **0.001\(\pm\)0.0004** \\ & & \multirow{2}{*}{✓} & GCN & 0.004\(\pm\)0.001 & 0.000\(\pm\)0.0001 & 0.001\(\pm\)0.001 & 0.002\(\pm\)0.000 & **0.0008\(\pm\)0.002** & 0.001\(\pm\)0.001 & 0.002\(\pm\)0.0008 & 0.002\(\pm\)0.007 \\ \cline{1-1} \cline{2-10} & & GEN & 0.181\(\pm\)0.032 & 0.006\(\pm\)0.0003 & 0.006\(\pm\)0.001 & 0.011\(\pm\)0.004 & 0.309\(\pm\)0.022 & 0.004\(\pm\)0.0002 & 0.006\(\pm\)0.001 & 0.003\(\pm\)0.001 \\ \cline{1-1} \cline{2-10} & & \multirow{2}{*}{✓} & GCN & 0.207\(\pm\)0.006 & 0.004\(\pm\)0.001 & 0.002\(\pm\)0.01 & 0.006\(\pm\)0.001 & 0.267\(\pm\)0.090 & 0.033\(\pm\)0.0004 & 0.004\(\pm\)0.001 & 0.002\(\pm\)0.0003 \\ \cline{1-1} & & \multirow{2}{*}{✓} & GEN & 0.211\(\pm\)0.0007 & 0.003\(\pm\)0.0002 & 0.003\(\pm\)0.001 & 0.008\(\pm\)0.002 & 0.236\(\pm\)0.014 & 0.033\(\pm\)0.0004 at the last converged step, with marginal constraint violation. Moreover, the relative objective gaps of our method are all under 1%. The GCN-based IPM-MPNNs perform best on large maximal independent set relaxation instances at \(0.094\pm 0.005\%\). Overall, GEN and GCN perform better than GIN layers among the three graph convolutions. The absolute constraint violations are mostly at the \(1\times 10^{-3}\) level, with the best \((0.0003\pm 0.0001)\) achieved by GCN on small maximal independent set relaxation instances. **Baselines (Q2)** To answer question **Q2**, we compare IPM-MPNNs to two baselines. First, we compare our IPM-MPNNs to Chen et al. (2023), where the authors proposed encoding LP instances as bipartite graphs. In Table 1, the rows with a cross mark (\(\mathbf{\mathcal{X}}\)) on the left are the bipartite baselines. As seen in this table, our IPM-MPNNs outperform the bipartite architectures in all instances with all types of MPNNs. Most relative objective gaps lie above 1%, except on the maximal independent set and large combinatorial auction relaxation instances. The largest gap is observed on the small set covering relaxation instances by GEN, with the baseline reporting as much as 26.1\(\times\) higher constraint violation number. Hence, our results indicate that IPM-MPNNs's tripartite representation is crucial. We also compare our IPM-MPNNs to a neural-ODE-based approach Wu and Lisser (2023). Since their approach is quite expensive during training by means of both time and GPU memory, we generate 1000 mini-sized instances. Due to the architecture-agnostic property of their approach, we embed our MPNNs in their training pipeline. When presenting the runtime and GPU usage, we use the same batch size as the baseline method on our MPNN approach for a fair comparison, even though our method can scale to a much larger batch size in practice. We report results in Table 2. Taking the GEN layer as an example, our method shows consistently better results than the neural-ODE baseline method by reaching at most 14.2\(\times\) lower relative objective gap, 8.6\(\times\) faster training, and 300.8\(\times\) less memory on the mini-sized capacitated facility location relaxation instances. **Inference time profiling (Q3)** We also compare IPM-MPNN's performance to exact IPM solvers. Thereto, we compare the time required to solve an instance between traditional solvers, namely SciPy's IPM solver and a Python-based custom-build one, and our IPM-MPNN. We run the solvers and our MPNNs on the test set of each dataset and report the mean and standard deviation in seconds. According to Table 3, our MPNN clearly outperforms the SciPy IPM solver on all large instances. Further, IPM-MPNNs beat our Python-based IPM solver described in Algorithm 2 on all instances. It is worth noting that both IPM solvers exhibit sensitivity to problem sizes. For example, the SciPy solver sees a performance degradation of approximately 65.0\(\times\) when transitioning from small to large set covering problems. In contrast, our MPNN method demonstrates a more consistent behavior across varying problem sizes, showing only 1.2\(\times\) slowdown for the analogous instances. Hence, we can positively answer question **Q3**. **Size generalization (Q4)** We investigate the possibility of generalizing our pre-trained MPNNs to larger instances than encountered during training. To that, we generate new sets of novel instances, each with the same number of instances as the test set. In Table 11 in the appendix, we list our training instance sizes and a collection of test instance sizes. Taking GEN on set covering relaxation problems as an example, as the in \begin{table} \begin{tabular}{l l l l l l l} \hline \hline \multicolumn{2}{c}{**Instances**} & SciPy Slower & Our Slower & GEN & GCN & GCN \\ \hline \multirow{4}{*}{\begin{tabular}{l} Small network \\ Large network \\ \end{tabular} } & \multirow{4}{*}{\begin{tabular}{l} ODE \\ \end{tabular} } & GEN & 14.91\(\pm\)0.003 & 6.22\(\pm\)0.007 & 12.35\(\pm\)0.004 & 20.000\(\pm\)0.009 \\ & & GEN & 14.95\(\pm\)0.005 & 6.71\(\pm\)0.005 & 12.94\(\pm\)0.005 & 20.000\(\pm\)0.002 \\ & & GEN & 15.00\(\pm\)0.005 & 6.74\(\pm\)0.004 & 13.74\(\pm\)0.004 & 21.00\(\pm\)0.009 \\ & & GEN & 25.25\(\pm\)0.005 & 1.47\(\pm\)0.005 & 27.90\(\pm\)0.004 & 1.478\(\pm\)0.005 \\ & & GEN & 27.94\(\pm\)0.005 & 1.47\(\pm\)0.005 & 27.60\(\pm\)0.004 & 1.278\(\pm\)0.004 \\ \hline \multirow{4}{*}{\begin{tabular}{l} Small network \\ \end{tabular} } & \multirow{4}{*}{\begin{tabular}{l} ODE \\ \end{tabular} } & GEN & 007.20\(\pm\)0.006 & 0.08\(\pm\)0.005 & 0.09\(\pm\)0.004 & 0.09\(\pm\)0.001 \\ & & GEN & 00.04\(\pm\)0.005 & 0.08\(\pm\)0.005 & 0.09\(\pm\)0.000 & 0.09\(\pm\)0.006 \\ & & GEN & 00.04\(\pm\)0.005 & 0.04\(\pm\)0.005 & 0.09\(\pm\)0.000 & 0.09\(\pm\)0.006 \\ & & GEN & 00.04\(\pm\)0.005 & 0.04\(\pm\)0.005 & 0.09\(\pm\)0.000 & 0.09\(\pm\)0.006 \\ \hline \multirow{4}{*}{\begin{tabular}{l} Small network \\ \end{tabular} } & \multirow{4}{*}{\begin{tabular}{l} Ours \\ \end{tabular} } & GEN & **00.023\(\pm\)0.000** & 0.05\(\pm\)0.000 & 0.01\(\pm\)0.005 & 0.01\(\pm\)0.003 \\ & & GEN & 00.04\(\pm\)0.000 & 0.003\(\pm\)0.000 & 0.09\(\pm\)0.006 & 0.09\(\pm\)0.006 \\ & & GEN & 00.02\(\pm\)0.005 & **0.005\(\pm\)0.000** & **0.014\(\pm\)0.002** & **0.006\(\pm\)0.000** \\ \hline \multirow{4}{*}{\begin{tabular}{l} Small network \\ \end{tabular} } & \multirow{4}{*}{\begin{tabular}{l} ODE \\ \end{tabular} } & GEN & 47.20\(\pm\)0.005 & 51.25\(\pm\)0.003 & 63.00\(\pm\)0.006 & 96.258 \\ & & GEN & 57.19\(\pm\)0.005 & 80.13\(\pm\)0.006 & 73.29\(\pm\)0.006 & 32.297 \\ & & GEN & 55.91\(\pm\)0.005 & 64.028 & 32.90\(\pm\)0.001 & 62.488 \\ \cline{1-1} \cline{2-6} & & GEN & 10.11\(\pm\)0.077 & 9.617 & 9.366 & 11.21\(\pm\)0.006 \\ & & GEN & 18.94\(\pm\)0.04 & 6.688 & **7.268** & **8.344** \\ \cline{1-1} & & GEN & **0.042** & **8.005** & 5.817 & 10.771 \\ \hline \multirow{4}{*}{\begin{tabular}{l} Small network \\ \end{tabular} } & \multirow{4}{*}{ \begin{tabular}{l} ODE \\ \end{tabular} } & GEN & 14.65\(\pm\)0.05 & 25.911 & 23.354 & 14.520 \\ & & GEN & 14.469\(\pm\)0.005 & 34.001 & 23.862 & 10.680 \\ & & GEN & 15.289\(\pm\)0.005 & 30.101 & 13.462 & 22.713 \\ \cline{1-1} \cline{2-6} & & GEN & **0.091** & 0.088 & 0.01 & 0.148 \\ \cline{1-1} \cline{2-6} & & GEN & 0.201 & 0.131 & **0.090** & **0.142** \\ \cline{1-1} \cline{2-6} & & GEN & **0.071** & **0.073** & 0.148 & 0.157 \\ \hline \hline \end{tabular} \end{table} Table 3: Comparing IPM-MPNNs’ inference time to SciPy’s IPM implementation and our Python-based IPM solver. We report mean and standard deviation in seconds over three runs. We print the best results per target in bold. ference size grows, the relative objective gap increases a bit, while the constraint violations are overall worse than on the training set. Notably, for the training size [600,800], which is at least \(1.37\times\) larger than the training instances, the objective gap is merely \(0.28\%\) worse than [500,700] size. For question **Q4**, we can conclude that our pre-trained MPNNs can generalize to unseen, larger instances to some extent. ## 6 Conclusion In summary, our study establishes a strong connection between (MPNNs and IPMs for LPs. We have shown that MPNNs can effectively simulate IPM iterations, revealing their potential in emulating strong branching within the branch-and-bound framework, as demonstrated by Gasse et al. (2019). In addition, building on this connection, we proposed IPM-MPNNs for learning to solve large-scale LP instances approximately, surpassing neural baselines and exact IPM solvers in terms of solving time across various problem domains. Looking forward, promising avenues for further research involve expanding our theoretical framework to encompass a broader range of convex optimization problems. #### Acknowledgments CQ and CM are partially funded by a DFG Emmy Noether grant (468502433) and RWTH Junior Principal Investigator Fellowship under Germany's Excellence Strategy.
2302.09143
An Application of Pontryagin Neural Networks to Solve Optimal Quantum Control Problems
Reliable high-fidelity quantum state transformation has always been considered as an inseparable part of quantum information processing. In this regard, Pontryagin maximum principle has proved to play an important role to achieve the maximum fidelity in an optimum time or energy. Motivated by this, in this work, we formulate a control constrained optimal control problem where we aim to minimize time and also energy subjected to a quantum system satisfying the bilinear Schrodinger equation. We derive the first order optimality conditions through the application of Pontryagin Maximum (minimum) Principle, which results in a boundary value problem. Next, in order to obtain efficient numerical results, we exploit a particular family of physics-informed neural networks that are specifically designed to tackle the indirect method based on the Maximum Principle of Pontryagin. This method has not yet been studied in the quantum context, but it can significantly speed up the process. To this end, we first obtain a set of relations which finally let us compute the optimal control strategy to determine the time- and energy-optimal protocol driving a general initial state to a target state by a quantum Hamiltonian with bounded control. We make use of the so-called "qutip" package in python, and the newly developed "tfc" python package.
Nahid Binandeh Dehaghani, A. Pedro Aguiar
2023-02-01T17:48:07Z
http://arxiv.org/abs/2302.09143v1
# An Application of Pontryagin Neural Networks to Solve Optimal Quantum Control Problems ###### Abstract Reliable high-fidelity quantum state transformation has always been considered as an inseparable part of quantum information processing. In this regard, Pontryagin maximum principle has proved to play an important role to achieve the maximum fidelity in an optimum time or energy. Motivated by this, in this work, we formulate a control constrained optimal control problem where we aim to minimize time and also energy subjected to a quantum system satisfying the bilinear Schrodinger equation. We derive the first order optimality conditions through the application of Pontryagin Maximum (minimum) Principle, which results in a boundary value problem. Next, in order to obtain efficient numerical results, we exploit a particular family of physics-informed neural networks that are specifically designed to tackle the indirect method based on the Maximum Principle of Pontryagin. This method has not yet been studied in the quantum context, but it can significantly speed up the process. To this end, we first obtain a set of relations which finally let us compute the optimal control strategy to determine the time- and energy-optimal protocol driving a general initial state to a target state by a quantum Hamiltonian with bounded control. We make use of the so-called "qutip" package in python, and the newly developed "tfc" python package. ## I Introduction Over the last years, understanding the optimization methods of quantum systems has been a challenge for researchers. In the most quantum control protocols, the control law is preferably computed without experimental feedback in an open-loop layout. In this regard, Optimal Control Theory (OCT) provides powerful tools, allowing to formulate quantum control problems in order to seek a set of admissible controls satisfying the system dynamics while optimizing a cost functional (e.g., fidelity, time or energy). For optimizing a cost functional in an optimal control setup, several numerical solution methods have been developed, which can generally be divided into direct and indirect subcategories, [2]. In the former method, the optimal control problem is considered as a non-linear optimization/programming problem, while the latter method is based on the optimality conditions of Pontryagin Maximum (or Minimum) Principle (PMP), which results in a two-point boundary value problem (BVP) in the state and adjoint conditions that possibly can be solved by shooting methods. As an example, a time discretized computational scheme has been proposed in [1], aiming to solve a high fidelity quantum state transfer problem by means of an indirect method based on PMP. Generally, dynamical quantum control originates from a time dependent quantum-mechanical Hamiltonian that steers the dynamics of the quantum system subjected to the constraints, e.g., relaxation processes. Hence, the realization of an optimal sequence is highly complicated in quantum control problems, and is dependant on the particular system under study. One way to deal with the problem complexity is the introduction of physics-informed neural networks (PINNs) to the context of quantum control. The term physics-informed neural networks is used to indicate the neural networks (NNs) for which the loss function comprises the physics as a regularization term, [3]. PINNs can be applied to any quantum evolution with a well-known model. Recently, the flexibility of PINNs has been shown in quantum control context, [4]. In this work, we implement a quantum optimal control problem by applying the PMP and modeling a NN representation of the state-adjoint pair, for which the residuals of the BVP are considered as the loss to be as close to zero as possible. We will utilize the PINN methodology, developed in [5, 10], in quantum framework. In this method, PINNs are trained to learn actions satisfying PMP, so the optimality is guaranteed by learning the solutions of the associated BVP. These PINNs, named Pontryagin NNs (PoNNs), play an effective role in learning optimal control actions. Finally, considering the importance of quantum state to state transition problem in quantum information processing, we propose a time- and energy-minimum optimal control problem to achieve a high fidelity quantum state transfer through exploiting PoNNs. The paper is organized as follows: We first recall the set of PMP optimality conditions for a general unconstrained quantum optimal control problem. Then, we review how PoNNs can be employed to learn the optimal control actions from the unknown solutions of the BVP arising from the PMP necessary optimality conditions. Afterwards, we formulate a quantum state transition problem under control constraints and obtain the necessary conditions of optimality. We then use PoNNs to solve the BVP, which is resulted from the application of PMP through the indirect method. The simulation results have been shown for the quantum state transfer problem in a three-level system. The paper ends with conclusions and an overview on prospective research challenges. Notation.For a general continuous-time trajectory \(x\), the term \(x(t)\) indicates the trajectory assessed at a specific time \(t\). For writing the transpose of a matrix (or vector) we use the superscript \(T\), and we use \(\dagger\) to show the conjugate transpose of a matrix (or vector). Throughout the text, the vectors are shown by vectorbold command. To denote the wave functions as vectors, we use the Dirac notation such that \(\left|\psi\right\rangle=\sum\limits_{k=1}^{n}\alpha_{k}\left|\hat{\psi}_{k}\right\rangle\), where \(\left|\psi\right\rangle\) indicates a state vector, \(\alpha_{k}\) are the complex-valued expansion coefficients, and \(\left|\hat{\psi}_{k}\right\rangle\) are basis vectors that are fixed. The notation bra is defined such that \(\left\langle\psi\right|=\left|\psi\right\rangle^{\dagger}\). For writing partial differential equations (PDEs), we denote partial derivatives using subscripts. In the general situation where \(f\) denotes a function of \(n\) variables including \(x\), then \(f_{x}\) denotes the partial derivative relative to the \(x\) input. ## II An Overview on Quantum Optimal Control In quantum mechanics, a pure state is described by a unit vector wave function \(\left|\psi\right\rangle\) in a complex Hilbert space \(\mathbb{H}\), represented as \[\left|\psi\right\rangle=\cos\frac{\theta}{2}\left|0\right\rangle+e^{i\varphi} \sin\frac{\theta}{2}\left|1\right\rangle \tag{1}\] in which \(\theta\in\left[0,\pi\right]\), and \(\varphi\in\left[0,2\pi\right]\). The evolution of an n-level pure state \(\left|\psi(t)\right\rangle\) can be modelled through the bilinear time-dependent Schrodinger equation for closed quantum systems as \[i\hbar\frac{\partial}{\partial t}\left|\psi(t)\right\rangle=H\left(t\right) \left|\psi(t)\right\rangle \tag{2}\] where \(\left|\psi(t)\right\rangle\) takes values on the state-space \(S^{2n-1}\), and \(\hbar\) is the reduced Planck's constant, considered as a unit in the rest of the paper. The control evolution is determined through the quantum-mechanical system Hamiltonian \(H(t)\), represented by \[H\left(u(t)\right) =H_{d}+H_{C}\left(t\right) \tag{3}\] \[=H_{d}+\sum\limits_{k=1}^{m}u_{k}(t)H_{k}\] The first term indicates the Hermitian matrix known as a drift Hamiltonian \(H_{d}=diag(E_{1},E_{2},\cdots,E_{n})\), where \(E_{k}\) represents a real number concerning the energy level. The second term captures a set of external control functions \(u_{k}(t)\in\mathbb{R}\) coupled to the quantum system via time independent interaction Hamiltonians \(H_{k}\), which are Hermitian matrices to describe the coupling between the control and the system. One important objective of optimal control in quantum information processing is to the address state to state transition problem in the state space, so before going ahead, we must address the problem of controllability to check if it is possible to steer the system from one state to another for all pairs of possible states. To do so, we first check the controllability of the system evolution operator \(U(t)\) satisfying \[i\frac{\partial}{\partial t}U\left(t\right)=H\left(t\right)U(t) \tag{4}\] which is right-invariant on the compact Lie group \(su(n)\). Note that it satisfies the necessary and sufficient condition of controllability since \[Lie\{iH_{d},iH_{1},\cdots,iH_{m}\}=su(n) \tag{5}\] which results in the controllability of (2) simply because the controllability of a right invariant system results in the controllability of the bilinear system. We now proceed with the optimal control formulation. For convenience and in order to express the problem in terms of only real quantities, we implement the system state and Hamiltonian as, [13, 15], \[\left|\bar{\psi}\left(t\right)\right\rangle=\begin{bmatrix}\text{Re}\left( \left|\psi\left(t\right)\right\rangle\right)\\ \text{Im}\left(\left|\psi\left(t\right)\right\rangle\right)\end{bmatrix} \tag{6}\] and \[\tilde{H}\left(u(t)\right):=\begin{pmatrix}\text{Re}\left(-iH\left(u\left(t \right)\right)\right)&-\text{Im}\left(-iH\left(u\left(t\right)\right)\right) \\ \text{Im}\left(-iH\left(u\left(t\right)\right)\right)&\text{Re}\left(-iH \left(u\left(t\right)\right)\right)\end{pmatrix} \tag{7}\] so we can rewrite (2) as \[\frac{\partial}{\partial t}\left|\bar{\psi}\left(t\right)\right\rangle= \tilde{H}\left(u\left(t\right)\right)\left|\bar{\psi}\left(t\right)\right\rangle \tag{8}\] In the following, we deal with a problem to find a way to drive an initial state \(\left|\bar{\psi}\left(t_{0}\right)\right\rangle=\left|\psi_{0}\right\rangle\) to a desired final state \(\left|\bar{\psi}\left(t_{f}\right)\right\rangle=\left|\psi_{f}\right\rangle\) while minimizing a cost functional. The methods to design the quantum optimal controller vary according to the choice of the cost functional, the construction of the Pontryagin-Hamiltonian, and the computation scheme using the Maximum Principle conditions. Let us consider the following unconstrained optimal control problem (\(OCP_{u}\)), \[\begin{array}{l}\text{minimize}\quad J\left(\left|\bar{\psi}\left(t\right) \right\rangle,u\left(t\right),t\right)\\ \\ \quad=\Phi\left(\left|\psi_{0}\right\rangle,\left(t_{0}\right),\left|\psi_{f} \right\rangle,\left(t_{f}\right)\right)+\int\limits_{t_{0}}^{t_{f}}L\left( \left|\bar{\psi}\left(t\right)\right\rangle,u\left(t\right),t\right)dt\end{array} \tag{9}\] _subjected to_ \[\left|\hat{\psi}\left(t\right)\right\rangle=f\left(\left|\bar{ \psi}\left(t\right)\right\rangle,u\left(t\right),t\right)\] \[\Phi\left(\left|\psi_{0}\right\rangle,t_{0}\right)=\Phi_{0}\] \[\Phi\left(\left|\psi_{f}\right\rangle,t_{f}\right)=\Phi_{f}\] where \(J\) in the cost function in which the term \(\Phi\) indicates the end-point cost, and \(L\) is the Lagrangian. The state and control are indicated by \(\left|\bar{\psi}\left(t\right)\right\rangle\) and \(u(t)\), respectively, and \(t\) in the independent variable with \(t_{0}\) showing the initial and \(t_{f}\) as the final time. For applying PMP within the indirect method, the Pontryagin Hamiltonian is defined by adjoining the constraints on the system dynamics to the Lagrangian \(L\) via introducing time-varying Lagrange multiplier vector \(\left|\lambda\left(t\right)\right\rangle\), whose elements are called the costates of the system. Hence, the Pontryagin Hamiltonian \(\mathcal{H}\) for all \(t\in\left[t_{0},t_{f}\right]\) is constructed as \[\begin{array}{l}\mathcal{H}(\left|\bar{\psi}\left(t\right)\right\rangle,u(t), \lambda\left(t\right),t)\\ \\ \quad=\left|\lambda\left(t\right)\right\rangle^{T}\tilde{H}\left(u\left(t\right) \right)\left|\bar{\psi}\left(t\right)\right\rangle+L(\left|\bar{\psi}\left(t \right)\right\rangle),u(t)\end{array} \tag{10}\] The first-order necessary optimality conditions of the PMP are then derived as \[\frac{\partial\mathcal{H}}{\partial u}=0 \tag{11}\] \[\left|\hat{\psi}\right\rangle=\frac{\partial\mathcal{H}}{\partial\left|\lambda \right\rangle} \tag{12}\] \[\left|\hat{\lambda}\right\rangle=-\frac{\partial\mathcal{H}}{\partial\left|\hat{ \psi}\right\rangle} \tag{13}\] Equations (12) and (13) that represent a boundary value problem are accompanied by the following possible transversality conditions on the Hamiltonian \[\left|\lambda\left(t_{0}\right)\right\rangle=-\frac{\partial J}{\partial\left| \psi_{0}\right\rangle} \tag{14}\] \[\mathcal{H}\left(t_{0}\right)=\frac{\partial J}{\partial t_{0}} \tag{15}\] \[\left|\lambda\left(t_{f}\right)\right\rangle=\frac{\partial J}{\partial\left| \psi_{f}\right\rangle} \tag{16}\] \[\mathcal{H}\left(t_{f}\right)=-\frac{\partial J}{\partial t_{f}} \tag{17}\] represent a boundary value problem (BVP). ## III Physics-Informed Neural Networks Based on the Theory of Functional Connections The boundary value problem resulted from the necessary optimality conditions has already been solved with several methods such as the so-called shooting method for quantum optimal control problems. In this section, we gave an overview of the newly-developed Pontryagin neural network method in [5], and, then, we apply the formulations in quantum context. The main feature of PINNs is to embed the differential equations (DEs) and boundary conditions describing the physics of the problem in their cost functions. PINNs can be designed to solve two classes of problems, including data-driven solution and data-driven discovery of PDEs, [3], following the original idea of using artificial neural networks to solve ordinary differential equations (ODEs) and PDEs in [8]. PINNs are a kind of universal function approximators that by means of a single neural network can approximate the solution of differential equations. To better understand the procedure of PINNs, let consider the following differential equation of a generic BVP: \[F_{i}\left(t,y_{j}\left(t\right),\dot{y}_{j}\left(t\right) \right) =0\] \[\text{ \emph{subjected to} :}\begin{cases}y_{j}\left(t_{0}\right)=y_{0_{j}}\\ y_{j}\left(t_{f}\right)=y_{f_{j}}\\ \dot{y}_{j}\left(t_{0}\right)=\dot{y}_{0_{j}}\\ \dot{y}_{j}\left(t_{f}\right)=\dot{y}_{f_{j}}\end{cases} \tag{18}\] in which \(i\) indicates the number of DEs forming the ODE system, and \(j\) shows the number of unknown solutions of the system that are approximated by a NN. By considering \(\theta\) as the NN parameters, which are trained by means of gradient-based methods, the PoNN is represented by, [5], \[y_{j}\left(t\right)=y_{j}^{NN}\left(t,\theta\right) \tag{19}\] where the time \(t\) is the input. PoNN is an especially trained NN satisfying the PMP through learning the solution of the arising BVP. To solve the BVP by applying the theory of functional connection (tfc) method, [5, 10], we first need to derive the constrained formulations together with their derivatives as \[y_{j}^{m}\left(t,g\left(t\right)\right)=g_{j}^{m}\left(t\right)+\sum_{k=1}^{n _{j}}s_{k}^{m}\left(t\right)\eta_{kj} \tag{20}\] in which \(g\left(t\right):\mathbb{R}\rightarrow\mathbb{R}\) indicates a user-specified function, \(s_{k}\left(t\right):\mathbb{R}\rightarrow\mathbb{R}\) are the so-called support functions, and the coefficients \(\eta_{k}\) represent constraint information, for all \(n_{j}\) constraints. Here, the superscript \(m\) and the subscript \(j\) refer to the \(m\)th derivative and \(j\)th unknown function, respectively. The support functions are linearly independent, and can possibly be chosen as \(s_{k}(t)=t^{k-1}\). By computing \(\eta_{kj}\)s, we can insert the boundary conditions to the constrained expression. Hence, by substituting the constrained expressions to (18), we can obtain a new unconstrained set of equations, which are only a function of \(g\left(t\right)\), represented as \[\tilde{F}_{i}\left(t,g_{j}\left(t\right),\dot{g}_{j}\left(t\right),\dot{g}_{j }\left(t\right)\right) \tag{21}\] The free function \(g_{j}\left(t\right)\), as developed in [7] based on the theory of extreme learning machine (ELM), is modeled by a single hidden layer feedforward neural network (SLFN) as \[g_{j}\left(z\right)=\sum_{n=1}^{L}\xi_{j,j}h\left(\omega_{l}z_{j}+b_{l}\right) =\xi_{j}^{T}h_{j}\left(z\right) \tag{22}\] where the summation is over all \(L\) hidden neurons, and \(h(\cdot)\) is the activation function. The output weight \(\xi_{l}\) and the input weights \(\omega_{l}=\left[\omega_{1},\omega_{2},\cdots,\omega_{L}\right]\) connect the \(l\)th hidden node to the output node and input nodes, respectively. \(b_{l}\) indicates the threshold of the \(l\)th hidden node. Since the domain of \(h(\cdot)\) and the \(t\) domain are not synchronous, we must do a mapping between \(t\) and \(z\), as \(z_{j}=z_{0}+c\left(t_{j}-t_{0}\right)\), where \(c>0\) is the mapping coefficient. Therefore, the derivatives of \(g_{j}\left(t\right)\) are transformed from \(t\) to \(z\) domain as \[\frac{d^{m}g_{j}}{dt^{n}}=\xi_{j}^{T}\frac{d^{n}h_{j}\left(z\right)}{dz^{n}}c^ {n} \tag{23}\] Since the theory of ELM is used for training the neural network, the unknowns would be \(\xi_{j}=\left[\xi_{j,1},...,\xi_{j,L}\right]^{T}\). Moreover, for the free final time optimal control problems, the coefficient \(c\) also becomes an unknown that needs to be computed. Now, we can summarize (21) as \[\tilde{F}_{i}\left(z_{j},\xi_{j}\right)=0 \tag{24}\] for which we need to discretize \(z_{j}\) into \(N\) points in order to obtain the set of unconstrained differential equations expressed as loss functions, so \[\mathcal{L}_{i}\left(\xi_{j}\right)=\left\{\begin{aligned} \tilde{F}_{i}\left(z_{0},\xi_{j}\right)\\ \tilde{F}_{i}\left(z_{1},\xi_{j}\right)\\ \vdots\\ \tilde{F}_{i}\left(z_{N-1},\xi_{j}\right)\\ \tilde{F}_{i}\left(z_{N},\xi_{j}\right)\end{aligned}\right\} \tag{25}\] For \(\tilde{N}\) differential equations, (25) is augmented to the loss function \(\mathbb{L}^{T}=\left[\mathcal{L}_{1},\mathcal{L}_{2},...\mathcal{L}_{i},..., \mathcal{L}_{\tilde{N}}\right]\). By imposing a true solution, we have \[\mathbb{L}=0_{Ns\tilde{N}} \tag{26}\] Therefore, the \(\xi_{j}\) coefficients can be learnt. It can be done by means of various optimization techniques, [5]. ## IV Quantum State Transition by a Pontryagin Neural Network Approach For many quantum operations, it is crucial to achieve the quantum state transition in the shortest possible time. However, for a given control objective, control amplitude is inversely proportional to the control time. Hence, in the case that state transition needs to be done in the shortest possible time, the control amplitude may be very large, which is not practically possible since the amplitude of control cannot be infinite. To address this problem, we now extend the optimal time-energy control problem formulation for the input constrained case. More precisely, in the sequel, we are interested in solving the input constrained optimal control problem (\(OCP_{c}\)): \[\begin{array}{c}\min_{u,t_{f}}\\ \text{subject to}\quad\left|\tilde{\psi}(t)\right\rangle=f(\left|\tilde{\psi} (t)\right\rangle,u(t)\,,t)=\tilde{H}\left(u\left(t\right)\right)\left|\tilde{ \psi}(t)\right\rangle\\ \left|\tilde{\psi}(t_{0})\right\rangle=\left|\psi_{0}\right\rangle\in\mathbb{R} ^{n}\\ t_{0}\leq t\leq t_{f}\\ u\left(t\right)\in\mathcal{U}:=\left\{u\in L_{\infty}:u\left(t\right)\in \Omega\subset\mathbb{R}\right\}\\ \Omega=\left[u_{\min},u_{\max}\right]\end{array}\] where \(\Gamma\) and \(\eta\) in the performance index (cost functional) \(J\) are non-negative coefficients, and \(t_{f}\) is the free final time to be optimized. The second term of \(J\) is a common choice for the cost functional in molecular control, which measures the energy of the control field in the interval \(\left[t_{0},t_{f}\right]\). Moreover, the control constraint is represented by a sufficiently smooth function with two-sided interval bounds. First, let turn our attention to transform the defined \(OCP_{c}\) into an unconstrained optimal control problem \(OCP_{u}\). Following the procedure that originally has been explained in [2], and has also been used in [5], we define a new unconstrained control variable \(\nu\) by replacing the control constraint with a smooth and monotonically increasing saturation function as \(u=\phi(\nu)\) where \[\phi\left(\nu\right)=u_{max}-\frac{u_{max}-u_{min}}{1+\exp\left(s\nu\right)} \quad with\quad s=\frac{c}{u_{max}-u_{min}} \tag{27}\] in which \(c\) is a constant parameter. Since the control variable is changed, we need to consider the following 4 items to define the new unconstrained optimal control problem; * Adding a regularization term to the cost function \(J\) defined in \(OCP_{c}\) by considering a regularization parameter \(\mu\). Therefore the new cost \(\tilde{J}\) is defined as \[\tilde{J}=J+\mu\int_{t_{0}}^{t_{f}}\left\|\nu\right\|^{2}dt\] (28) As it is explained in details in the optimization by indirect methods, [6], the closer the value of \(\mu\) gets to zero, the more the solution of the new \(OCP_{u}\) approaches the solution of the original \(OCP_{c}\). * Introducing an additional multiplier \(\varphi\) for taking the equality constraints into account. Hence, the new Pontryagin Hamiltonian is \[\tilde{\mathcal{H}}=\mathcal{H}+\mu\left\|\nu\right\|^{2}+\varphi\left(u- \phi\left(\nu\right)\right)\] (29) * Considering an additional optimality condition for the new control variable by maximizing new Pontryagin Hamiltonian with respect to \(\nu\). * Adding the constraint equation \[u-\phi(\nu)=0\] (30) to the boundary value problem. Now, the new \(OCP_{u}\) is well-defined. Therefore, the new cost functional is expressed by \[\tilde{J}=\Gamma t_{f}+\eta\int_{t_{0}}^{t_{f}}u^{2}\left(t\right)\,dt+\mu \int_{t_{0}}^{t_{f}}\left\|\nu\right\|^{2}dt \tag{31}\] and the Pontryagin Hamiltonian is formulated as \[\begin{array}{c}\tilde{\mathcal{H}}(\left|\tilde{\psi}\left(t\right)\right\rangle,u(t),\lambda(t),t)=\\ \left|\lambda\left(t\right)\right\rangle^{T}\tilde{H}\left(u\left(t\right) \right)\left|\tilde{\psi}\left(t\right)\right\rangle+\eta u^{2}\left(t\right) +\mu\nu^{2}+\varphi\left(u-\phi\left(\nu\right)\right)\end{array} \tag{32}\] We now apply the maximum principle to determine the form of the optimal control by \[\frac{\partial\tilde{\mathcal{H}}}{\partial u}=\left|\lambda\left(t\right) \right\rangle^{T}\tilde{H}_{u}\left|\tilde{\psi}\left(t\right)\right\rangle+2 \eta u\left(t\right)+\varphi=0 \tag{33}\] where \(\tilde{H}_{u}=\frac{\partial\tilde{H}\left(u(t)\right)}{\partial u(t)}\), and also we have \[\frac{\partial\tilde{\mathcal{H}}}{\partial\nu}=2\mu\nu-\varphi\phi^{\prime} \left(\nu\right)=0 \tag{34}\] Moreover, we need to apply the first-order necessary conditions for the state and adjoint, so \[\left|\hat{\psi}\right\rangle=\frac{\partial\tilde{\mathcal{H}}}{\partial \left|\lambda\right\rangle}=\tilde{H}\left(u\left(t\right)\right)\left|\tilde{ \psi}\left(t\right)\right\rangle,\quad\left|\tilde{\psi}\left(t_{0}\right) \right\rangle=\left|\psi_{0}\right\rangle \tag{35}\] \[\left|\hat{\lambda}\right\rangle^{T}=-\frac{\partial\tilde{\mathcal{H}}}{ \partial\left|\tilde{\psi}\right\rangle}=-\left|\lambda\left(t\right)\right\rangle ^{T}\tilde{H}\left(u\left(t\right)\right) \tag{36}\] since the implemented quantum-mechanical Hamiltonian is skew symmetric, we can rewrite (36) as \[\left|\hat{\lambda}\right\rangle=\tilde{H}\left(u\left(t\right)\right)\left| \lambda\left(t\right)\right\rangle,\quad\left|\lambda\left(t_{f}\right)\right\rangle =\mathbf{0} \tag{37}\] Notice that since the Lagrangian in the cost functional is not dependent on the state, the adjoint equation satisfies the same dynamics as the system state, and, therefore, \(\left|\hat{\psi}\right\rangle\) and \(\left|\hat{\lambda}\right\rangle\) are only coupled by means of the control field. Since the system dynamics is not explicitly dependent on time, the Pontryagin Hamiltonian has to be constant. From the transversality condition \(\tilde{\mathcal{H}}\left(t_{f}\right)=-\Gamma\). The presented optimal control problem is solved through the X-TFC framework. To do so, the state and adjoint are approximated using the constrained expressions, hence, \[\left|\tilde{\psi}\right\rangle\left(z,\xi\right)=\left(h_{\psi} \left(z\right)-\Omega_{1}\left(z\right)h_{\psi}\left(z_{0}\right)-\Omega_{2} \left(z\right)h_{\psi}\left(z_{f}\right)\right)^{T}\xi_{\psi}\] \[+\Omega_{1}\left(z\right)\left|\psi_{0}\right\rangle+\Omega_{2} \left(z\right)\left|\psi_{f}\right\rangle \tag{38}\] \[\left|\lambda\left(z\right),\xi\right\rangle=\left(h_{2}\left(z \right)-\Omega_{2}\left(z\right)h_{\lambda}\left(z_{f}\right)\right)^{T}\xi_{ \lambda}+\Omega_{2}\left(z\right)\left|\lambda_{f}\right\rangle \tag{39}\] where \(\Omega_{1}\) and \(\Omega_{2}\) are switching functions, [11], which in the general domain of z for initial and final values are respectively expressed as the following: \[\Omega_{1}\left(z\right)=1+\frac{2\left(z-z_{0}\right)^{3}}{\left(z_{f}-z_{0} \right)^{3}}-\frac{3\left(z-z_{0}\right)^{2}}{\left(z_{f}-z_{0}\right)^{2}} \tag{40}\] \[\Omega_{2}\left(z\right)=-\frac{2\left(z-z_{0}\right)^{3}}{\left(z_{f}-z_{0} \right)^{3}}+\frac{3\left(z-z_{0}\right)^{2}}{\left(z_{f}-z_{0}\right)^{2}} \tag{41}\] The derivatives of (38) and (39) are, then, \[\left|\hat{\psi}\right\rangle\left(z,\xi\right)=c\left(h_{\psi}^{ \prime}\left(z\right)-\Omega_{1}^{\prime}\left(z\right)h_{\psi}\left(z_{0} \right)-\Omega_{2}^{\prime}\left(z\right)h_{\psi}\left(z_{f}\right)\right)^{T }\xi_{\psi}\] \[+\Omega_{1}^{\prime}\left(z\right)\left|\psi_{0}\right\rangle+ \Omega_{2}^{\prime}\left(z\right)\left|\psi_{f}\right\rangle \tag{42}\] \[\left|\hat{\lambda}\right\rangle\left(z,\xi\right)=c\left(h_{\lambda}^{ \prime}\left(z\right)-\Omega_{2}^{\prime}\left(z\right)h_{\lambda}\left(z_{f} \right)\right)^{T}\xi_{\lambda}+\Omega_{2}^{\prime}\left(z\right)\left|\hat{ \lambda}_{f}\right\rangle \tag{43}\] Regarding the control variables, the following constrained expressions can be introduced \[u\left(z,\xi\right)=h_{u}^{T}\left(z\right)\xi_{u} \tag{44}\] \[\nu\left(z,\xi\right)=h_{\nu}^{T}\left(z\right)\xi_{\nu} \tag{45}\] and the multiplier \(\varphi\) is expanded as \[\varphi\left(z,\xi\right)=h_{\varphi}^{T}\left(z\right)\xi_{\varphi} \tag{46}\] Actually, the consideration for \(\varphi\) can also be done for the control variable \(\nu\). Hence, the vector of PoNN's unknown parameters to be learned is made up of \[\xi=\left\{\xi_{\psi}\quad\xi_{\lambda}\quad\xi_{\omega}\quad\xi_{\upsilon} \quad\xi_{\varphi}\quad c\right\}^{T} \tag{47}\] and the loss functions to be minimized are \[\mathcal{L}_{\psi}=\left|\hat{\psi}\right\rangle-\tilde{H}\left(u\left(t \right)\right)\left|\tilde{\psi}\left(t\right)\right\rangle \tag{48}\] \[\mathcal{L}_{\lambda}=\left|\hat{\lambda}\right\rangle-\tilde{H}\left(u \left(t\right)\right)\left|\lambda\left(t\right)\right\rangle \tag{49}\] \[\mathcal{L}_{u}=\left|\lambda\left(t\right)\right\rangle^{T}\tilde{H}_{u} \left|\tilde{\psi}\left(t\right)\right\rangle+2\eta u\left(t\right)+\varphi \tag{50}\] \[\mathcal{L}_{\nu}=2\mu\nu-\varphi\phi^{\prime}\left(\nu\right) \tag{51}\] \[\mathcal{L}_{\phi}=u-\phi\left(\nu\right) \tag{52}\] and the loss function being computed at the final time is \[\mathcal{L}_{\tilde{\mathcal{H}}}=\tilde{\mathcal{H}}\left(t_{f}\right)+\Gamma \tag{53}\] Now, we have to impose the valid solution of the augmented loss function as a \(N\times\tilde{N}\) dimensional zero matrix, and solve it by means of a numerical minimization scheme. ## V Simulation Results We consider a three-level system being controlled through a single control field \(u(t)\) on the orthonormal basis \(\left|a\right\rangle=\left[\begin{matrix}1&0&0\end{matrix}\right]^{T}\), \(\left|b\right\rangle=\left[\begin{matrix}0&1&0\end{matrix}\right]^{T}\), and \(\left|c\right\rangle=\left[\begin{matrix}0&0&1\end{matrix}\right]^{T}\). The drift and control Hamiltonians for such system are expressed as, [14], \[H_{d}=\left(\begin{matrix}0.5&0&0\\ 0&0.4&0\\ 0&0&0.6\end{matrix}\right),\quad H_{C}\left(t\right)=u\left(t\right)\left( \begin{matrix}0&1&0\\ 1&0&1\\ 0&1&0\end{matrix}\right) \tag{54}\] The convergence tolerance is considered on \(10^{-16}\), \(N=40\), \(\eta=0.1\), and \(\Gamma=0.01\). Moreover we use the Chebyshev orthogonal polynomials as the basis for tfc implementation. However, different basis or number of discretization points can be experimented. Let consider the transition of the initial state \(\left|\psi_{t}\right\rangle=\left|a\right\rangle\) to the target \(\left|\psi_{d}\right\rangle=\left|c\right\rangle\), for the case that \(-1\leq u(t)\leq 1\). The population evolution is shown in Fig 1. As it can be seen from the graph, the population of the initial state decays exponentially, while the population of target increases by time. Figure 2 shows the state trajectories in Cartesian coordinates, which is learnt by the PoNN during the computation time. To better understand the trajectory, we also considered the quantum state evolution on the Bloch Fig. 1: Population dynamics under quantum dynamics Fig. 2: State trajectories in Cartesian coordinates sphere with the spherical coordinates in Fig 3. Finally, in order to check the security level of reaching the target, we have to calculate the transition probability known as the quantum fidelity, which for two pure quantum states is computed by, [12], \[\mathcal{F}(|\psi(t)\rangle,|\psi_{f}\rangle)=|\langle\psi(t)|\psi_{f}\rangle|^{2} \tag{55}\] Since the system studied in this paper is a closed quantum system, we expect to reach the fidelity of 1, as well shown in Fig 4. ## VI Conclusions In this paper, we have exploited the newly introduced method called the physics informed theory of functional connections. Through this method, PoNNs are used to learn optimal control actions for an input constrained optimal control problem. We used the scheme to solve the boundary value problem arising from the application of the indirect optimal control method to a quantum state to state transition problem under control constraint at the cost of compromising between the goal of attaining optimal time and, simultaneously, keeping the energy of the field relatively small. For the studied quantum control system, we considered a pure state, evolving through Schrodinger equation. The same procedure can also be applied for considering the dynamics of the evolution operator. Future challenges first consist in a detailed comparison and illustration the superiority of PoNN method over the state of the art quantum control methods, and also exploiting the versatility of the optimal control paradigm further by considering an open quantum system, for which the dynamics is explained through, e.g., Markovian or stochastic master equations, and also considering additional constraints, e.g., state constraints, to tackle with more complicated quantum optimal control problems. ## Acknowledgment The authors acknowledge the support of FCT for the grant 2021.07608.BD, the ARISE Associated Laboratory, Ref. LA/P/0112/2020, and the R&D Unit SYSTEC-Base, Ref. UIDB/00147/2020, and Programmatic, Ref. UIDP/00147/2020 funds, and also the support of projects SNAP, Ref. NORTE-01-0145-FEDER-000085, and RELIBABLE (PTDC/EEI-AUT/3522/2020) funded by national funds through FCT/MCTES. The work has been done in the honor and memory of Professor Fernando Lobo Pereira.
2305.02099
Joint A-SNN: Joint Training of Artificial and Spiking Neural Networks via Self-Distillation and Weight Factorization
Emerged as a biology-inspired method, Spiking Neural Networks (SNNs) mimic the spiking nature of brain neurons and have received lots of research attention. SNNs deal with binary spikes as their activation and therefore derive extreme energy efficiency on hardware. However, it also leads to an intrinsic obstacle that training SNNs from scratch requires a re-definition of the firing function for computing gradient. Artificial Neural Networks (ANNs), however, are fully differentiable to be trained with gradient descent. In this paper, we propose a joint training framework of ANN and SNN, in which the ANN can guide the SNN's optimization. This joint framework contains two parts: First, the knowledge inside ANN is distilled to SNN by using multiple branches from the networks. Second, we restrict the parameters of ANN and SNN, where they share partial parameters and learn different singular weights. Extensive experiments over several widely used network structures show that our method consistently outperforms many other state-of-the-art training methods. For example, on the CIFAR100 classification task, the spiking ResNet-18 model trained by our method can reach to 77.39% top-1 accuracy with only 4 time steps.
Yufei Guo, Weihang Peng, Yuanpei Chen, Liwen Zhang, Xiaode Liu, Xuhui Huang, Zhe Ma
2023-05-03T13:12:17Z
http://arxiv.org/abs/2305.02099v1
Joint A-SNN: Joint Training of Artificial and Spiking Neural Networks via Self-Distillation and Weight Factorization ###### Abstract Emerged as a biology-inspired method, Spiking Neural Networks (SNNs) mimic the spiking nature of brain neurons and have received lots of research attention. SNNs deal with binary spikes as their activation and therefore derive extreme energy efficiency on hardware. However, it also leads to an intrinsic obstacle that training SNNs from scratch requires a re-definition of the firing function for computing gradient. Artificial Neural Networks (ANNs), however, are fully differentiable to be trained with gradient descent. In this paper, we propose a joint training framework of ANN and SNN, in which the ANN can guide the SNN's optimization. This joint framework contains two parts: First, the knowledge inside ANN is distilled to SNN by using multiple branches from the networks. Second, we restrict the parameters of ANN and SNN, where they share partial parameters and learn different singular weights. Extensive experiments over several widely used network structures show that our method consistently outperforms many other state-of-the-art training methods. For example, on the CIFAR100 classification task, the spiking ResNet-18 model trained by our method can reach to **77.39**% top-1 accuracy with only 4 time steps. keywords: Spiking Neural Networks, Artificial Neural Networks, Knowledge Distillation, Weight Factorization + Footnote †: journal: Pattern Recognition ## 1 Introduction The Spiking Neural Networks (SNNs) have been recognized as one of the next-generation neural networks [1]. This type of neural network is known for its bio-mimicry of the brain neurons, which utilize "spikes" for information communication and can process data in a spatial-temporal manner [2; 3]. SNNs imitate such spike mechanisms and thus received a lot of research attention. Through the time dimension of spiking neurons, each of them fires a spike only if a variable called membrane potential transcends the threshold, if not, the spiking neuron would remain still. As a result, the activation would be either 1 (fire a spike) or 0 (remain silent), which eliminates multiplication in the neural networks and brings energy efficiency. For example, some work shows that SNNs can save orders of magnitude energy over Artificial Neural Networks (ANNs) [4; 5]. In addition, the temporal processing ability of SNNs makes them unique to ANNs in a way that learns spatial-temporal information. Despite its energy efficiency and special spatial-temporal processing ability, training SNNs is challenging because spiking neurons fire discrete spikes whose gradients are not well-defined. Consequentially, the zero-but-all gradient makes it impossible to train SNNs via gradient-based optimization methods. To address this, various training methods have been proposed. First, spike-timing-dependent plasticity (STDP) [6] approaches [7; 8] leverage an unsupervised learning algorithm called Hebbian learning [9] to update the weights. STDP is inspired by biology where the spiking time difference can determine the connection of the synaptic weight. Yet, STDP is limited to small-scale datasets, which may be due to the lack of global information about the error. Second, the Surrogate Gradient (SG) tries to find an alternative function when doing back-propagation of the spiking neurons. Therefore, SG can be incorporated into the current gradient-based optimization framework. SG provides decent performance and can narrow the time steps into (_i.e._ 5 \(\sim\) 20) even on a large-scale dataset such as ImageNet [10]. However, the SG inevitably introduces some error in calculating the gradient, though sometimes it is hard to estimate the error, which, makes the convergence unstable and slower than ANN training. Last, the ANN-to-SNN conversion [11; 12] offers another approach. It utilizes the well-trained ANN checkpoint and converts it into SNN by replacing the activation function from ReLU with spiking activation. It provides a fast way to obtain an SNN without using gradient descent at all. The disadvantage of this type of method is that SNN does not have its own learned feature, rather, all SNN does is to mimic ANN. In this work, we propose to employ a joint training framework of both ANN and SNN. During training, the parameters of ANN and SNN are shared partially. Specifically, we apply the matrix factorization of weights via Singular Value Decomposition (SVD) and let ANN and SNN optimize their own singular weights but keep the singular vectors the same. Second, we propose adding multiple branches in the network to distill the knowledge from ANN to SNN, called self-distillation. Our method can be viewed as a combination of ANN-SNN conversion and SG gradient training. We do not alter the SG training algorithm in SNN, but we provide guidance during the training of SNN. Unlike ANN-SNN conversion, where the ANN and SNN share the same parameters, we add more degree of freedom, _i.e._, different singular values in parameters, but restricting them to be totally different. The overall workflow can be seen in Fig. 1. Extensive experiments over several popular network structures show that our joint training framework consistently outperforms state-of-the-art training methods. For example, on the CIFAR100 classification task, we can train a spiking ResNet-18 and achieve 77.39% top-1 accuracy. In summary, our contributions are three-fold: 1. We propose a joint training framework where the knowledge of ANN is consistently transferred to the SNN during training. 2. We factorize the parameters of both ANN and SNN and restrict them to have the same singular vectors while learning different singular values. 3. Extensive experiments are conducted on vision benchmarks, demonstrating that our method reaches SOTA. The remainder of the paper is organized as follows: Section 2 provides a background for a better understanding of the proposed method. Next in Section 3, some preliminaries related to the method are introduced. In Section 4, the motivation of the paper, our ANN-SNN joint training framework, and the corresponding weight factorization method for the parameters in trained ANN and SNN are introduced in detail sequentially. Moreover, an overall algorithm pseudocode for better explaining the workflow of the proposed method is given. In Section 5, experimental settings and performance results of the proposed method and comparisons with other SoTA methods are presented. Finally, we summarize the research. ## 2 Related Work ### Spiking Neural Networks (SNNs). The SNN as a biology-inspired method, is recognized as a potential architecture to reach high-level artificial intelligence. Generally, there are two routers to Figure 1: The overall joint training framework. To better transfer knowledge, some multiple branches with a global average pooling layer and a fully-connected layer are added inside the network. Then three kinds of distillation losses are applied to these branches: the cross-entropy (CE) loss between the output and the label, the Kullback-Leibler Divergence (KLD) loss between the ANN’s output and the SNN’s output, and the L2 loss between the output features of ANN and SNN. obtain the high-performance SNNs: (1) converting a trained ANN to an SNN [13; 14] and (2) training the SNN from scratch directly [15; 16]. The ANN-SNN conversion method trains a well-performed ANN first and then modifies the ANN ReLU activation to the SNN spike activation and reuses other parameters of the ANN to generate the same architecture-based SNN. To further improve the converted SNN accuracy, some interesting methods are proposed. For example, in [11] and [12], the conversion error is decomposed to each layer and is reduced via calibrating the parameters. [17; 18] further advance the analysis of conversion error and formulate a conversion-aware training technique for ANN. Though this kind of method can obtain an SNN in a short time, getting a high-accuracy SNN requires many time steps which will increase the inference time at the same time. Training an SNN directly from scratch can greatly reduce time steps, even less than 5 [19; 20; 21], which receives more research attention recently. Recent works, such as [22; 23], by co-optimizing parameters, firing threshold, and leaky factor together respectively, have obtained comparable SNNs as the conversion method. However, all these methods do not solve the non-differentiability of the firing function and the gradient explode/vanish well, which will be introduced in detail in Section 4.1. In this work, we focus on solving this problem. ### Knowledge Distillation. Knowledge distillation (KD) was originally introduced as a kind of model compression method by [24]. [24] trains a small student model via transferring the knowledge of a rather large trained teacher model to the small one. In his work, the knowledge is defined as the teacher's outputs after the final softmax layer. It carries richer information than one-hot labels since it can provide the inter-class similarities information learned by the teacher, which the labels do not enjoy. Following this, many works extract the intermediate representations of the teacher as the knowledge to facilitate the optimization of the student, such as intermediate feature tensors [25] or attention maps [26]. Another line of KD methods transfers the feature relationships rather than the actual features themselves [27]. Along with classification tasks, Many works that use the KD based learning in other tasks, e.g., action detection [28], text recognition [29], continuous emotion recognition [30], and object detection [31]. There are also some works that introduce the KD method in the SNN domain [32]. However, they all adopt a big teacher SNN model to guide the small SNN counterpart learning. In this paper, rather than compress the SNN model, we use the KD method to solve the obstacle of the gradient exploding/varnish which avoids the good training of SNNs. ## 3 Preliminary ### Leaky Integrate-and-Fire Model We first introduce the notation following [33]. Throughout the paper, vectors are denoted by bold italic letters. For instance, \(\mathbf{x}\) and \(\mathbf{y}\) denote the input and target output variables. Matrices or tensors as clear from the text are denoted by bold capital letters (_e.g._\(\mathbf{W}\)). Constants are represented by small upright letters, e.g., \(t\). We can denote the time dimension and the element indices with bracketed superscripts and subscripts, respectively. For example, \(\mathbf{u}_{i}^{(t)}\) means the \(i\)-th membrane potential at time step \(t\). In this paper, the spiking neurons we use for SNNs are the well-known Leaky Integrate-and-Fire (LIF) neuron model [34]. The variable controlling the dynamics of LIF is called membrane potential, denoted by \(\mathbf{u}\). At each time step, the membrane potential is updated by \[\mathbf{u}^{(t+1),\text{pre}}=\tau\mathbf{u}^{(t)}+\mathbf{c}^{(t+1)},\text{ where }\mathbf{c}^{(t+1)}=\mathbf{W}\mathbf{x}^{(t+1)}, \tag{1}\] where \(\tau\) is a constant within \((0,1)\) and controls the leakage of membrane potential. \(\mathbf{c}^{(t+1)}\) is the pre-synaptic input at time step \(t+1\), which is charged by input current \(\mathbf{c}^{(t+1)}\). The input current can be calculated from the dot-product between the weights and the spike from the previous layer. Once the membrane potential exceeds the firing threshold \(V_{th}\), a spike will be fired from the LIF neuron, given by \[\mathbf{y}^{(t+1)}=\begin{cases}1&\text{if }\mathbf{u}^{(t+1),\text{pre}}>V_{th}\\ 0&\text{otherwise}\end{cases},\quad\mathbf{u}^{(t+1)}=\mathbf{u}^{(t+1),\text{pre}} \cdot(1-\mathbf{y}^{(t+1)}) \tag{2}\] After firing, the spike output \(\mathbf{y}^{(t+1)}\) will propagate to the next layer and become the input \(\mathbf{x}^{(t+1)}\) of the next layer, (note that we omit the layer index for simplicity). **The Classifier in SNN.** Generally, in a neural network-based classification model, the final network output will be used to compute the softmax and predict the desired class object. If we directly output the number of spikes to compute the probability, it will lose too much information. This is because the output of the network could be positive and negative as well. The spikes, however, can only output positive values. For this reason, we choose to only integrate the network output and do not fire them across time, as did in recent practice [35]. \[\mathbf{y}_{\text{net}}=\frac{1}{T}\sum_{i=1}^{T}\mathbf{c}_{\text{net}}^{(t)}=\frac{ 1}{T}\sum_{i=1}^{T}\mathbf{W}\mathbf{x}^{(t)}, \tag{3}\] Then, we can compute the cross-entropy loss based on the true label and \(\text{Softmax}(\mathbf{y}_{\text{net}})\). ## 4 Method In this section, we introduce our ANN-SNN joint training framework. First, we discuss the motivation of this work, _i.e._ the gradient computation problem in spiking neurons. Then, we present self-distilled training with multiple branches. In the end, we present the weight factorization for the parameters in ANN and SNN. ### Motivation The most notorious problem in SNN training may be the non-differentiability of the firing function Eq. (2). To concretely discuss this problem, we denote the loss function as \(L\) and calculate the gradients w.r.t. weights using the chain rule: \[\frac{\partial L}{\partial\mathbf{W}}=\sum_{t}\frac{\partial L}{\partial\mathbf{y}^ {(t)}}\frac{\partial\mathbf{y}^{(t)}}{\partial\mathbf{u}^{(t),\text{pre}}}\frac{ \partial\mathbf{u}^{(t),\text{pre}}}{\partial\mathbf{c}^{(t)}}\frac{\partial\mathbf{c}^{(t )}}{\partial\mathbf{W}}. \tag{4}\] Here, the firing function (Eq. (2)) is similar to the sign function. The gradient of sign is 0 almost everywhere except for the threshold. Recall that the gradient descent updates the parameters by subtracting the learning rate multiplied by the gradient, therefore, the actual updates for weights would either be 0 or infinity. As mitigation of this problem, the surrogate gradient was proposed. When performing the forward pass, the firing function remains exactly the same, however, when performing the backward pass, the firing function becomes a surrogate function. And we can compute the surrogate gradient function. A popular surrogate gradient may refer to the rectangular function proposed in [16]. Another type is called rectangular function, given by \[\begin{cases}\frac{\partial\mathbf{y}^{(t)}}{\partial\mathbf{u}^{(t),\text{pre}}}&= \gamma\max\left(0,1-\left|\frac{\mathbf{u}^{(t),\text{pre}}}{V_{th}}-1\right| \right),\\ \frac{\partial\mathbf{y}^{(t)}}{\partial\mathbf{u}^{(t),\text{pre}}}&=\frac{1}{a} \text{sign}\left(\left|\mathbf{u}^{(t),\text{pre}}-V_{th}\right|<\frac{a}{2} \right).\end{cases} \tag{5}\] Both of them have a hyper-parameter to control the width and the sharpness of the surrogate gradient. The rectangular function will become the Straight-Through Estimator [36] if \(V_{th}=0.5,a=1\). The triangular is computed based on the distance between the potential and threshold. **Gradient Explode/Vanish.** The gradient explode or vanish problem in ANN can be effectively mitigated by residual block, which contains the skip connection [37]. The skip connection can be formulated by \[\mathbf{y}=g(f(\mathbf{x})+\mathbf{x}), \tag{6}\] where \(g(\cdot)\) is the activation function, _e.g_. ReLU in ANN, and \(f(\cdot)\) is the convolutional layers and activation layers in the main path. Since ReLU is unbounded for the positive part, the gradient can be passed to the input of the block. However, in the case of LIF neurons, the gradient will be reduced through SG. Either \(\mathbf{u}^{(t),\text{pre}}>2V_{th}\) or \(\mathbf{u}^{(t),\text{pre}}<0\) the gradient of LIF will be 0. Moreover, the output of \(g(\cdot)\) is 0/1, which cannot effectively carry the information from the input tensor to the network output. Thus, even using ResNet and SG the SNN still cannot be well-trained due to the potential gradient exploding/varnish. ### Self Distillation Here, we propose our joint-training framework, which composes of distillation of partial weight sharing. Let us divide the ResNet into several parts. The ResNet has a stem (the first convolution), a body, and a head (the global average pooling layers and the classifier). The body is made of 4 stages, where each stage composes several residual blocks. The residual blocks have two or three convolution layers and the skip connection. As we discussed before, even equipped with residual blocks, the SNN may still suffer from the gradient explode/vanish problem. Thus, we add knowledge distillation from ANN to SNN. Particularly, the source of knowledge comes from not only the network output but also the intermediate output. Similar to Branchynet [38] we add multiple branches inside the network. In total, there are four intermediate branches, which are followed right after the end of each stage of the ResNet with a global average pooling layer and a fully-connected layer. The overall loss function for this distillation framework is composed of 4 parts: 1. Loss 1: The cross-entropy (CE) loss between the output and the label. Note that, the CE loss is introduced for both ANN and SNN, and also both the intermediate output from ANN and SNN. Thus, all branches in the framework receive direct knowledge from the labels. It can be formulated by: \[L_{\text{CE}}=\sum_{i=1}^{4}CrossEntropy(\mathbf{y}_{\text{ANN},i,\mathbf{z}})+\sum_{ i=1}^{4}CrossEntropy(\mathbf{y}_{\text{SNN},i,\mathbf{z}}),\] (7) where both ANN and SNN have 4 stages and thus there are 8 CE losses. 2. Loss 2: The Kullback-Leibler Divergence (KLD) loss between the ANN's output and the SNN's output. This loss function is computed based on the softmax (_i.e._ class probabilities), and ensures that the output from SNN should mimic that from ANN. It can be formulated by: \[L_{\text{KLD}}=\sum_{i}^{4}KLD(\texttt{detach}(\mathbf{y}_{\text{ANN},i}),\ \mathbf{y}_{\text{SNN},i}).\] (8) Again, this loss function is applied to all branches of the network. Note that the output from ANN is detached from calculating the gradients. Otherwise, the ANN's output will be pulled over to the SNN's output, leading to an accuracy decrease. 3. Loss 3: The L2 loss from hints. Due to the temporal dimension and binary activation in SNN architecture, the features in ANN and the features in SNN may have different norms of magnitude. Therefore, we impose L2-norm loss between the output features of ANN and SNN, given by \[L_{\text{Norm}}=\sum_{i}^{4}||\texttt{detach}(\mathbf{y}_{\text{ANN},i})-\ \mathbf{y}_{\text{SNN},i}||_{F}^{2},\] (9) Similar to KLD loss, the L2 norm loss also detaches the output from ANN from computing the gradients. Together, we optimize these three loss functions simultaneously to transfer the knowledge from ANN to SNN. Remarkably, the loss function from the first and second stage's outputs provides the guiding information for shallow layers, which alleviates the gradient explode/vanish problems. The overall loss function can be written by \[L=L_{\text{CE}}+\lambda_{1}L_{\text{KLD}}+\lambda_{2}L_{\text{Norm}}, \tag{10}\] where \(\lambda_{1}\) and \(\lambda_{2}\) are the hyperparameters for controlling the distillation loss. ### Weight-Factorization Training The second ingredient of our joint-training framework is weight-factorization training (WFT). This method is inspired by ANN-SNN conversion. Conventionally, the ANN-SNN conversion directly copy-pastes the weight and bias parameters from ANN to SNN [39]. This method is only effective when the time steps in SNN are large enough. However, in our training framework the SNN is trained with less than 10 time steps. Thus if we keep the parameters in the ANN and the SNN identical, the performance of the SNN is limited. Recently, [12] suggests that a proper _calibration_ of the weights in ANN is needed for conversion to SNN in extremely low time steps. This finding inspires us to develop a **partial weight-sharing** regime for the joint training of ANN and SNN. In order to do so, we apply the Singular Value Decomposition (SVD) to the weights parameters and share the eigenvectors for ANN and SNN while keeping the eigenvalues optimized at the discretion of the ANN and SNN separately. Intuitively, let us first consider a simple case: a fully-connected layer \(\mathbf{W}\in\mathbb{R}^{c_{in}\times c_{out}}\). We can apply the SVD to the weight matrix, given by \[\mathbf{W}=\mathbf{U}\mathbf{\Sigma}\mathbf{V}^{\top}=\begin{bmatrix}\mathbf{u}_{1 }&\mathbf{u}_{2}&\cdots&\mathbf{u}_{cin}\end{bmatrix}\begin{bmatrix}\sigma_{1}&0& \cdots&0\\ 0&\sigma_{2}&\cdots&0\\ \vdots&0&\ddots&0\\ 0&0&\cdots&\sigma_{r}\end{bmatrix}\begin{bmatrix}\mathbf{v}_{1}\\ \mathbf{v}_{2}\\ \vdots\\ \mathbf{v}_{c_{out}}\end{bmatrix}, \tag{11}\] where \(\mathbf{u}_{i}\in\mathbb{R}^{c_{in}}\) and \(\mathbf{v}_{i}\in\mathbb{R}^{c_{out}}\) are the \(i\)-th eigenvectors of \(\mathbf{W}\mathbf{W}^{\top}\) and \(\mathbf{W}^{\top}\mathbf{W}\), respectively. \(\sigma\) is the singular value and \(r\) is the number of singular value. SVD can decompose weights into: \[\mathbf{W}=\sum_{i=1}^{r}\sigma_{i}\mathbf{u}_{i}\mathbf{v}_{i}^{\top}. \tag{12}\] In other words, SVD can decompose the weight matrix into a weighted sum of several rank-1 matrices. In our WFT, we let SNN and ANN have the same eigenvectors but different eigenvalues, given by \[\mathbf{W}_{\text{ANN}}=\mathbf{U}\mathbf{\Sigma}_{\text{ANN}}\mathbf{V}, \quad\mathbf{W}_{\text{SNN}}=\mathbf{U}\mathbf{\Sigma}_{\text{SNN}}\mathbf{V}. \tag{13}\] In this case, the SNN and ANN do not share parameters completely, providing more degree of freedom compared to the ANN-SNN conversion works. In our implementation, we re-parameterize the weights using Eq. (13) and directly update \(\mathbf{U},\mathbf{V},\mathbf{\Sigma}_{\text{ANN}}\), and \(\mathbf{\Sigma}_{\text{SNN}}\) with gradient descent. The initial values are determined by applying the SVD for the initialized weights. The singular values in the ANN and SNN are also initialized to the same. We put the overall algorithm pseudocode in Algo. 1. #### 4.3.1 Memory Complexity Our method does not largely increase the memory of weights training when compared to the separate training baseline, _i.e._ optimize \(\mathbf{W}_{\text{ANN}}\) and \(\mathbf{W}_{\text{SNN}}\) separately. The number of elements for our method is \(c_{in}^{2}+c_{out}^{2}+2r\) where \(r=\min(c_{in},c_{out})\), while the number of elements for the baseline is \(2c_{in}c_{out}\). For most convolutional layers in ResNets, the \(c_{in}\) is the same with \(c_{out}\), therefore, our method only has \(2c_{in}\) additional parameters, with the same order of magnitude with bias parameters. For the downsampling layers, we have \(c_{out}=2c_{in}\) and thus our method has 20% more parameters, which is affordable considering that there are only 3 downsampling layers in ResNets. #### 4.3.2 Generalization to Convolutional Layers For Conv layers, the weights are 4D tensors, where kernel sizes add up to two additional dimensions. In our implementation, these two dimensions do not affect our implementations. We can apply the same SVD decomposition in every entry of the kernel. As a consequence, all layers can be implemented with WFT. ### Extending to Other Networks In addition to the ResNet we discussed before, our joint learning framework can be applied to other network architectures like VGG-series [40]. For these modern convolutional architectures, the network is usually partitioned into four different stages, each stage corresponding to a downsample of the input feature map and an increase of the channel numbers. We add the distillation loss function to the exit of these four stages. Thus, our method can seamlessly incorporate most convolutional networks. ## 5 Experiments In this section, we demonstrate the effectiveness and efficiency of our algorithms. We first briefly illustrate the implementation details of our experiments and then compare the results with existing state-of-the-art. We also provide ablation studies. ### Implementation Details We use ResNet-18 and ResNet-34 as our selected architectures for experiments. We also use VGG-16 [40] in some cases. The distillation hyper-parameters are set to \(\lambda_{1}=1\) and \(\lambda_{2}=0.3\). We use Adam optimizer [48] with a learning rate of \(1e-3\). The learning rate is decayed using the cosine annealing strategy [49]. The weight decay is set to \(5e-4\) and we train all models for 300 epochs and report the test accuracy in the last epoch. We run the model with 4 GTX 1080Tis. We verify our models on CIFAR-10, CIFAR-100 [50], as well as Tiny-ImageNet [10]. We encode the images to spike using the first layer in the SNN, as adopted in recent works[46; 44]. We also give an introduction for each dataset: **CIFAR10.** CIFAR-10 contains \(50\)k \(32\times 32\) training images and \(10\)k test images. It is divided into 10 classes. The network kernel sizes and strides of neural networks are adjusted to fit the size of this dataset. **CIFAR100.** CIFAR-100 consists of \(50\)k \(32\times 32\) training images and \(10\)k test images. It is divided into 100 classes. Similarly, the network kernel sizes and strides of neural networks are also adjusted to fit the size of this dataset. **Tiny-ImageNet.** Tiny-ImageNet is the modified subset of the original ImageNet dataset [10]. Here, there are 200 different classes of ImageNet dataset, with 100k training and 10k validation images. The resolution of the images is \(64\times 64\) pixels. ### Comparison with State of the Art In this section, we compare our method with the existing state-of-the-art works. We first focus on the evaluation of SNNs on CIFAR-10 and CIFAR-100 datasets. We adopt Hybrid training, TTBR, Temp Prune, Diet-SNN, STBP-tdBN, TSSL-BP, PLIF, Dspike, Real Spike, RecDis, and TET as our comparison (see reference in the results table) and summarize the accuracy comparison in Table 1. For the CIFAR-10 dataset, the highest accuracy from prior work is \(94.44\) with ResNet-19. While our joint-training method achieves \(1\%\) absolute improvements with the same time steps based on the ResNet-18. And the ResNet-19 has 2x channel numbers and more than 10x computation cost than ResNet-18. It is also worth noting that with only 2 time steps, our method can also outperform the Real Spike and the Dspike with 4 time steps with \(1.48\%\) \begin{table} \begin{tabular}{c c c c c} \hline \hline **Dataset** & **Method** & **Architecture** & **Time Steps** & **Accuracy** \\ \hline \hline \multirow{8}{*}{CIFAR10} & Hybrid training [41] & ResNet-20 & 250 & 92.22 \\ & TTBR [42] & ResNet-18 & 64 & 95.04 \\ & TSSL-BP [43] & CIFARNet & 5 & 91.41 \\ & TET [44] & ResNet-19 & 4 & 94.44 \\ & RecDis-NN [45] & ResNet-19 & 2 & 93.64 \\ \cline{2-5} & Real Spike [46] & ResNet-20 & 4 & 92.53 \\ & & & 2 & 90.47 \\ \cline{2-5} & & & 4 & 93.66 \\ \cline{2-5} & Dspike [33] & ResNet-18 & 2 & 93.13 \\ \cline{2-5} & STBP-tdBN [19] & ResNet-19 & 4 & 92.92 \\ & & & 2 & 92.34 \\ \cline{2-5} & ResNet-18 & 4 & **95.45** \\ & **Joint A-SNN (Ours)** & & 2 & **94.01** \\ \cline{2-5} & ResNet-34 & 4 & **96.07** \\ & ResNet-34 & 2 & **95.13** \\ \hline \multirow{8}{*}{CIFAR100} & TTBR [42] & ResNet-18 & 64 & 78.45 \\ & Diet-SNN [35] & ResNet-20 & 5 & 64.07 \\ \cline{1-1} & TET [44] & ResNet-19 & 4 & 74.47 \\ \cline{1-1} & RecDis-NN [45] & ResNet-19 & 4 & 74.10 \\ \cline{1-1} \cline{2-5} & Real Spike [46] & ResNet-20 & 4 & 64.87 \\ \cline{1-1} \cline{2-5} & Dspike [33] & ResNet-18 & 2 & 63.40 \\ \cline{1-1} \cline{2-5} & Dspike [33] & ResNet-18 & 4 & 73.35 \\ \cline{1-1} \cline{2-5} & ResNet-18 & 4 & **77.39** \\ \cline{1-1} \cline{2-5} & **Joint A-SNN (Ours)** & & 2 & **75.79** \\ \cline{1-1} \cline{2-5} & ResNet-34 & 4 & **79.76** \\ \cline{1-1} \cline{2-5} & ResNet-34 & 2 & **77.11** \\ \hline \hline \end{tabular} \end{table} Table 1: Comparison between our algorithm and existing algorithms on CIFAR-10/100 datasets with ResNets. Our method improves network performance across all tasks. and 0.35% accuracy, respectively. These comparison results clearly show the efficiency and effectiveness of our method. For the CIFAR-100 dataset, the TET [44] and Dspike [33] achieve the best accuracies, which are 73.35 and 74.47, respectively. Our joint training method greatly improves the accuracy to 77.39, nearly 3% improvement. Notably, the SNN trained by our method with even half-time steps (_i.e._, 2) can obtain 75.8% accuracy, outperforming the state of the arts. Moreover, we train a 34-layer network with our joint-training framework, pushing the limit of SNN higher. For example, on CIFAR-10, our ResNet-34 reaches 96.07% accuracy. As for the CIFAR-100 dataset, the ResNet-34 scores a 79.8% accuracy, a result close to 80%. In addition to the ResNet family architecture, we show that our framework can be applied to other networks like VGG-16. We run SNN with only 1 time step in order to compare the state-of-the-art Temporal Pruning [47]. We list the results in Table 2, where we can find our method outstrips the other SNN works tested with VGG-16. Our method achieves a much higher improvement on the CIFAR-100 dataset (4% compared to [47]). \begin{table} \begin{tabular}{c l c c c} \hline \hline **Dataset** & **Method** & **Architecture** & **Time Steps** & **Accuracy** \\ \hline \multirow{4}{*}{CIFAR10} & Hybrid training [41] & VGG-16 & 100 & 91.13 \\ & PLIF [22] & VGG-11 & 8 & 93.50 \\ & Temp Prune [47] & VGG-16 & 1 & 93.05 \\ \cline{2-5} & **Joint A-SNN (Ours)** & VGG-16 & 1 & **93.79** \\ \hline \multirow{4}{*}{CIFAR100} & Hybrid training [41] & VGG-11 & 125 & 67.87 \\ & Temp Prune [47] & VGG-16 & 1 & 70.15 \\ \cline{1-1} \cline{2-5} & **Joint A-SNN (Ours)** & VGG-16 & 1 & **74.24** \\ \hline \hline \end{tabular} \end{table} Table 2: Comparison between our algorithm and existing algorithms on CIFAR-10/100 datasets with VGGs. \begin{table} \begin{tabular}{c l c c c} \hline \hline **Dataset** & **Method** & **Architecture** & **Time Steps** & **Accuracy** \\ \hline \multirow{4}{*}{Tiny-ImageNet} & AGC [51] & VGG-16 & 150 & 51.92 \\ & DCT-SNN [52] & VGG-13 & 125 & 52.43 \\ \cline{2-5} & **Joint A-SNN (Ours)** & VGG-16 & 4 & **55.39** \\ \cline{1-1} \cline{2-5} & **Joint A-SNN (Ours)** & VGG-16 & 2 & **53.91** \\ \hline \hline \end{tabular} \end{table} Table 3: Comparison between our algorithm and existing algorithms on Tiny-ImageNet datasets. Our method improves network performance across all tasks. Next, we conduct experiments on the Tiny-ImageNet dataset in Table 3, which is a more complex dataset than CIFAR, to verify our method. There aren't many baselines on this dataset, yet our method still achieves higher accuracy with 4 or even 2 time steps. This shows the ability of our method to handle the large-scale dataset. ### Ablation Studies In this section, we conduct ablation studies on the design choice of our joint training frameworks. Here, we have several baselines: (1) Independent trained SNN without any distillation loss function; (2) trained SNN with vanilla KLD loss from trained ANN (similar to Knowledge Distillation [24]); (3) jointly trained ANN and SNN with different choices of loss functions, including CE Loss, KLD Loss, Norm Loss; (4) jointly trained ANN and SNN with weight-factorized training yet without distillation. Here, we summarize these cases together with final test accuracy and training time cost for 1 epoch running. Note that here we use ResNet-18 for the CIFAR-10 dataset. The results are put in Table 4, from which we can see that the standard training of SNN is 92.4%, a similar accuracy level to existing works. Because standard training does not use the knowledge from ANN, the training is the fastest among other approaches, amounting to 26.7 seconds per training epoch. If we choose to use Knowledge Distillation [24] (the second row), the performance would boost to 93.1%, which is a moderate improvement (0.7%). It also leads to a higher training time (increased by 5 seconds). Using the joint training with CE and KLD loss, we get a 1.7% accuracy improvement. Moreover, with the L2 norm loss, one even further gets another performance lift, amounting to 94.5% final accuracy. These two choices also increase the a bit training time but get significantly higher accuracy. Finally, we verify the WFT mechanism, which obtains 93.7% accuracy. This result proves that near-ANN parameters may help the optimization with SNN. Together, these parts all contribute to the final accuracy, resulting in 95.45% accuracy. We also compare the ANN performance here. Since WFT will also affect the training convergence of ANN, here we report how ANN's accuracy changes after \begin{table} \begin{tabular}{c c c c c c c} \hline \hline & \multicolumn{4}{c}{**Design Choices**} & \multirow{2}{*}{**Accuracy**} & \multirow{2}{*}{**Time**} \\ \hline w./ ANN & CE Loss & KLD Loss & Norm Loss & WFT & & \\ \hline & ✓ & & & & 92.39 & 26.7s \\ ✓ & & ✓ & & & 93.12 & 31.6s \\ ✓ & ✓ & ✓ & & & 94.09 & 34.8s \\ ✓ & ✓ & ✓ & ✓ & & 94.52 & 34.9s \\ ✓ & & & & ✓ & 93.69 & 32.2s \\ ✓ & ✓ & ✓ & ✓ & ✓ & **95.45** & 36.7s \\ \hline \hline \end{tabular} \end{table} Table 4: Ablation results for different design choices. using WFT. Our baseline result is \(95.61\%\). Using the CE loss, we add multiple branches to ANNs, which also helps the optimization, and get \(95.98\%\) accuracy. Finally, using WFT the accuracy of ANN is slightly affected (\(95.74\%\)). ### Energy Efficiency In this section, we measure the hardware efficiency of our proposed framework during inference. To measure the inference cost, we measure the energy cost of both computation and data movement. It is worthwhile to highlight that in some neuromorphic hardware, the data movement cost could be negligible due to the in-memory computing design [5]. Yet in the digital circuit, the data accessing energy cannot be ignored. Hence, we discuss the energy cost of computation and data movement separately in this section. **Computational Energy Cost.** The dot-product in ANN is equal to performing a multiply-accumulate (MAC) operation, composed of an addition and a multiplication. As for SNN, the binary nature of spike-based computation can eliminate the multiplication for all layers except for the first layer. Moreover, if the spike is not fired, the hardware can even avoid this addition with sparse computation. Based on this, we estimate the energy consumption following [35; 53], a technique using \(45\)nm CMOS technology. The MAC operation in ANN costs \(4.6pJ\) energy and the accumulation in SNN costs \(0.9pJ\) energy. Based on this, we compute the energy cost and put it in Table 5. Our network only costs \(82.2mJ\) for a single forward and consumes \(12.5\times\) lower energy compared with ANN. Compared to existing [33], our model consumes slightly higher energy, amounting to \(1.9mJ\). Nevertheless, our sacrifices only trivial energy for a large accuracy improvement over [33] (\(0.9\%\) accuracy uplift). **Data Movement Energy Cost.** We also estimate the energy cost of data movement in the case of digital circuit deployment. We follow that moving \(64\) bits of data from the cache costs \(10-100pJ\) using \(45\)nm CMOS technology too [53]. For ANN, we calculate the total data moved as two times of activation sizes from all layers, based on that every feature map will be moved from the computational unit to the cache after the computation of the previous layer and moved from the cache to the computational unit again for the computation of the present layer. For SNN, we multiply the activation sizes by \(T\) times due to the movement of membrane potential, as well as the output spikes number. Note that one spike is counted as \(1\) bit while one activation or one membrane potential is counted as \(32\) bits. We put the summary of data movement cost in Table 6 where minimum energy is calculated by \(10pJ\) per \(64\)-bit movement and \begin{table} \begin{tabular}{l c c c c c} \hline \hline **Method** & **Model** & **Acc.** & **\#Add.** & **\#Mult.** & **Energy** \\ \hline ANN (ours) & Res-18 & 95.74 & 187M & 187M & \(1.03J\) \\ \hline SNN [35](T=5) & Res-20 & 92.70 & 142M & 8.80M & \(168mJ\) \\ SNN ([33], T=2) & Res-18 & 93.13 & 71.2M & 3.52M & \(\mathbf{80.3}mJ\) \\ SNN (ours, T=2) & Res-18 & 94.01 & 73.4M & 3.52M & \(82.2mJ\) \\ \hline \hline \end{tabular} \end{table} Table 5: Energy estimation of ANN and SNNs of computation. maximum energy is calculated by \(100pJ\) per 64-bit movement. We can find that SNN indeed costs a slightly higher data movement energy than ANN. However, combing both data movement energy and computational energy still exhibits better energy efficiency in SNNs. ## 6 Conclusion In this paper, we have introduced the joint-training framework of ANN and SNN. Our framework consists of two core ingredients, the first is self-distillation from multiple branches, and the second is weight-factorized training assisted by the Singular Value Decomposition. Both of them aim to provide auxiliary information during the training of SNNs to circumvent the problem of gradient vanishing/exploding. Our method can be viewed as a special case of "hybrid learning", _i.e._, using ANN for SNN training. We have demonstrated that our method brings a large improvement over the original baseline and the existing state of the arts on several widely used network structures. We hope this framework will enable more advanced neuromorphic intelligence. However, since ANNs are experts in spatial feature processing but poor at temporal ones, depending on the guide of ANNs, our framework will limit the spatial-temporal processing ability of SNNs to some extent. For future work, we will further study the combination manner of ANNs and SNNs to optimize the underlying code and retain the spatial-temporal processing ability of SNNs. ## Acknowledgment This work is supported by grants from the National Natural Science Foundation of China under contracts No.12202412 and No.12202413.
2307.11844
Bio-realistic Neural Network Implementation on Loihi 2 with Izhikevich Neurons
In this paper, we presented a bio-realistic basal ganglia neural network and its integration into Intel's Loihi neuromorphic processor to perform simple Go/No-Go task. To incorporate more bio-realistic and diverse set of neuron dynamics, we used Izhikevich neuron model, implemented as microcode, instead of Leaky-Integrate and Fire (LIF) neuron model that has built-in support on Loihi. This work aims to demonstrate the feasibility of implementing computationally efficient custom neuron models on Loihi for building spiking neural networks (SNNs) that features these custom neurons to realize bio-realistic neural networks.
Recep Buğra Uludağ, Serhat Çağdaş, Yavuz Selim İşler, Neslihan Serap Şengör, Ismail Akturk
2023-07-21T18:28:17Z
http://arxiv.org/abs/2307.11844v2
# Bio-realistic Neural Network Implementation on Loihi 2 with Izhikevich Neurons ###### Abstract In this paper, we presented a bio-realistic basal ganglia neural network and its integration into Intel's Loihi neuromorphic processor to perform simple Go/No-Go task. To incorporate more bio-realistic and diverse set of neuron dynamics, we used Izhikevich neuron model, implemented as microcode, instead of Leaky-Integrate and Fire (LIF) neuron model that has built-in support on Loihi. This work aims to demonstrate the feasibility of implementing computationally efficient custom neuron models on Loihi for building spiking neural networks (SNNs) that features these custom neurons to realize bio-realistic neural networks. Neuromorphic chip, Loihi, Izhikevich neuron, basal ganglia circuit, energy efficiency. ## 1 Introduction Spiking Neural Networks (SNNs) enable a new model of computing that mimics asynchronous and sparse spiking behavior of biological neurons. These spiking neurons maintain their own internal states stored in local memory. Their dynamics change over time based on their internal states and external stimuli they receive. Inspired by biological counterparts, spiking neurons try to build highly efficient, parallel and scalable computing substrate by realizing SNNs in a dedicated neuromorphic hardware, such as Intel's Loihi [1], IBM's TrueNorth [2], SpiNNaker [3], BrainScaleS [4], NeuroGrid [5], BrainDrop [6] and DYNAPs [7]. Each of these neuromorphic chip has its own benefits and limitations. However, all neuromorphic chips are inspired by the structural and functional features of the biological brain, aiming energy-efficient, fault tolerant, highly parallel and scalable computing substrate. Programming neuromorphic chips and developing SNNs remain open, especially for applications that target bio-realistic behavior of neural networks. Therefore, in this paper, we demonstrate a showcase for developing bio-realistic neural network implementation on neuromorphic chip, Loihi in particular. While TrueNorth has a similar hardware and programming support, its inter-neuron connectivity capability is relatively limited as opposed to Loihi which supports larger-scale connectivity. SpiNNaker has similar capabilities, but is constructed of standard CPU hardware. Loihi's capabilities on the other hand are built-in on a chip which allows to explore new programming paradigms [8]. For the showcase that we demonstrated in this paper, we picked basal ganglia (BG) as neural network since it is a network of interest of many researchers due its central role on computationally demanding tasks, such as decision-making and reward related learning. In particular, we developed an SNN to implement BG network that performs Go/No-Go task. While Loihi provides built-in Leaky-Integrate-and-Fire (LIF) neuron model, we employ custom-built Izhikevich neurons (via microcodes that Loihi allows execute) on this BG network to further demonstrate how custom neuron models can be implemented and used on Loihi. **Related Work:** [8] demonstrates an SNN model for a mouse primary visual cortex using Leaky-Integrate and Fire (LIF) neuron on Loihi. In [9], an SNN-based neuronal-astrocytic central pattern generator was implemented on Loihi to control the locomotion of a hexapod robot. In this work, bursting neuron dynamics were implemented on Loihi by using customizable multi-compartmental neurons, in particular using non-spiking compartments that had no voltage reset (these non-spiking compartments were essential for realizing a bursting neuron behavior) [9]. On the other hand, various SNNs were developed to solve a diverse range of problems from various domains, such as event-based data processing, adaptive control, constrained optimization, sparse feature regression, and graph search [10]. Among those, noticeable ones are inspired by bio-realistic neural networks responsible for brain's navigational system [11][12], and a canonical columnar cortical circuit which is considered to have impact on capabilities such as perceptual organization, motion detection and attention [13]. Including these earlier studies, there are few realization of SNNs to implement bio-realistic neural networks on neuromorphic chips. Our hope is that this paper would demonstrate the feasibility of implementing bio-realistic neural networks on Loihi, helping to accelerate the advancement in the field. We make the following contributions in this paper: * To achieve the bio-realistic functionality of neuron behavior, we employed the Izhikevich neuron model which has been implemented on Intel's Loihi using microcodes. * We developed an SNN that features Izhikevich neurons to implement bio-realistic basal ganglia network running on low-power Intel's Loihi. * We used the basal ganglia network to demonstrate a fundamental neuropsychological decision-making task, namely the Go/No-Go task, running on Intel's Loihi. * We quantify the performance and energy usage of Intel's Loihi for the implemented basal ganglia neural network, performing the Go/No-Go task. We hope that this paper would demonstrate the feasibility and flexibility of using microcodes on Loihi neuromorphic chip to support different neuron types and mapping bio-realistic neural networks as SNNs. By doing so, we hope that this study would catalyze the participation of wider research community into neuromorphic computing. This paper is organized as follows. We highlight the features of the Loihi architecture in Section 2. Section 3 explains the Izhikevich neuron model and its implementation. We discuss the neural structure of basal ganglia along with its functionality and Loihi implementation in Section 4. Our experimental methodology and evaluation are provided in Section 5. Finally, we conclude the paper with Section 6. Figure 1: Simplified Diagram of Loihi 2 Neurocore Architecture. Intel Loihi Architecture Intel Loihi chip is a low-power, digital, many-core neuromorphic processor that was developed to mimic the complex functions of the human brain. It consists of a mesh of neuromorphic cores (a.k.a. neurocore), with x86 processing cores, and it features off-chip communication interface that allows to scale out to many other chips. As the building blocks of Loihi, neurocores can perform real-time inference and online learning (e.g., spike-timing-dependent plasticity (STDP) and reinforcement learning). These neurocores communicate asynchronously via barrier synchronization messages [1]. The Loihi architecture incorporates hierarchical connectivity, dendritic compartments, synaptic delays, and synaptic learning rules, in order to facilitate the implementation of SNNs in silicon. Each neurocore has synapse, dendrite, axon and learning components, as illustrated in Figure 1. The synapse block processes all the incoming spikes from the previous compartment/neuron and captures the synaptic weight from the memory. In the dendrite block, dendrite accumulators provide accumulated synaptic inputs. Compartent state keeps neuron-specific state that can vary over time and accumulated inputs are used to update these dynamic state variables. The axon block generates the spike messages to be carried ahead by the fan out cores. The learning block updates the synaptic weights based on a learning rule. In this paper, we have not incorporated any learning rule and left it as a future work. The learning block of Loihi provides standard STDP and a reward-based learning mechanism for online training. Its successor Loihi 2 supports three factor learning rule which allows to map the modulatory factors to post-synaptic neurons individually. It also supports custom on-chip learning via a microcode-based learning rules that can be executed by each neurocore. To program these neurocores and implement SNNs, a programming framework called Lava [14] can be used. Memory capacity of the blocks limits the total number of neurons that can be simulated by a neurocore. As the precision of the neuron model increases, the number of neuron per-neurocore decreases. First version of Loihi presents only generalized Leaky Integrate and Fire (LIF) neuron model. Despite its simplicity, LIF neurons may fall short to capture the dynamics of the bio-realistic neural networks which necessitate more sophisticated, yet computational efficient neuron models [15][16][17]. Because of that Loihi 2, successor of the first version, supports fully programmable neuron models that can be implemented via microcode instructions. The microcode instruction set includes bitwise, math and conditional operations. One can identify variables, parameters and define the behavior of the neuron model by using short sequence of instructions [18]. Because of the same drawback of LIF models, we preferred to use Izhikevich neuron model in this work [19]. We exploit these features of Loihi 2 in implementing Izhikevich neurons and furthermore the basal ganglia neural network. ## 3 Implementation of Neuron Model The following equations describe the discrete Euler form of the Izhikevich neuron model which is the basis of the neuron model used in this paper for Loihi implementation: \[\begin{split} v[t+\Delta t]&=v[t]+(0.04v[t]^{2}+5v[ t]-u[t]+I)\Delta t\\ u[t+\Delta t]&=u[t]+a(bv[t]-u)\Delta t\\ v[t]>v_{p}&\Rightarrow v[t+\Delta t]=c,u[t+\Delta t ]=u[t]+d\end{split} \tag{1}\] where \(v\) is the membrane potential and \(u\) is recovery variable, \(v_{p}\) is peak potential value corresponding to \(v_{thr}\) as in [20] and besides the initial values of \(v\), the value of \(v_{p}\) are the only biologically defined parameters. Behavior of a neuron can be tuned by setting the parameters of \(a\), \(b\), \(c\) and \(d\). \(I\) is the current that consists of an external component and synaptic input, which can be described as: \[\begin{split} I[t]&=I_{const}[t]+I_{syn}[t](1+\beta \Delta dop)\\ I_{syn}[t+\Delta t]&=\alpha I_{syn}[t]+\sum\left(w _{ij}\delta(t-t_{f}^{(i)})\right)\end{split} \tag{2}\] where \(t_{f}^{(i)}\) is the spike times of \(i\)th pre-synaptic neuron and \(w_{ij}\) is the strength of this synapse, whereas \(I_{syn}\) is used as a dynamic quantity to define synaptic currents. When a pre-synaptic neuron fires, the current increases momentarily by the value of synaptic weight. In the equation, decay parameter \(\alpha=1-\Delta t/\tau\) is a function of exponential time constant \(\tau\) (\(15ms\) in our case) and timestep duration \(\Delta t\) (which is \(1/8ms\)). Finally, the dopamine modulation is achieved by a factor called \(\beta\)[21] which regulates synaptic transmission between pre- and post-synaptic neurons. If \(\beta\) is higher than the baseline value, it increases the excitability of post-synaptic neurons. On the other hand, if the \(\beta\) value is negative, then it has an opposite effect on the post-synaptic neurons. Figure 2 illustrates the relationship among blocks and how inputs to the neuron model is processed and how output spike is generated, following the formulation provided above. Computation of the neuron model is expressed in dendrite block of the neurocore (Figure 1). Variables and neuron specific parameters in the model are stored in the compartment states. Each compartment state has small amount of memory. As the complexity of the model or the precision of the computation increases more memory is needed. Thus, multiple states are occupied. In this study, all the state variables \((v,u,Iext,Isyn)\) of the model are stored in the compartment state. In addition, \(a,b,c\) and \(d\) parameters are also kept in the compartment state to be able to provide variability between neurons in the group (Table 1). Figure 3, shows the block diagram of model's discrete computation on the hardware. Instructions are executed in discrete computation blocks. In each block one compartment state is accessible. Data of the state is temporarily stored in registers when needed to overcome this constraint. Some blocks (such as Blk 4, Blk 7) are used just for that purpose. Total synaptic input activity for the block diagram is provided through dendrite accumulator block which is denoted by DA in Figure 3. 12 bits of the data is used as fraction for all variables except DA. Accumulated value is shifted nine bits initially since its fraction bit number is three. In Blk 6, data is shifted three bits instead of multiplying by \(\Delta t=1/8\) before updating state variables. After the implementation, Izhikevich neurons are tested to check their ability of mimicking different spiking regimes. As shown in Figure 4, the neuron simulated on Loihi 2 is able to show different spiking behavior like regular spiking, fast spiking, intrinsically bursting, chattering, low-threshold spiking, tonic and rebound spiking successfully. In addition, the behavior of Izhikevich neuron model running on Loihi 2 chip is compared to the behavior of the same model simulated on CPU using both floating point and fixed point numbers. For the accuracy analysis, the ERRt measure is used which is based on spiking times. ERRt is defined as the time interval differences between two spikes in the original and the proposed model [22, 23]. The first spikes in the two simulations are synchronized for the ERRt calculation. Afterwards, the ratio of the difference between the second spikes to the difference between the two spikes of a neuron is used as a measure of accuracy: \begin{table} \begin{tabular}{l c c} \hline \hline & Size (Bits) & Compartment State Index \\ \hline v & 24 & 2 \\ u & 24 & 2 \\ a & 16 & 0 \\ b & 16 & 0 \\ c & 24 & 1 \\ d & 24 & 1 \\ Isyn & 24 & 0 \\ Iconst & 16 & 2 \\ delta\_dop & 16 & 1 \\ \hline \hline \end{tabular} \end{table} Table 1: Memory allocation in compartment state. Figure 2: Single point neuron diagram of Izhikevich neuron model given in Eq. 1 and Eq. 2. Post-synaptic current (PSC) is computed using spike inputs. PSC causes postsynaptic potential and action potential (AP) at soma calculated using Eq. 1. Finally, action potentials are converted to spikes and relayed to other neurons via axon. \[ERRt =\left|\frac{\Delta t_{x}-\Delta t_{fl}}{\Delta t_{fl}}\right|\times 100 \tag{3}\] \[\Delta t_{x} =t_{s2}^{(x)}-t_{s1}^{(x)}\] In Eq. (3), \(t_{s1}^{(x)}\) and \(t_{s2}^{(x)}\) are the time of first and second spikes, respectively. \(\Delta t_{x}\), on the other hand, is the difference of these spikes. As seen in the equation, simulation result with floating point (i.e., \(\Delta t_{fl}\)) is used as the reference. Two different analysis showing regular spiking (RS) and fast spikig (FS) behavior are carried out for each implementation as shown in Figure 5. On the other hand, Table 2 shows the ERRt values for these analysis. For RS behavior, all three implementations spike at the same time whereas FS spiking neurons differ in floating point implementation. In both RS and FS analysis, neurons implemented with fixed point on CPU and Loihi 2 yield consistent results (which increases the confidence on the fidelity of neuron behavior observed on Loihi 2). \begin{table} \begin{tabular}{l l l} \hline \hline & RS & FS \\ \hline CPU float. pt. - CPU fixed pt. & \(\%0\) & \(\%1.724\) \\ CPU float. pt. - Loihi 2 & \(\%0\) & \(\%1.724\) \\ \hline \hline \end{tabular} \end{table} Table 2: Accuracy Analysis (ERRt) for CPU Fixed Point Simulation and LOIHI 2 Hardware Implementation Figure 3: (a) Overall view of block diagram of Izhikevich neuron discrete computation for Loihi 2; (b) each block executes limited number of instructions and is related to just one compartmental state. Variables with green color allocate compartment state and blue colored blocks represent allocation of register memory. Orange variables are constant. The same constant value is used by all cells in a neuron group. Loihi employs a fixed-size discrete time-step to simulate the dynamics of the models. In this study, we use an explicit Euler integration scheme, where the time steps relate to the algorithmic time of the computation. Therefore, the algorithmic time may differ from the execution time spent on the hardware [8]. Moreover, due to hardware constraints and to increase the efficiency of the Loihi chip, certain bit-size constraints are imposed on the state variables which should be taken into account during microcode development to preserve the fidelity of the model that captures the intended dynamics of the neurons. encompasses basal ganglia identified depending on their source and target, which result in various neuropsychological functions such as motor control and learning, occur movement, limbic and cognitive behaviours [24]. While each loop goes through BG input nuclei in different regions and project to different output regions, the underlying algorithm and structure remains similar. Figure 6 illustrates the main pathways of cortico-basal ganglia network and indicates excitatory, inhibitory and modulatory connections of the BG network. The basal ganglia has two pathways, the direct and indirect, which emerge from the main input nuclei, striatum. The direct pathway facilitates movement by sending a signal to the output nuclei while the indirect pathway suppresses movement by sending a signal to the inhibitory pathway. In addition, the basal ganglia has a hyperpricted pathway that bypasses the striatum and directly inhibits movement, which is involved in pre-movement inhibition. By using inner connection between these multiple pathways, the lateral inhibition of losing actions over winning action is realized. Thus, the interplay of two pathways, namely, direct and indirect pathway will be considered in this paper to realize a computational model of _Go/No-Go_ task. This task is used as neuropsychological test to measure the ability of inhibiting habitual responses in favor of novel one. The classical model of BG introduces many neuroanatomical and functional diversity both in terms of the neuron behaviour, neurotransmitters and circuitry. While each connection provides unique interactions, the task can be implemented using a simplified model, relying on Izhikevich neurons. The details of neuron parameters and their connections to implement BG model on Loihi are given in Table 3 and Table 4 (mostly derived from [25]), respectively. Each population is limited to 100 neurons, as in [26], to keep the mapping time of the network onto neurocores reasonable. \(I_{const}\), is added to each of the neurons to increase the basal activity [25][27]. The afferent connections from the cortex is simulated through a Poisson spike generator that is microcoded via utilizing the random registers provided by the neurocore, whose parameters are shown in Table 5. Since SNc is not explicitly implemented, the impact of dopamine is represented as a variable in the neuron model. ## 5 Evaluation To facilitate the development of SNNs for capturing bio-realistic behavior of neural networks, a software programming platform, called Lava, has been introduced recently [14]. Lava framework allows to develop SNNs that employ different neuron models and these SNNs can be mapped to different neuromorphic hardware backends (it is also possible to Figure 6: The diagram of the cortico-basal ganglia circuit. STR-D1: direct striatum pathway neuron, STR-D2: indirect striatum pathway neuron, STR-FSI: striatum fast spiking neuron, STN: subthalamic nucleus, GPe: globus pallidus external,SNc: subtantia nigra pars compacta, SNr/GPi: substantia nigra pars reticulata/globus pallidus internal. simulate the behavior of the SNNs on CPU and GPU). In our case, we use Lava to develop an SNN that implements Basal Gaglia (BG) network targeting Loihi as a hardware backend. In our analysis, the BG circuit was run in three configurations based on the level of dopamine is introduced: i) base-level dopamine, ii) low-level dopamine and iii) high-level dopamine. In these configurations, the input from cortex remains constant, however, different levels of dopamine is introduced to striatum neurons. The Figure 7 illustrates the basal ganglia input, intrinsic and output nuclei activity in high dopamine and low dopamine stimulations. As it can be seen, high level dopamine excitation of D1R type MSNs of striatum results in decrease in the inhibitory activity of SNr that allows action selection. In the opposite, low level dopamine causes the promotion of indirect pathway and suppression of the direct pathway causing total suppression of the action. This demonstrates the realization of intended functionality of BG circuit for Go/No-Go task. For quantitative analysis, we examined different metrics, including resource utilization, power dissipation, energy usage and execution time on Loihi 2 and compared the results with similar BG circuits running on other platforms. In particular, the same BG circuit is used in [25] that has both SpiNNaker neuromorphic chip and simulation-based CPU (referred as SpineML in text) implementations. While the BG circuit is the same, the number of neurons in the populations are smaller in our implementation. Moreover, they have three channels in their implementation where the replicated BG models are connected via SNr and GPe to apply Go/No-Go task over multiple actions. Table 6 shows the \begin{table} \begin{tabular}{c c c c} \hline \hline Presyn. Group & Postsyn. Group & Weight & Conn. Prob. \\ \hline STR1 & STR1 & -0.3 & 1 \\ & STR2 & -0.3 & 1 \\ & GPi/SNr & -7.5 & 0.15 \\ STR2 & STR1 & -0.3 & 1 \\ & STR2 & -0.3 & 1 \\ & GPe & -7.5 & 0.15 \\ STR\_FSI & STR1 & -1.5 & 0.1 \\ & STR2 & -1.5 & 0.1 \\ GPe & STR\_FSI & -2.25 & 0.1 \\ & GPe & -2.25 & 0.1 \\ & STN & -2.25 & 0.1 \\ & GPi/SNr & -2.25 & 0.1 \\ STN & GPe & 2.25 & 0.1 \\ & GPi/SNr & 2.25 & 0.1 \\ GPi/SNr & GPi/SNr & -1 & 0.1 \\ \hline \hline \end{tabular} \end{table} Table 4: Connectivity Parameters of Basal Ganglia Circuit \begin{table} \begin{tabular}{l c c c c c} \hline \hline Group & \(a\) & \(b\) & \(c\) & \(d\) & \(I_{const}\) & \(\beta\) \\ \hline STR\_D1 & 0.02 & 0.2 & -65 & 8 & - & 0.6 \\ STR\_D2 & 0.02 & 0.2 & -65 & 8 & - & -0.6 \\ STR\_FSI & 0.1 & 0.2 & -65 & 2 & - & 0 \\ GPe & 0.1 & 0.585 & -65 & 4 & 5 & 0 \\ STN & 0.005 & 0.265 & -65 & 2 & 2 & 0 \\ GPi/SNr & 0.005 & 0.32 & -65 & 2 & 5 & 0 \\ \hline \hline \end{tabular} \end{table} Table 3: Neuron Parameters For the Basal Ganglia Circuit \begin{table} \begin{tabular}{c c c c} \hline \hline Presyn. & Postsyn. & Weight & Conn. & Freq. (Hz) \\ Group & Group & & Prob. \\ \hline G\_Ctx1 & STR1 & 5 & 0.2 & 15 \\ G\_Ctx2 & STR2 & 5 & 0.2 & 15 \\ G\_Ctx3 & STN & 1.125 & 0.05 & 4 \\ G\_noise & All & 0.05 & 0.1 & 5 \\ \hline \hline \end{tabular} \end{table} Table 5: Poisson Spike Generator Groups and Connection Parameters comparison for different metrics, and their implementations with one and three channels are labeled as 1CH and 3CH, respectively. Our implementation has only one channel. All measurements were obtained using Lava version 0.4.1 on Oheo Gulch that incorporates a single socketed Loihi 2 chip. Table 6 shows breakdown of performance metrics across BG models on Loihi2, SpiNNaker and CPU [25] (Core i7 2600, 3.4 GHz). As shown in Table 6, the BG circuit running on Loihi 2 is faster compared to SpiNNaker and CPU implementations. In terms of power dissipation, both Loihi 2 and SpiNNaker are comparable, and they both perform better than CPU implementation. While SpiNNaker has comparable power dissipation, Loihi 2 has lower energy-delay product, since each inference takes significantly less amount of time on Loihi 2. The implementation occupies 13 neurocores on Loihi 2, with 1750 neurons and 42,400 synapses. For the base-level dopamine configuration, a single time step takes approximately 7.25 \(\mu\)s and consumes 4.23 \(\mu\)J of energy (0.3 \(\mu\)J of which is active energy), resulting in an energy delay product of 3.1e-05 \(\mu\)Js. Despite its high energy-efficiency and performance, we encountered some challenges and limitations during the deployment of the BG network on Loihi 2 (mostly due to limitations imposed by the current version of the Lava framework, rather than Loihi hardware itself). First, during the deployment of SNNs onto Loihi 2 for larger network models that feature larger number of neurons, we observed relatively longer mapping duration due to increased synaptic connections (approx. an hour). Another limitation is the realization of conductance-based synaptic dynamics on Loihi2. The current version of Lava (0.4.1) allows only one dendritic accumulator input per neuron. This prevents us to use different reverse potential values for excitatory and inhibitory neurons. Because of that, it is not possible to compute the dynamics of different receptors, such as NMDA, AMPA, GABA [21]. To overcome this limitation in our BG model, we introduce a statically determined value \(I_{syn}\) (as used in Eq. 2). Also, because of the current limitations on Lava, we had to implement a custom monitoring tool via microcode to collect desired neuron states and variables. We allocated subset of neurocores to buffer spike data (where these data are \begin{table} \begin{tabular}{c c c c c c c c} \hline \hline & & & & Latency & Energy & Energy per & \\ Paper/Model & Power & Power & Power & per & per & Inference & Energy Delay \\ & Static & Dynamic & Total & Inference & Inference & Dynamic & Product \\ & (W) & (W) & (W) & (\(\mu\)s) & (\(\mu\)J) & (\(\mu\)J) & (\(\mu\)Js) \\ \hline BG Base Level Dopamine & 0.537 & 0.045 & 0.582 & 7.232 & 4.206 & 0.322 & 3e-5 \\ BG High Dopamine & 0.536 & 0.049 & 0.585 & 7.232 & 4.232 & 0.356 & 3.1e-5 \\ BG Low Dopamine & 0.537 & 0.045 & 0.582 & 7.228 & 4.210 & 0.328 & 3e-5 \\ SpiNNaker [25] 1CH & n/a & n/a & 0.8 & 1e3 & 80 & n/a & 0.08 \\ SpiNNaker [25] 3CH & n/a & n/a & 1.8 & 1e3 & 180 & n/a & 0.18 \\ SpineML [25] 3CH & n/a & n/a & 95 & 2.67e3 & 2.53e5 & n/a & 6.77e2 \\ \hline \hline \end{tabular} \end{table} Table 6: Performance Analysis of Various Networks Figure 7: Raster plots of striatum (MSN D1 and D2), GPe, STN and GPi/SNr neuron groups when (left) the dopamine release is higher and (right) the dopamine release is lower than the baseline level. collected via microcode). These buffers are readout in certain time intervals by the host machine to obtain raster plots (similar to Figure 7). Overall, Loihi 2 provides flexible and energy-efficient neuromorphic substrate to have bio-realistic implementations of neural networks, practical design and deployment on Loihi 2. As the Lava framework matures, it would address the existing limitations and make it more convenient to explore advanced features of Loihi 2. ## 6 Conclusion In this paper, we demonstrated that that Loihi is quite efficient in terms of performance and energy usage in the context of large bio-realistic neural network implementation and flexible in terms of supporting different neuron models featuring rich repertoire of neural dynamics by facilitating microcodes. In particular, we demonstrate a showcase of implementing a simplified bio-realistic basal ganglia neural network that carries Go/No-Go task, by using Izhikevich neurons on Intel Loihi chip.
2310.08716
Transformer Choice Net: A Transformer Neural Network for Choice Prediction
Discrete-choice models, such as Multinomial Logit, Probit, or Mixed-Logit, are widely used in Marketing, Economics, and Operations Research: given a set of alternatives, the customer is modeled as choosing one of the alternatives to maximize a (latent) utility function. However, extending such models to situations where the customer chooses more than one item (such as in e-commerce shopping) has proven problematic. While one can construct reasonable models of the customer's behavior, estimating such models becomes very challenging because of the combinatorial explosion in the number of possible subsets of items. In this paper we develop a transformer neural network architecture, the Transformer Choice Net, that is suitable for predicting multiple choices. Transformer networks turn out to be especially suitable for this task as they take into account not only the features of the customer and the items but also the context, which in this case could be the assortment as well as the customer's past choices. On a range of benchmark datasets, our architecture shows uniformly superior out-of-sample prediction performance compared to the leading models in the literature, without requiring any custom modeling or tuning for each instance.
Hanzhao Wang, Xiaocheng Li, Kalyan Talluri
2023-10-12T20:54:10Z
http://arxiv.org/abs/2310.08716v1
# Transformer Choice Net: A Transformer Neural Network for Choice Prediction ###### Abstract Discrete-choicee models, such as Multinomial Logit, Probit, or Mixed-Logit, are widely used in Marketing, Economics, and Operations Research: given a set of alternatives, the customer is modeled as choosing one of the alternatives to maximize a (latent) utility function. However, extending such models to situations where the customer chooses more than one item (such as in e-commerce shopping) has proven problematic. While one can construct reasonable models of the customer's behavior, estimating such models becomes very challenging because of the combinatorial explosion in the number of possible subsets of items. In this paper we develop a transformer neural network architecture, the Transformer Choice Net, that is suitable for predicting multiple choices. Transformer networks turn out to be especially suitable for this task as they take into account not only the features of the customer and the items but also the context, which in this case could be the assortment as well as the customer's past choices. On a range of benchmark datasets, our architecture shows uniformly superior out-of-sample prediction performance compared to the leading models in the literature, without requiring any custom modeling or tuning for each instance. Imperial College Business School, Imperial College London {h.wang19, xiaocheng.li, kalyan.talluri}@imperial.ac.uk ## 1 Introduction Firms are interested in understanding the choice behavior of their customers as well as forecasting the sales of their items. When customers choose at most one item per shopping instance, discrete-choice models estimate the probability of the choice, either at a segment level or individual customer level, based on a latent utility function of the features of the item, the customer, and the provided assortment. However, there are many situations where customers choose multiple items on a single shopping instance, either from the same category or across categories. The firm may be aware of only the final choices made by the customer (as in physical retail) or the precise sequence of those choices (such as in an e-commerce setting). _Multi-choice models_ are used for the former case, to estimate the probability of choosing a subset of items, amongst all possible subsets of the given assortment, considering potential interactions amongst the items and their features. _Sequential choice models_ consider the sequence of choices, taking into account not only the item and customer features but also what the customer has chosen till then to predict the subsequent choice(s). Modeling and predicting the choice probabilities for these situations is challenging: the complexity of the sequential and multi-choice models is considerably more than in the single-choice case because of combinatorial explosion in the number of possible customer journeys and final choices, and consequently models for multiple choices are less widely adapted in practice. In this paper, we introduce the Transformer Choice Net, a neural network using the Transformer architecture (Vaswani et al., 2017), as a data-driven solution that works under any of the three models: single, sequential, and multiple. The key contributions of this paper are as follows: * We develop the Transformer Choice Net, a neural network-based framework capable of encompassing all three choice paradigms--single, sequential, and multiple choices. This unification simplifies the traditionally fragmented approach to choice modeling. * We empirically validate the prediction performance of our model across diverse industry benchmark datasets. Our architecture shows uniformly superior out-of-sample prediction performance compared to the leading models in the discrete-choice literature, without requiring any custom modeling or tuning for each instance. Moreover, our architecture is scalable, showing an ability to learn and predict multiple choices over a large assortment size, overcoming the limitations of many sequential and multi-choice models. * We show theoretically the universal representation capacity of the Transformer Choice Net across the three choice paradigms. ## 2 Literature Review This section reviews the literature for single, sequential, and multiple choices, and also the literature on neural networks for predicting the choice probabilities. **Single-choice models.** For general background on discrete-choice models, see McFadden and Train (2000) and the book by Ben-Akiva and Lerman (1985). A plethora of models have been proposed for the single-choice case starting from the popular Multinomial Logit (MNL) choice model: to name a few, the Probit (Daganzo, 2014), the ranking-based choice model (Block and Marschak, 1959; Farias et al., 2013), the Negative-Exponential (also called Exponential) model (Alptekinoslu and Semple, 2016), and the Markov-chain choice model (Blanchet et al., 2016). From a machine learning perspective, the single-choice case can be viewed as a classification task where we assign probabilities for the various items (classes) to be chosen. From this point of view, researchers have applied random forests (Chen et al., 2021; Chen and Misic, 2022), embedding methods (Seshadri et al., 2019), and assortment context vectorization (Yousefi Maragheh et al., 2020; Tomlinson and Benson, 2021; Najafi et al., 2023; Bower and Balzano, 2020) with the latter trying to overcome some known weaknesses of the MNL model. Van Cranenburgh et al. (2022) provide a comprehensive review of the current literature on integrating machine learning into single-choice modeling. Bentz and Merunka (2000) give an early effort to use neural networks for single-choice modeling. Wang et al. (2020); Han et al. (2020); Sifringer et al. (2020); Wong and Farooq (2021); Arkoudi et al. (2023) investigate different neural network architectures to capture the relationships between the items' features and utility in the MNL choice model. Several recent works try to capture more complicated assortment effects: the RUMNet (Aouad and Desir, 2022) mimics the mixed-MNL model instead of the MNL model, and the AssortNet (Wang et al., 2023) encodes the entire assortment into the choice probability via ResNet architecture. Pfannschmidt et al. (2022); Rosenfeld et al. (2020) employ the Deep Set architecture (Zaheer et al., 2017) to allow permutation variations in input assortments (see also Wagstaff et al. (2019) and SS4). **Sequential and multi-choice models.** Sequential choice is typically based on purchase history data, often from assortments with only a small number of items (\(\leq 10\)) (Manchanda et al., 1999; Gupta, 1988). Despite the growth of e-commerce and the availability of click-stream data, it is somewhat surprising that there are relatively few models for sequential choice behavior: The SHOPPER model (Ruiz et al., 2020) stands out as a probabilistic representation of consumer choice, aiming to forecast sequential choices based on variational inference. Another noteworthy approach is due to Jacobs et al. (2021), where they compress purchase history data into purchase motivations and then employ variational inference for model deductions. Gabel and Timoshenko (2022) design a neural network that takes each customer's history as input to predict the next choice, but like Jacobs et al. (2021) the architecture does not encode the customer and item features. There is a slightly richer body of research on multiple choices, i.e., without knowing the sequence of choices (Chen et al., 2023; Bai et al., 2023; Luan et al., 2023; Jasin et al., 2023; Tulabandhula et al., 2023). Benson et al. (2018) expand the random utility maximization model from single to multi-choice scenarios. Tulabandhula et al. (2023) take a different approach, quantifying pairwise item interactions within each potentially chosen subset through a linear sum. Aarts et al. (2023) bridge point processes with subset-choice models, encoding pairwise interactions using the \(\log\det\) function. Lin et al. (2022a) augment the ranking-based choice model (Block and Marschak, 1959; Farias et al., 2013) to multiple choices, but they do not explicitly model item or customer features. A common limitation for all these models is scalability: as we have to predict the most likely amongst an exponential number of subsets, the size of the assortment they can handle is small. **Transformer architecture.** First introduced by Vaswani et al. (2017), the Transformer architecture has emerged as a ground-breaking deep learning framework. Initially tested on machine translation within the realm of natural language processing (NLP), it has since expanded to a broad range of NLP tasks as exemplified by ChatGPT (OpenAI, 2023) for text generation. The Transformer architecture has also excelled in computer vision (Han et al., 2022), audio processing (Dong et al., 2018), and integrated multimodal tasks (Ramesh et al., 2021). For a survey, we refer to the review by Lin et al. (2022b). Relevant to this paper, Lee et al. (2019) design the Set Transformer, which ensures any permutation of the input to yield identical outputs (see SS4 for more discussions). To the best of our knowledge, there has been no application till now to choice modeling. ## 3 Problem Setup ### Preliminaries on Choice Models #### 3.1.1 Single-Choice Model Consider a ground set of \(n\) potential items \(\mathcal{N}=\{1,2,...,n\}\). For completeness, we can let \(n\) denote the no-purchase option which (when selected) means the customer chooses none of the offered items. A seller chooses an _assortment_\(\mathcal{S}\subseteq\mathcal{N}\) to offer to the customer, and in the single-choice case the customer will choose at most one item from it. A _single-choice model_ prescribes the probability of choosing item \(i\) conditional on the assortment \(\mathcal{S}\) (where we can assume the no-purchase option is always in the assortment): \[\mathbb{P}(i|\mathcal{S})\text{ for all }i\in\mathcal{N}\text{ and } \mathcal{S}\subseteq\mathcal{N}.\] In particular, \(\mathbb{P}(i|\mathcal{S})=0\) for \(i\notin\mathcal{S}\), i.e., the customer cannot choose an item not offered in the assortment. In this way, a single-choice model \[\mathcal{M}=\{\mathbb{P}(i|\mathcal{S}):\mathcal{S}\subseteq\mathcal{N}\} \tag{1}\] dictates \(2^{n}-1\) probability distributions, each of which corresponds to one possible assortment (excluding when \(\mathcal{S}\) is an empty set). #### 3.1.2 Sequential Choice Model The sequential choice model is an intermediate between the single-choice model and the multi-choice model, and it also serves as a useful model by itself. Consider a customer shopping at an e-commerce who may choose more than one item for purchase and the items are chosen sequentially one after another from an assortment. To capture this scenario, we define the set of currently not chosen items as _candidates_ (denoted by \(\mathcal{C}\)), while the set of initially offered items as _assortment_ (denoted as \(\mathcal{S}\)). Thus \(\mathcal{C}\subseteq\mathcal{S}\) and the set \(\mathcal{S}\setminus\mathcal{C}\) is the set of chosen items so far. The single-choice model then can be viewed as a special case where \(\mathcal{C}=\mathcal{S}\). The sequential choice model describes the probability of choosing item \(i\) from candidates \(\mathcal{C}\) given the assortment \(\mathcal{S}\) \[\mathbb{P}(i|\mathcal{C},\mathcal{S})\text{ for all }i\in\mathcal{N},\mathcal{C }\subseteq\mathcal{S}\subseteq\mathcal{N}.\] Let \(\mathbb{P}(i|\mathcal{C},\mathcal{S})=0\) for \(i\notin\mathcal{C}\), i.e., the customer can only choose an item from the candidates set. In parallel to (1), the sequential choice model encapsulates the following distributions \[\mathcal{M}=\{\mathbb{P}(i|\mathcal{C},\mathcal{S}):\mathcal{C}\subseteq \mathcal{S}\subseteq\mathcal{N}\}. \tag{2}\] #### 3.1.3 Multi-Choice Model The multi-choice model considers the purchase of a basket of items, i.e., a subset of the given assortment. Hence, we are interested in the following distributions \[\mathcal{M}=\{\mathbb{P}(\mathcal{B}|\mathcal{S}):\mathcal{S}\subseteq \mathcal{N}\} \tag{3}\] where \(\mathcal{B}\subseteq\mathcal{N}\) denotes the basket of (chosen) items and \(\mathcal{S}\) is the given assortment as before. As earlier, we assume \(\mathbb{P}(\mathcal{B}|\mathcal{S})=0\) if \(\mathcal{B}\nsubseteq\mathcal{S}\); in other words, the chosen basket can only contain items from the assortment. ### Learning Task The learning task, the focus of our paper, refers to estimating the choice model \(\mathcal{M}\) from \(m\) observed samples \(\mathcal{D}\): \[\mathcal{D}=\begin{cases}\{(i_{k},\mathcal{S}_{k}),k=1,...,m\}&\text{single choice,}\\ \{(i_{k},\{\mathcal{C}_{k},\mathcal{S}_{k}\}),k=1,...,m\}&\text{sequential choice,}\\ \{(\mathcal{B}_{k},\mathcal{S}_{k}\}),k=1,...,m\}&\text{multiple choices,} \end{cases}\] where each observation, depending on the model to be estimated, consists of the final choice(s) (\(i_{k}\) or \(\mathcal{B}_{k}\)), accompanied by the assortment information (\(\mathcal{S}_{k}\) or \(\{\mathcal{C}_{k},\mathcal{S}_{k}\}\)). **Item/product feature**. We assume that there is a feature vector associated with each item/product. Such a feature vector encodes characteristics of the product such as color, size, brand, price, etc. When no such feature is available, one can still obtain such a vector by a one-hot encoding of the items. **Reduction to sequential choice model.** The goal of our paper is to develop one single transformer model that fits all three choice modeling scenarios. In this light, we discuss here how the single-choice model and the multi-choice model can be reduced to the sequential choice model in terms of both learning and inference so the transformer model can be based only on learning and predicting a sequential choice model. The reduction of the single-choice model to the sequential choice model is straightforward. As we pointed out earlier, we simply set \(\mathcal{C}=\mathcal{S}\), i.e., to predict the first item to be chosen given the initial assortment. For the estimation part, the sequential choice model can be estimated from the single-choice training samples \(\{(i_{k},\mathcal{S}_{k}),k=1,...,m\}\) by simply augmenting it into the form \(\{(i_{k},\{\mathcal{S}_{k},\mathcal{S}_{k}\}),k=1,...,m\}\). For the inference part, one can infer the probabilities of the single-choice model by using the probability \(\mathbb{P}(i|\mathcal{S},\mathcal{S})\) from the sequential choice model. The reduction from the multi-choice model to the sequential choice model is a bit more complicated. First, we note that the multi-choice model can also be mathematically represented by the sequential choice model. To see it, we can introduce a sequence \(\sigma\) to denote the order of items being added to the basket. Then we can decompose the choice probability of a basket by sequential choice probabilities: \[\mathbb{P}(\mathcal{B}|\mathcal{S})=\sum_{\sigma\in\text{Perms}} \prod_{j=1}^{|\mathcal{B}|}\mathbb{P}(\sigma_{j}|\mathcal{C}_{j}^{\sigma, \mathcal{S}},\mathcal{S}), \tag{4}\] where Perms contains all possible permutations over the set \(\mathcal{B}\), \(\sigma_{j}\) is the \(j\)-th item in the permutation \(\sigma\), and \(\mathcal{C}_{j}^{\sigma,\mathcal{S}}=\mathcal{S}\setminus\{\sigma_{i}:i<j\}\), i.e., the candidates when adding \(j\)-th item to the basket. With this representation in mind, we first consider the learning of a sequential choice model from multi-choice training samples \(\{(\mathcal{B}_{k},\mathcal{S}_{k})\},k=1,...,m\}\). Since the sequence in which the items are added to the basket \(\mathcal{B}_{k}\) is unobserved, we cannot directly use the data to train a sequential choice model. One remedy involves an iteratively random selection of items from the basket, designating it as the sequential choice, and then constructing its associated candidates. For example, we are given a multi-choice sample \(\{\mathcal{B},\mathcal{S}\}\) and we start the sample generation (for the sequential choice model) by setting \(\mathcal{C}=\mathcal{S}\). Say, the first randomly chosen item from \(\mathcal{B}\) is \(i^{(1)}\); then we obtain one sample of \(\{i^{(1)},(\mathcal{S},\mathcal{S})\}\). Then we move on to generating the second sample, \(\{i^{(2)},(\mathcal{S})\backslash\{i^{(1)}\},\mathcal{S})\}\) where \(i^{(2)}\) is randomly picked from \(\mathcal{B}\backslash\{i^{(1)}\}\). By continuing this process, we generate training samples for the sequential choice model from the original multi-choice sample \(\{\mathcal{B},\mathcal{S}\}\). A similar sampling method is also applied in Ruiz et al. (2020). To predict the multiple choices of a given assortment \(\mathcal{S}\) from a sequential choice model, the set of predicted choices can be sequentially generated by reversing the above sampling method. Specifically, we can start with \(\mathcal{C}=\mathcal{S}\) and either sample a product \(i^{(1)}\) following the distribution \(\mathbb{P}(\cdot|\mathcal{C},\mathcal{S})\) or select the item with the largest choice probability, and then remove \(i^{(1)}\) from \(\mathcal{C}\). By continuing this process, we can sample multiple items and add them to the predicted set of choices, until a stopping rule is met. This stopping rule can be enforced either when a pre-determined size of the basket is met or a virtual "stopping item" is sampled. ## 4 Transformer Choice Net Now we introduce the Transformer Choice Net (TCNet) for the sequential choice model (which as we pointed out covers both single and multi-choices). Mathematically, the TCNet is denoted as \(f^{\text{TCN}}\), a function that maps the candidate set \(\mathcal{C}\) and the assortment \(\mathcal{S}\) to the choice probability \(f^{\text{TCN}}_{i}(\mathcal{C},\mathcal{S})\) for each item \(i\in\mathcal{C}\). ### Attention Mechanism The attention mechanism has become a fundamental component of modern deep learning to solve various tasks of natural language processing and computer vision. In this subsection, we provide some preliminaries on this mechanism (see Niu et al., 2021) for more details) and show how it can be adapted for choice modeling. An _Attention_ function \(\text{Att}(Q,K,V)\) takes three matrices as input: the matrix of queries \(Q\in\mathbb{R}^{S\times d}\), the matrix of keys \(K\in\mathbb{R}^{S^{\prime}\times d}\), and the matrix of values \(V\in\mathbb{R}^{S^{\prime}\times d}\) \[\text{Att}(Q,K,V)=\phi(QK^{\top})V,\] where \(d\) is the feature dimension. The function \(\phi\) is an activation function to \(QK^{\top}\), with Softmax being the most prevalent choice. The matrix \(QK^{\top}\) is termed the (unnormalized) score matrix, the \((i,j)\)-element of which quantifies the influence of item \(j\) on item \(i\). Intuitively, the attention mechanism empowers a model to selectively focus on specific segments of its input, guided by the score function, to generate an output. _Self-attention_ is an exemplification of the attention mechanism where all the three matrices above depend on the input feature matrix \(X\): \[f^{\text{Att}}(X;W_{Q},W_{K},W_{V})=\text{Att}(XW_{Q},XW_{K},XW_{V}), \tag{5}\] where \(W_{Q},W_{K},W_{V}\in\mathbb{R}^{d\times d}\) are trainable parameters. For simplicity, we abbreviate the parameters and use \(f^{\text{Att}}(X)\) to denote this self-attention function. ### Architecture of TCNet Figure 1 illustrates the architecture of the Transformer Choice Net \(f^{\text{TCN}}\). The network's input comes from two sources: the assortment set \(\mathcal{S}\) of size \(S\) and the candidate set \(\mathcal{C}\) of size \(C\). At noted in SS3, we suppose each item \(i\) is associated with a feature vector \(x_{i}\in\mathbb{R}^{d}\) (either product feature or one-hot encoding of the product id). Then the input matrices of TCN are \(X^{\mathcal{S}}\in\mathbb{R}^{S\times d}\) and \(X^{\mathcal{C}}\in\mathbb{R}^{C\times d}\), and the output is a vector of choice probabilities for each item \(i\in\mathcal{C}\). The TCN consists of three main parts: assortment encoder, candidates encoder, and utility decoder. The _assortment encoder_ processes the input \(X^{\mathcal{S}}\) and encodes both the original feature \(X^{\mathcal{S}}\) and the interaction effects (from the assortment) into a latent feature matrix \(\tilde{X}^{\mathcal{S}}\in\mathbb{R}^{S\times d_{v}}\). Here each item \(i\) is associated with a latent feature vector \(\tilde{X}^{\mathcal{S}}_{i}\in\mathbb{R}^{d_{v}}\). In this feature transformation, the assortment encoder can contain \(L\) layers (which is a hyperparameter), and each with three sub-layers: First, an optional embedding sub-layer processes the original input \(X^{\mathcal{S}}\) by an element-wise fully connected feed-forward network layer applied to each item in the input assortment matrix separately, via two linear operations and an activation function \(\phi\): \[f^{\text{FFN}}(x)\coloneqq W_{2}\phi(W_{1}x+b_{1})+b_{2},\] where \(W_{1}\in\mathbb{R}^{d_{v}\times d}\), \(W_{2}\in\mathbb{R}^{d_{v}\times d_{v}}\) and \(b\in\mathbb{R}^{d_{v}}\) are trainable parameters. The dimension \(d_{v}\) controls the embedding's complexity. Second, a self-attention sub-layer implements the attention mechanism defined in (5). This layer captures the interaction effects between the items within the assortment. Third, a fully connected feed-forward network layer \(f^{\text{FFN}}(x)\) (similar to the first part) is applied to each item separately to further process each item's latent features. The _candidates encoder_ processes the original input \(X^{\mathcal{C}}\) in a similar manner as the assortment encoder. Figure 1: Architecture of Transformer Choice Net (TCNet). We omit the residual connections within each sub-layer. It processes the original feature and captures the interaction effect between items within the candidate set through three modules as the assortment encoder: an optional embedding sub-layer, a self-attention sub-layer, and a fully-connected feed-forward layer. One special point is an additional cross-attention sub-layer that mingles the assortment set and the candidate set. Specifically, this assortment-candidate attention sub-layer takes (i) the output of the assortment encoder \(\tilde{X}^{\mathcal{S}}\in\mathbb{R}^{S\times d_{v}}\) and (ii) the output \(X\) of the self-attention sub-layer of the candidates encoder as input, and then maps them to a latent feature matrix \(\tilde{X}^{\mathcal{C}\cdot\mathcal{S}}\in\mathbb{R}^{C\times d_{v}}\) that is aware of the assortment context. Mathematically, this is represented by \[f^{\text{AC}}(X)=\text{Att}(XW_{Q},\tilde{X}^{\mathcal{S}}W_{K},\tilde{X}^{ \mathcal{S}}W_{V})\] where \(W_{Q},W_{K},W_{V}\in\mathbb{R}^{d_{v}\times d_{v}}\) are trainable parameters. The _utility decoder_ processes the output latent features from the candidates encoder into some latent utilities for each item in \(\mathcal{C}\). Ideally, the output latent feature \(\tilde{X}^{\mathcal{C}\cdot\mathcal{S}}_{i}\) from the candidates encoder has encoded both the candidate set effect and the assortment set effect. The utility decoder transforms each of this latent feature vector \(\tilde{X}^{\mathcal{C}\cdot\mathcal{S}}_{i}\) into a (scalar) latent utility \(\tilde{u}_{i}\), and the transformation shares the same weight/parameter across different items. Here we apply a fully-connected feed-forward network, which can be replaced by other network architectures. Lastly, an MNL model/softmax layer converts these latent utilities into choice probabilities. ### Remarks on TCNet We make the following remarks on the TCNet. **Assortment size flexibility**. One advantage of the attention mechanism is that it can handle input (e.g., assortment set and candidate set) with varying sizes. This is useful in a choice modeling context because the assortment and the candidate sets may have variable cardinality. Moreover, the number of parameters in TCNet does not depend on the total number of items \(|\mathcal{N}|\) which makes it attractive for the case when there are a large number of items or newly added items. As long as the item/product feature of a new item/product is available, the TCNet can be used seamlessly for assortments with newly launched products. **Permutation equivariance**. For any permutation \(\sigma\) applied to the rows of \(X\) (such as interchanging the first and second row), the \(f^{\text{Att}}\) satisfies _Permutation Equivariant_(Lee et al., 2019), which is defined as \(f^{\text{Att}}(\sigma(X))=\sigma(f^{\text{Att}}(X))\). This ensures that each output choice probability remains invariant to the ordering/position of the input. This is useful for choice modeling context where the items in the assortment/candidate set are presented to the customer all at once. In this case, there is no ordering of the products and thus the customer choice should be permutation equivariant. Of course, when the position/order does matter in determining choice, one can encode the position/order as a feature. **Comparison against other NN-based choice models.** In Table 1, we make a comparison \begin{table} \begin{tabular}{c|c|c|c} \hline \hline Model & \# parameters & Variable size & Assortment effect \\ \hline TCNet (Ours) & \(O\left(dd_{v}+Ld_{v}^{2}\right)\) & Yes & Yes \\ DeepMNL(Wang et al., 2020; Sifringer et al., 2020) & \(O\left(dd_{v}+Ld_{v}^{2}\right)\) & Yes & No \\ AssortNet (Wang et al., 2023) & \(O\left(\|\mathcal{N}\|dd_{v}+Ld_{v}^{2}\right)\) & No & Yes \\ SDANet (Rosenfeld et al., 2020) & \(O\left(dd_{v}+Ld_{v}^{2}\right)\) & Yes & Yes \\ FATENet (Pfannschmidt et al., 2022) & \(O\left(dd_{v}+Ld_{v}^{2}\right)\) & Yes & Yes \\ DLCL (Tomlinson and Benson, 2021) & \(O\left(d^{2}\right)\) & Yes & Yes \\ RUMMet(Aouad and Desir, 2022) & \(O\left(dd_{v}+Ld_{v}^{2}\right)\) & Yes & No \\ \hline \hline \end{tabular} \end{table} Table 1: Comparison on the model complexity, where \(d\) and \(d_{v}\) are dimensions of item and latent features respectively, \(L\) is the number of layers, and \(\|\mathcal{N}\|\) is the total number of items. between TCNet and several other neural network-based choice models (for single-choice) from several aspects. The column "variable size" refers to whether the model requires a fixed assortment size or allows a variable size. The column "assortment effect" refers to whether the model captures the assortment effect, i.e., the interactions between items within the assortment. In terms of the number of parameters, we can see that TCNet has the same order of the number of parameters as other models, thus its empirical advantage (in the numerical experiment) should be attributed to its architecture rather than model size. In particular, we note that SDANet (Rosenfeld et al., 2020) and FATENet (Pfannschmidt et al., 2022) essentially implement the Deep Set (Zaheer et al., 2017) for choice modeling, and thus capture item-wise interaction on a coarser scale than our TCNet. DLCL (Tomlinson and Benson, 2021) explicitly models product interactions through linear functions and does not introduce a neural network architecture. **Transformer specializations for choice modeling.** The Transformer (Vaswani et al., 2017) is originally designed for seq2seq tasks, such as machine translation and text summarization. The model predicts the likelihood of the subsequent word from the vocabulary list. In comparison, the TCNet is designed for a set-to-member task, where the goal is to forecast the item(s) to be chosen from the candidate set and thus it requires the permutation equivariance. This necessitates modifications to the input's structure and the utility decoder. Similarly, Lee et al. (2019) introduce the Set Transformer which is designed to model interactions within an input set. Different from TCNet, the Set Transformer aims for permutation invariance (\(f(X)=f(\sigma(X))\) for any permutation \(\sigma\) over an ordered set \(X\)) which keeps the whole output invariant through permuting inputs. In the language of choice modeling, permutation invariance assumes that the assortment effect will take place through the assortment set as a whole \(\mathcal{S}\) (or \(\mathcal{C}\)) and keep same for all items, while the permutation equivariance allows a finer interaction between the items. **Training:** We use the cross-entropy loss (CE loss) for the training. With dataset \(\mathcal{D}=\{(i_{k},\{\mathcal{C}_{k},\mathcal{S}_{k}\}),k=1,\ldots,m\}\), the CE loss is defined by \[L_{\text{CE}}=-\frac{1}{m}\sum_{k=1}^{m}\log(f_{i_{k}}^{\text{TCN}}(\mathcal{C }_{k},\mathcal{S}_{k})). \tag{6}\] Several tricks/techniques are used in the original Transformer (Vaswani et al., 2017) such as layer normalization, multi-head attention, residual connection, and dropout. We also implement them for TCNet. ## 5 Expressiveness of TCNet The seminal work (Manski, 1977) shows that any single-choice model can be represented by \(O(2^{n}\times n)\) utility parameters: \(\{u_{i}^{\mathcal{S}},i\in\mathcal{N},\mathcal{S}\subseteq\mathcal{N}\}\). Specifically, for all \(i\in\mathcal{S}\) and \(\mathcal{S}\subseteq\mathcal{N}\), \[\mathbb{P}(i|\mathcal{S})=\frac{\exp(u_{i}^{\mathcal{S}})}{\sum_{j\in\mathcal{ S}}\exp(u_{j}^{\mathcal{S}})} \tag{7}\] where the utility \(u_{i}^{\mathcal{S}}\) represents the _contextualized_ utility of the \(i\)-th item under the assortment \(\mathcal{S}\). Bat-sell and Polking (1985) further show that the utility \(u_{i}^{\mathcal{S}}\) can be decomposed into a sum of item-wise interactions among the subsets of the assortment which is also recently discussed by Seshadri et al. (2019). **Theorem 1** ((Batsell and Polking, 1985)).: _For any \(\{u_{i}^{\mathcal{S}}:i\in\mathcal{N},\mathcal{S}\subseteq\mathcal{N}\}\), there exists a unique set of parameters \(\{v_{i}^{\mathcal{S}}:i\in\mathcal{S},\mathcal{S}\subseteq\mathcal{N}\}\) where \(\sum_{i\notin\mathcal{S}}v_{i}^{\mathcal{S}}=0,\forall\mathcal{S}\subset\mathcal{N}\), such that for all \(i\in\mathcal{S}\) and \(\mathcal{S}\subset\mathcal{N}\),_ \[u_{i}^{\mathcal{S}}=\sum_{S^{\prime}\subseteq\mathcal{S}\setminus i}v_{i}^{S^ {\prime}}.\] The above theorem shows that to estimate a single-choice model, it is enough to estimate the interaction effects of each item \(i\), i.e., \[\{v_{i}\},\{v_{i}^{\{j\}}:j\in\mathcal{N},j\neq i\},\ldots,\{v_{i}^{\mathcal{N }\setminus\{i\}}\}.\] Here the constraints \(\sum_{j\notin\mathcal{S}}v_{j}^{\mathcal{S}}=0,\forall\mathcal{S}\subset \mathcal{N}\) ensure the uniqueness of the parameters (noting the scale-invariance of the utilities in (7)). Based on the level of interaction, we call \(\{v_{i}\}\) as 0-th order interaction, \(\{v_{i}^{\{j\}}\}\) as 1-st order (or pairwise) interaction, and so on. The classic MNL model captures only 0-th order interaction, and several studies (Seshadri et al., 2019; Bower and Balzano, 2020; Yousefi Maragheh et al., 2020; Tomlinson and Benson, 2021; Najafi et al., 2023) explore diverse formulations to capture 1st-order interactions \(\{v_{i}^{\{j\}}\}\). In this sense, TCNet can capture \(L\)-th order interactions with \(L\) the number of layers in the self-attention module. Thus \(L\) provides a statistical handle for controlling the model complexity and also a modeling handle for controlling the level of item-wise interactions. In parallel, one can parameterize any sequential choice model with utility parameters: \[\mathbb{P}(i|\mathcal{C},\mathcal{S})=\frac{\exp(u_{i}^{\mathcal{C},\mathcal{S }})}{\sum_{j\in\mathcal{C}}\exp(u_{j}^{\mathcal{C},\mathcal{S}})}, \tag{8}\] where the utilities can be further decomposed by \[u_{i}^{\mathcal{C},\mathcal{S}}=\sum_{\mathcal{C}^{\prime}\subseteq\mathcal{ C}\setminus i}v_{i}^{\mathcal{C}^{\prime},\mathcal{S}}.\] Here the term \(v_{i}^{\mathcal{C}^{\prime},\mathcal{S}}\) captures the interaction effects of (i) the candidate subset \(\mathcal{C}^{\prime}\) towards item \(i\) and (ii) the assortment effect from \(\mathcal{S}.\) The interaction from the subset \(\mathcal{C}^{\prime}\) can be viewed as a candidate interaction effect, while the interaction from \(\mathcal{S}\) can be viewed as a background contextual effect. This decomposition provides intuition for why the TCNet architecture is suitable for the choice modeling task: the assortment encoder encodes the global contextual effect from \(\mathcal{S}\), and the candidate encoder encodes the local candidate interaction effect. Theoretically, this utility decomposition also provides a guarantee on the model expressiveness of TCNet for the choice modeling task as follows. **Theorem 2**.: _Any sequential choice model can be represented by a Transformer Choice Net. Specifically, for any sequential choice model defined by (2), there exists a Transformer Choice Net \(f^{\text{TCN}}\) such that_ \[\mathbb{P}(i|\mathcal{C},\mathcal{S})=f_{i}^{\text{TCN}}(\mathcal{C},\mathcal{ S})\] _holds for all \(i\in\mathcal{C},\mathcal{C}\subseteq\mathcal{S}\) and \(\mathcal{S}\subseteq\mathcal{N}\)._ The proof is deferred to Appendix A. It is inspired by (Lee et al., 2019) which proves the approximability of the Transformer Set for the permutation invariant function family (but not the permutation equivariant needed here for choice modeling). Combined with our discussion in SS3, we yield the following result. **Corollary 1**.: _Any single-choice model or multi-choice model can be represented by a Transformer Choice Net._ Numerical Experiments In this section, we present numerical experiments to demonstrate the performance of TCNet. Then we give visualizations and interpretations of the learned TCNet. ### Numerical Performance on Real Datasets We evaluate TCNet's performance against multiple benchmark models for the three choice modeling tasks we consider in this paper: single-choice, sequential choice, and multi-choice. We emphasize that for all the models and datasets, we use a single architecture of TCNet to showcase its power of "one-size-fits-all". Each experiment is conducted 5 times, with training, validation, and test data randomly split at ratios of \(60\%,20\%,\) and \(20\%\), respectively. The reported numbers are based on the average values over the test data, accompanied by the standard deviations. Further details on the datasets, the implementation, and the hyperparameter tuning are given in Appendix B. **Single-choice prediction.** We use the cross-entropy (CE) loss (6) to train the TCNet and also as the performance metric to report the test performance in single-choice prediction. We compare the TCNet against several benchmark models: DeepMNL (Wang et al., 2020; Sifringer et al., 2020), AssortNet (Wang et al., 2023), SDANet (Rosenfeld et al., 2020), FATENet (Pfannschmidt et al., 2022), Mixed-MNL (McFadden and Train, 2000), and DLCL (Tomlinson and Benson, 2021). These benchmarks represent the state-of-the-art methods of single-choice modeling. Our experiment includes the public datasets used in these existing works: Car (McFadden and Train, 2000), Sushi (Kamishima, 2003), Expedia(book), Hotel (Bodea et al., 2009), SFwork and SFshop (Koppelman and Bhat, 2006); as well as two private datasets Flight, and Retail. **Sequential choice prediction.** We also use the CE loss as the training objective and the performance metric in sequential choice prediction. We consider two public datasets commonly used in existing works: Expedia(click) and Bakery. These two datasets are originally multi-choice datasets without purchasing sequence information. We transform them into the sequential choice data by a method described in Appendix B. Though several algorithms are developed for sequential choice prediction, their limitations make them inapplicable with these specific datasets. As a result, for benchmarking purposes, we formulate sequential choice prediction as a single-choice prediction problem and utilize the above-mentioned benchmark models. Specifically, for a sequential choice dataset denoted as \(\mathcal{D}=\{(i_{k},\{\mathcal{C}_{k},\mathcal{S}_{k}\}),k=1,...,m\}\), we drop \(\mathcal{S}_{k}\) and recast it as a single-choice dataset: \(\mathcal{D}=\{(i_{k},\mathcal{C}_{k}),k=1,...,m\}\) for both the training and testing of the single-choice benchmark models. In essence, these models predict a single-choice from the candidate set \(\mathcal{C}\) as the assortment and omits the original assortment \(\mathcal{S}\), which may cause the information from what have been chosen unavailable (i.e., the assortment context) and only focus on modeling the candidates effect. To assess the implications of overlooking the assortment context, we train two variants of the Transformer Choice Net: TCNet(Var) and TCNet, where "Var" denotes the variant version. The former is trained as the single-choice model based on the above method while the latter is trained by minimizing the CE loss (6) over the original sequential choice dataset. **Multi-choice prediction.** We adopt the F1 score loss as the performance metric for multiple choices prediction, in line with the approach in (Pfannschmidt et al., 2022). Given the dataset \(\mathcal{D}=\{(\mathcal{B}_{k},\mathcal{S}_{k}),k=1,\ldots,m\}\), the F1 score loss is defined by \[L_{\text{F1}}=1-\frac{2}{m}\sum_{k=1}^{m}\frac{|\tilde{\mathcal{B}}_{k}\cap \mathcal{B}_{k}|}{|\tilde{\mathcal{B}}_{k}|+|\mathcal{B}_{k}|}.\] Here, \(\mathcal{B}_{k}\) represents the algorithm's predicted multiple choices. This loss provides a balanced measure of model performance on imbalanced datasets, which is the case for most choice modeling data (far fewer chosen item(s) than unchosen ones). We focus solely on the Expedia dataset here. The Bakery dataset, due to its consistent assortment and unvarying item features, results in identical multi-choice predictions across all samples when deterministic prediction methods are employed which renders it unsuitable for algorithmic comparison. As discussed in SS2, models designed for multiple choices become computationally expensive with increasing assortment sizes. Following the strategy in (Pfannschmidt et al., 2022), we adopt several single-choice models for multi-choice prediction: if an algorithm can produce interim utilities, \(u_{i}^{\mathcal{S}}\) for each item \(i\) within assortment \(\mathcal{S}\), then the item's choice probability is \(\frac{\exp(u_{i}^{\mathcal{S}})}{1+\exp(u_{i}^{\mathcal{S}})}.\) And resultant predicted multiple choices are \[\left\{i\in\mathcal{S}:\frac{\exp(u_{i}^{\mathcal{S}})}{1+\exp(u_{i}^{\mathcal{ S}})}>\mu\right\} \tag{9}\] Here, the threshold \(\mu\) is a tunable hyperparameter. In this case, the training loss remains the CE loss, yet is applied to each item's choice outcome independently. We use TCNet to denote the TCNet trained by the method discussed in SS3.2 and use TCNet(Var) as the one trained by the above method. **Results.** The performances on the test sets across all the experiments are summarized in Table 2. The Transformer Choice Net (TCNet) exhibits superior performance across all three tasks and datasets. One interesting observation is about the sequential choice prediction on the Bakery data: the TCNet(Var), which is trained without feeding the assortment information outperforms the standard TCNet, which enjoys the assortment information. One explanation is that the uniformity of assortments in all Bakery data samples allows an implicit encoding of this invariant assortment information. Conversely, in the Expedia(click) dataset, where assortments largely vary across samples, the provision of the additional assortment information appears beneficial, enhancing the performance of the standard TCNet. Also, as noted in the last section, the TCNet has a comparable number of parameters as the benchmark networks, so its advantage should be attributed to its explicit modeling of the item interaction. ### Probing into the Representation of TCNet We train a TCNet on the Bakery dataset which contains a total of 50 items, including food (e.g., cakes with different flavors, and snacks like cookies) and drinks (e.g., different coffees). The original dataset contains 4 item features. However, we train the model without these features and only use a one-hot encoding for each item. We then extract the latent features of each product from the assortment encoder and do linear probing (Belinkov, 2022) of the model through running linear logistic regression for two tasks: (1) identify cakes from snacks; (2) identify drinks from food. Due to the limited space, we only show the first here and defer the second to the Appendix. \begin{table} \begin{tabular}{c c|c|c|c|c|c|c|c|c} \hline Task & Data & TCNet & TCNet(Var) & DeepMNL & AssortNet & SDANet & FATENet & Mixed-MNL & DLCL \\ \hline \multirow{8}{*}{Sin.} & Car & **1.517\(\pm\)**0.026** & - & 1.578\(\pm\)0.013 & 1.585\(\pm\)0.032 & **1.517\(\pm\)**0.026 & 1.521\(\pm\)0.024 & 1.579\(\pm\)0.029 & **1.517\(\pm\)**0.025 \\ & Sushi & **1.747\(\pm\)**0.011 & - & 1.789\(\pm\)0.007 & 1.491\(\pm\)0.016 & **1.747\(\pm\)**0.013 & 1.750\(\pm\)0.010 & 1.764\(\pm\)0.008 & 1.763\(\pm\)0.007 \\ & Expedia(hook) & **2.314\(\pm\)**0.021 & - & 2.408\(\pm\)0.014 & 2.389\(\pm\)0.021 & 2.328\(\pm\)0.020 & 2.350\(\pm\)0.019 & 2.351\(\pm\)0.020 & 2.340\(\pm\)0.017 \\ & Hotel & **0.778\(\pm\)**0.008 & - & 1.321\(\pm\)0.014 & 0.851\(\pm\)0.008 & **0.778\(\pm\)**0.006 & 0.803\(\pm\)0.006 & 0.882\(\pm\)0.004 & 0.885\(\pm\)0.003 \\ & SFwork & **1.539\(\pm\)**0.031 & - & 1.902\(\pm\)0.167 & 1.667\(\pm\)0.026 & 1.542\(\pm\)0.027 & 1.570\(\pm\)0.033 & 1.664\(\pm\)0.022 & 1.683\(\pm\)0.014 \\ & SFshop & **0.821\(\pm\)**0.006 & - & 1.265\(\pm\)0.140 & 0.928\(\pm\)0.024 & **0.821\(\pm\)**0.010 & 0.831\(\pm\)0.015 & 0.909\(\pm\)0.022 & 0.894\(\pm\)0.011 \\ & Flight & **0.412\(\pm\)**0.007 & - & 2.819\(\pm\)0.051 & 2.751\(\pm\)0.049 & 0.427\(\pm\)0.007 & 0.477\(\pm\)0.006 & 0.476\(\pm\)0.005 & 0.477\(\pm\)0.006 \\ & Real & **0.982\(\pm\)**0.021 & - & 1.429\(\pm\)0.073 & 1.032\(\pm\)0.008 & 0.992\(\pm\)0.022 & 0.996\(\pm\)0.023 & 0.997\(\pm\)0.023 & 0.997\(\pm\)0.023 \\ \hline \multirow{2}{*}{Seq.} & Bakery & 2.738\(\pm\)0.024 & **2.710\(\pm\)**0.029 & 3.817\(\pm\)0.006 & 2.767\(\pm\)0.016 & 2.729\(\pm\)0.009 & 3.808\(\pm\)0.006 & 3.557\(\pm\)0.001 & 3.811\(\pm\)0.006 \\ & Expedia(click) & **2.863\(\pm\)**0.017 & 2.890\(\pm\)0.023 & 2.913\(\pm\)0.020 & 2.922\(\pm\)0.015 & 3.067\(\pm\)0.023 & 2.974\(\pm\)0.023 & 2.924\(\pm\)0.024 & 2.937\(\pm\)0.012 \\ \hline Mul. & Expedia(click) & **0.576\(\pm\)**0.005 & 0.583\(\pm\)0.003 & 0.659\(\pm\)0.003 & 0.653\(\pm\)0.005 & 0.593\(\pm\)0.002 & 0.639\(\pm\)0.005 & - & - \\ \hline \end{tabular} \end{table} Table 2: Test performances (\(\downarrow\)) on three tasks: single-choice (Sin.), sequential choice (Seq.), and multi-choice (Mul.). Figure 2 showcases our results: Figure 1(a) shows the predicted probabilities to be the cake, and Figure 1(b) uses t-SNE (Van der Maaten and Hinton, 2008) to visualize the top-10 latent features with largest absolute coefficients from the logistic regression. Both figures are based on the testing samples. We note that the latent representation indeed has the ability to identify Cake from Snack, although this is not explicitly included as the feature (only implicitly encoded in the choice). This shows that by learning the choice model from customer behaviors, the latent features can uncover useful properties of items, such as their categories and characteristics. ### Attention Visualization The attention scores in TCNet across various attention sub-layers reveal the degree of "attention" allocated by the model to each item (whether from an assortment or candidates set) while processing a specific item of interest. Essentially, these scores give insights into the influences and correlations (such as substitutes) of items on the final choice prediction. Moreover, they can help to verify whether the model is concentrating on the important items as we expect. In this subsection, we visualize the attention scores from a trained TCNet as an example to demonstrate how we can understand and explain them. The TCNet is again trained on the Bakery dataset. Figure 3 shows two sets of self-attention scores (Figure 2(a) and 2(b)) and two cross-attention scores (Figure 2(c) and 2(d)) from the candidates encoders. We make the following observations: Comparing Figures 2(a) and 2(b), we can see Cake 1 and Cake 2 put extremely high weights on the lemonade in Figure 2(b) in contrast to the Cake 3 offered in Figure 2(a). This aligns with one's intuition when making the choice: Lemonade, as a drink, represents a new category differing from the other candidates and can impose a substantial influence on the final choice. For instance, a thirsty customer might randomly choose one cake in Figure 2(a) but will definitely choose the lemonade when it is offered as in Figure 2(b). In Figures 2(c) and 2(d), the first observation is consistent with the above: all three cakes assign substantial weights to Coffee 1, which is a drink, in both figures. Another observation is on the weight of Coffee 1: its weight on Coffee 2 in Figure 2(c) is double of that on the Pie in Figure 2(d). Given that both Coffee 2 and Pie are purchased items, this implies that buying Coffee 2 has a greater influence on choosing Coffee 1 than purchasing the Pie. This is reasonable, as consumers typically do not buy two coffees but may purchase a coffee alongside a pie. Figure 2: Probing the latent representation. In summary, examining the attention scores enables us to validate whether the model adheres to our common sense and allows us to get insights into the relationships between items. ## 7 Conclusion and Future Directions The existing literature on single-choice model, sequential choice model, and multi-choice model have been largely separate from each other: the current sequential choice models have there own limitations, and the current multi-choice models become impractical when dealing with a large assortment. While the research on single-choice models is vast, the literature on predicting sequential and multi-choice is noticeably less developed. Our paper introduces the Transformer Choice Net as a unified neural network framework capable of addressing all three types of choice behaviors. Notably, it is the first Figure 3: Candidates encoder’s (self) attention and cross-attention scores. For the second row, the side items are from candidates \(\mathcal{C}\) and the bottom items are from assortment \(\mathcal{S}\). Each row indicates the normalized attention scores for the side item. Transformer-based architecture tailored for choice(s) prediction tasks. We prove its universal representation capacity and, through extensive numerical experiments, demonstrate its superior performance over several benchmarks. We conclude with the following future directions. **Assortment optimization.** One important downstream application of choice prediction is assortment optimization, which optimizes the offered assortment to maximize the expected revenue for the seller. Given the Transformer Choice Net's strong prediction performance, an intriguing avenue to explore would be the optimization of assortment offerings for a trained Transformer Choice Net model. **Exploring alternative Transformer-based structures.** The Transformer architecture has increasingly shown its significance within the deep learning realm, showcasing its adaptability across diverse tasks. While the Transformer Choice Net represents an initial endeavor in integrating the Transformer framework into choice modeling, we believe there is still large potential in exploring other Transformer-inspired architectures.
2302.12239
What makes a language easy to deep-learn? Deep neural networks and humans similarly benefit from compositional structure
Deep neural networks drive the success of natural language processing. A fundamental property of language is its compositional structure, allowing humans to systematically produce forms for new meanings. For humans, languages with more compositional and transparent structures are typically easier to learn than those with opaque and irregular structures. However, this learnability advantage has not yet been shown for deep neural networks, limiting their use as models for human language learning. Here, we directly test how neural networks compare to humans in learning and generalizing different languages that vary in their degree of compositional structure. We evaluate the memorization and generalization capabilities of a large language model and recurrent neural networks, and show that both deep neural networks exhibit a learnability advantage for more structured linguistic input: neural networks exposed to more compositional languages show more systematic generalization, greater agreement between different agents, and greater similarity to human learners.
Lukas Galke, Yoav Ram, Limor Raviv
2023-02-23T18:57:34Z
http://arxiv.org/abs/2302.12239v4
# What makes a language easy to deep-learn? ###### Abstract Neural networks drive the success of natural language processing. A fundamental property of natural languages is their compositional structure, allowing us to describe new meanings systematically. However, neural networks notoriously struggle with systematic generalization and do not necessarily benefit from a compositional structure in emergent communication simulations. Here, we test how neural networks compare to humans in learning and generalizing a new language. We do this by closely replicating an artificial language learning study (conducted originally with human participants) and evaluating the memorization and generalization capabilities of deep neural networks with respect to the degree of structure in the input language. Our results show striking similarities between humans and deep neural networks: More structured linguistic input leads to more systematic generalization and better convergence between humans and neural network agents and between different neural agents. We then replicate this structure bias found in humans and our recurrent neural networks with a Transformer-based large language model (GPT-3), showing a similar benefit for structured linguistic input regarding generalization systematicity and memorization errors. These findings show that the underlying structure of languages is crucial for systematic generalization. Due to the correlation between community size and linguistic structure in natural languages, our findings underscore the challenge of automated processing of low-resource languages. Nevertheless, the similarity between humans and machines opens new avenues for language evolution research. Natural language processing Machine learning Language acquisition Language evolution ## 1 Introduction Fueled by deep learning [1, 2], natural language processing is becoming increasingly influential [3, 4, 5, 6, 7, 8]. In particular, large pretrained language models based on deep neural networks [5, 6, 9, 10], such as GPT-3 [7], have shown to be incredibly successful, even when generalizing to new tasks without being trained for them [7, 11]. Although these neural networks are not biologically plausible [12], an increasing body of work reports striking similarities to humans regarding their properties in natural language processing, including similarity in neural activity patterns [13] and similar biases in reasoning [14]. However, the role of linguistic structure in the input language is largely unknown, i. e., to what extent artificial neural networks generalize to new meanings in a systematic way and whether they make similar mistakes during memorization. Here, we investigate how the degree of systematic structure in a language affects the memorization and generalization capabilities of deep neural networks, small and large, and directly compare their performance to human learners. For humans, languages with more regular, compositional, and transparent structures are typically easier to learn compared to languages with opaque and irregular structures [15, 16, 17, 18]. This is because more structured languages allow learners to derive a set of generative rules rather than memorizing individual forms [19, 20]. While all languages are fully learnable in the long run, cross-linguistic variation in systematic structure, i. e., the degree to which grammatical rules are informative, productive, and clearly marked [21, 22, 23, 24, 25, 26, 27], can have important consequences for learning: some languages appear to be easier to learn than others, and human learners exposed to languages that are more morphologically opaque show slower learning trajectories and worse overall proficiency [28, 29, 30, 31, 32, 33, 34]. This pattern from real languages was recently confirmed in a large-scale experimental study with human participants, which used an artificial language learning paradigm to test the acquisition of a broad yet tightly controlled range of comparable languages with different degrees of systematic structures [32]. Results showed that languages with more systematic structures were indeed learned faster, better, and more consistently, and also promoted better generalizations and more robust convergence on new, unfamiliar forms. These findings have far-reaching implications not only for research on language acquisition but also for broader theories on language evolution in our species. However, whether this structure advantage carries over to computational learning systems in natural language processing is poorly understood. The central point we aim to establish here is: How similar are deep neural networks and humans in language learning? What makes a language easy to learn for deep learning models? In other words, do neural network architectures that have been successful in natural language processing tasks exhibit the same structure bias as humans do and benefit from more structured linguistic input when learning a new language? Answering these questions is crucial for two reasons. First, it reflects on a broader and long-standing debate on the similarity between humans and neural networks with respect to core cognitive functions such as learning, categorization, and abstraction across a wide range of research areas, e. g., language understanding [35, 36], language emergence [37], language acquisition [38, 39], reasoning [14], neural activity patterns [13], shape versus texture in computer vision [40, 41], catastrophic forgetting [42] in continual learning [43], i. e., forgetting all previous knowledge when trained for a new task, difficulties when generalizing out of the training distribution [44], systematic generalization in natural language processing [45, 46, 47], and the abilities of large language models that emerge at scale, such as tackling new tasks without further training [7, 11]. Second, answering these questions is crucial for simulating language evolution with neural networks [48, 49, 50, 51, 52, 53, 54, 55, 56]. In these simulations, deep neural networks start without any prior knowledge of the language, with no predefined vocabulary, and need to develop a language to solve a communication game. Although these simulations have great potential for advancing our understanding of how languages emerge, we can only expect insights gained with deep networks to inform studies of language evolution in our species if the resulting languages had the same properties as natural languages [57]. However, the properties of the emergent languages show crucial mismatches with human languages [58, 59, 60]. Specifically, it has been found that deep neural networks show no correlation between the degree of structure in the emergent language and the generalization capabilities of the networks [58, 60]. This finding stands in stark contrast to the compositional structure of human languages [61] and raises the question if systematic and compositional structure is helpful at all for deep neural networks--in the same way as it is for humans. Notably, popular models of language evolution directly attribute the emergence of systematic grammatical structures in human languages to the learnability and expressivity pressures operating during cross-generational transmission and communication [62, 63]. In particular, more systematic and predictable grammars are favored in the cultural evolution process exactly because they are learned better by novices and are advantageous for generalizations, seeing as they allow learners to overcome the poverty of stimulus and produce infinite utterances after exposure to just a finite set [19, 20, 64, 65, 66, 67, 68, 69, 70, 62, 64, 67, 69, 80, 62, 68, 64, 69, 90, 67, 68, 69, 70]. Here, we investigate this precise relationship between linguistic structure and generalization performance in language learning with deep neural networks and compare that to human language learning. We are interested in five aspects: First, how well can they memorize form-meaning pairs of the input languages? Second, how systematically do they generalize to new meanings? Third, to what extent do different neural network agents generalize in the same way? Fourth, to what extent do neural networks behave in the same way as humans (i.e., how similar are the machine-generated labels and the corresponding human-generated labels)? Lastly, do these patterns also hold for large language models like GPT-3? To answer these questions, we replicate a large-scale preregistered study on language learnability carried out with adult human participants [32]. That study tested the learnability of artificial languages created by participants in a previous group communication experiment [71]. The input languages vary in the degree of systematic structure they contain, i. e., ranging from completely unstructured languages with no grammatical rules, to languages with fully systematic and compositional mappings between meanings and labels. For example, one of the weakly structured languages uses moof for shape 1 moving upwards and wait for the same shape 1 moving towards the top left of the screen. In contrast, one of the highly structured languages uses tup-oo for shape 1 moving upwards (see Figure 1(_Left_)) and tup-oi for the same shape moving to the top left. In this highly structured case, labels contain a sub-part for describing the shape and a sub-part for describing the direction. In contrast, the two words in the unstructured language do not share a single character despite describing a scene with the same shape. In the learnability study, 100 human participants were randomly assigned to ten different input language conditions and then engaged in repeated learning blocks consisting of passive exposure, guessing trials, and production trials. After training, participants were tested on their knowledge of the input language in a memorization test (measuring their reproduction accuracy on learned items) and a generalization test (measuring their ability to produce labels for new, unseen items). We directly replicate this experimental setup with neural networks. Specifically, we use the same ten input languages and train 100 differently-initialized neural network models for each language, i. e., 10 per human participant. We carefully follow the humans experiment training protocols to mimic the learning objectives, procedures, and measures as closely as possible by training neural networks on the same stimuli presented to humans and in the same order, using the same learning tasks, and providing the same feedback during learning blocks. To simulate the previous study's exposure, guessing, and production blocks as closely as possible, we have designed a custom neural network architecture that combines generative and contrastive components (Figure 1). The architecture is inspired by image-captioning approaches [72], the emergent communication literature [51], and a recent review paper [57] which suggested having shared model parameters between generation and processing of a label. Our model consists of two components: a generative component that facilitates the production of a descriptive sequence of symbols (here, a label) for a scene and a contrastive component that shapes the latent space and enables the models to tackle guessing tasks (i.e., given a label, pick the correct scene from a set of distractors). Each component has its sequential module, the well-known long short-term memory [73], to carry out the generation and processing of a sequence, respectively. The two components share the symbol embedding that maps each symbol to a continuous vector and an encoder module that transforms an input scene into a latent representation. Production tasks are modeled by a generative objective: the model generates a label, character by character. This generated label is compared to the target input language by character-level cross-entropy. Guessing tasks are modeled by a contrastive objective [74], which aligns the representations of input scenes and corresponding labels and facilitates selecting the correct scene from a set of distractors. We then evaluate the neural networks' learning and generalization performance using the same metrics used for humans and compare the labels produced by networks to the ones produced by humans in terms of edit distance. To preview our results, we found that neural networks display the same structure bias as humans: Neural networks trained on more structured languages generalized more systematically to new scenes, and their produced labels were more similar to those produced by humans--for both meanings in the training set and new meanings. Moreover, different neural network models are more likely to converge to the same generalization when there is more structure in the input language. In addition, we show that GPT-3, a large language model based on the Transformer architecture [4], also displays the same structure bias as humans and as our custom architecture based on recurrent neural networks. ## 2 Results The language learning capabilities of neural networks were evaluated with a memorization test and a generalization test following each training round. The memorization test included the production of labels for the 23 scenes that were part of the training data. In contrast, during generalization, networks needed to produce labels for 13 new scenes Figure 1: Overview of exemplary input data _(Left)_, the experimental procedure _(Center)_, and model architecture _(Right)_. Figure 2: **Neural Networks’ memorization and generalization performance**. More structured languages lead to better and faster reproduction of the input language (a), to better generalization on unknown scenes (c), better agreement with human participants during memorization (b) and generalization (d), and higher convergence between networks (e). **(A)** Production similarity between labels generated by neural agents and labels of the input language. **(B)** Production similarity between labels generated by neural agents and labels generated by human participants. **(C)** Generalization score of labels generated by neural agents for new scenes that were not part of the training data. **(D)** Production similarity between labels generated by neural agents and labels generated by human participants for unseen scenes. **(E)** Convergence score measures the similarity between labels generated for unseen scenes by different neural agents. Stars mark the round at which neural agents first exceed the final performance of human participants. Input languages are grouped into 5 bins. Each line is the average of 200 neural agents with a different random initialization. A star marks the epoch at which the NN agents exceed human performance. Results are cut off for visualization at epoch 60. that were not a part of the training data. For each of the 100 agents trained on each of the ten input languages, we calculated the following measures after each of the 100 rounds: the similarity between networks' productions and the input language; the similarity between networks' productions and the human learners' productions during memorization and generalization; a generalization score capturing the degree of systematic generalization [32]; and a convergence score capturing the agreement between different agents. The results are shown in Figure 2. In the following, we present the results for the learning trajectory organized along the two types of tests: memorization and generalization. Subsequently, we compare the generalization systematicity of the large language model GPT-3 with the final generalization systematicity of our neural network agents and that of humans. Lastly, we conduct an error analysis of the imperfect reproductions in the final memorization test to investigate to what extent the mistakes are affected by the structure. ### Memorization How well did neural agents memorize the input languages? And how similar were their generated labels to those produced by human learners? This is measured by production similarity [32], which captures the similarity between the original label and the produced label by calculating the average normalized edit distance between two labels for the same scene. We use this measure in two ways: once to compare the generated labels to the true label of the input language and once to compare the machine-generated label to the human-generated label for the same scene. Similarity to Input Languages during MemorizationWith sufficient training rounds, all languages can be learned by all neural agents, reaching a production similarity of at least 0.8 (out of 1) by round 60 (Figure 2A). Structured languages are learned significantly better (LME 1; \(\beta=0.045\), \(\mathrm{SD}=0.001\), \(z=62.865\), \(p<0.001\)), i. e. they show a higher similarity with the input language. However, this advantage tends to diminish over training rounds (LME 1; \(\beta=-0.005\), \(\mathrm{SD}<0.001\), \(z=-54.978\), \(p<0.001\)). Similarity to Humans during MemorizationWe measured the similarity between the human memorization data (i. e. their productions at test time after completing the training rounds) and the memorization test data of the neural network agents after each training round (Figure 2B). Structured languages led to a significantly greater similarity with human learners (LME 2; \(\beta=0.097\), \(\mathrm{SD}=0.001\), \(z=81.429\), \(p<0.001\)). This effect became even stronger over rounds (LME 2; \(\beta=0.022\), \(\mathrm{SD}=0.000\), \(z=208.708\), \(p<0.001\)). ### Generalization We evaluate the productions of neural agents when they generalize, i. e., produce labels for new scenes that were not part of the training data. We test the productions regarding three aspects: the degree of systematicity, the similarity to humans, and the generalization convergence between different agents. Generalization SystematicitySystematicity is the degree to which similar scenes are described by similar meanings, as measured by the generalization score [32]. In the generalization test, there is no true label in the input language. The generalization score thus correlates the pairwise label difference and the pairwise semantic difference between the labels generated for new scenes and the labels generated by the same agent for known scenes, reflecting the degree to which new labels conform to the labels of the input language. More structured languages consistently led to significantly higher generalization scores (Figure 2C) (LME 3; \(\beta=0.088\), \(\mathrm{SD}=0.001\), \(z=148.901\), \(p<0.001\)), and this effect became stronger with time (\(\beta=0.046\), \(\mathrm{SD}<0.001\), \(z=703.483\), \(p<0.001\)). Similarity to Humans during GeneralizationWe measure the similarity between the productions of neural agents and humans for new scenes (Figure 2D), i. e. during generalization. More structure in the input language led to a significantly higher similarity between humans and neural agents (LME 5; \(\beta=0.132\), \(\mathrm{SD}=0.002\), \(z=70.280\), \(p<0.001\)), which became stronger over rounds (\(\beta=0.046\), \(\mathrm{SD}<0.001\), \(z=344.287\), \(p<0.001\)). Table 1 shows examples of generated labels. Convergence between Networks during GeneralizationMore structured languages lead to better agreement between networks (LME 4; \(\beta=0.043\), \(\mathrm{SD}=0.001\), \(z=49.027\), \(p<0.001\)), such that, for more structured languages, different neural agents learning the same input language produced more similar labels for new scenes (Figure 2E). This effect became stronger over rounds (\(\beta=0.009\), \(\mathrm{SD}<0.001\), \(z=121.740\), \(p<0.001\)). ### Comparison with a Large Language Model (GPT-3) We tested how well a large language model, the GPT-3 model text-davinci-003, performs on our input language. We compared its produced labels to the final productions of humans and our neural network agents. Strikingly, the results reveal that higher structure leads to more systematic generalization in all cases (Figure 3). Table 1 shows examples of the final productions of humans, our recurrent neural networks, and large language models in the generalization test. Memorization Error AnalysisWe seek to understand better whether the memorization errors of humans and neural networks are similarly affected by the structure. Therefore, we analyze the cases where the learning systems fail to \begin{table} \begin{tabular}{l c c c c c} \hline \hline **Struct.** & **Shape** & **Angle** & **Human** & **RNN** & **GPT-3** \\ \hline low & 2 & 360 & kokoke & seefe & tik-tik \\ & 4 & 45 & woti & kite & hihi \\ & 3 & 150 & priu & mimi & hihi \\ \hline mid-low & 3 & 225 & wangsuus & wangsoe & wangsuus \\ & 4 & 225 & gntsoe & gntuu & gntsi \\ & 1 & 135 & sketsi & gesh & geshts \\ \hline mid & 3 & 60 & powi & powu-u-u & powee \\ & 4 & 330 & fuottoa & fuotio & fuottu-u-u \\ & 1 & 30 & fewo-o-o-o & fewen & fewee \\ \hline mid-high & 1 & 30 & fas-a & fas-a & fas-a \\ & 3 & 360 & muif-i & muif-a & muif-i \\ & 1 & 225 & fas-huif & fas-huif & fas-huif \\ \hline high & 4 & 60 & smut-tkk & smut-tk & smut-ttk \\ & 2 & 360 & nif-k & nif-kks & nif-k \\ & 1 & 315 & wef-ks & wef-kks & wef-kks \\ \hline \hline \end{tabular} \end{table} Table 1: Generalization examples from neural and human learners, showing labels generated for unseen scenes. The column GPT-3 corresponds to completions generated by the GPT-3 model text-davinci-003 via in-context learning, where the training data is provided in context. The examples cover the differently structured input languages from low to high. Figure 3: Comparison of the final generalization score achieved by 10 humans _(Left)_, 100 recurrent neural networks _(Center)_, and GPT-3 _(Right)_ for each of the input languages. The x-axis shows the structure score of the input languages. Error regions show 95% confidence intervals estimated via bootstrapping. memorize the correct label perfectly. We compare the final memorization test results of humans, our custom neural networks, and GPT-3. The results show the same pattern for all three learning systems (Figure 4): When there is more structure in the input language, the non-perfectly memorized productions are still more similar to the correct labels. ## 3 Discussion Main FindingsOverall, our results show that neural networks benefit from more structured linguistic input in the same way humans do, and that neural networks' performance becomes increasingly more human-like when trained on more structured languages. This structure bias can be found in networks' learning trajectories and even more so in the networks' generalization behavior, mimicking previous findings with humans. Although all languages can eventually be learned, we show that more structured languages are learned better and with greater similarity to human productions. Networks and humans produce nearly identical labels when trained on high-structured languages but not when trained on low-structured languages. Moreover, networks that learn more structured languages are significantly better at systematic generalization to new, unseen items, and crucially, their generalizations are significantly more consistent and more human-like. This means that highly systematic grammars allow for better generalization and facilitate greater alignment between different neural agents as well as between neural agents and humans. We replicate these results with small recurrent neural networks and with transformer-based large language models, showing that, together with humans, all three learning systems show the same bias in systematic generalization and memorization errors. Thus, our findings add to the increasing evidence of similarity in language learning between humans and machines [13, 75, 76, 77, 78], which strengthen the idea that language models are useful for studying human cognitive mechanisms. For example, our findings support using language models' estimated probabilities as surprisal scores in psycholinguistics studies [79, 80, 81]. ImplicationsFirst and foremost, our findings support a usage-based view of language learning: languages' underlying grammatical structure can be learned directly from the available linguistic input [82, 83], without the need to assume innate knowledge or a universal grammar [84]. Our findings have further implications for natural language processing, where systematic generalization is of high interest [45, 46, 47]. Specifically, we show that seeding models with well-structured inputs can improve the generalization capabilities of the learning system. Even though our study is based on artificial languages, our findings directly pertain to the natural language processing of real-world languages. To confirm this prediction, we reanalyzed data from Wu et al. [85], who used the Wug Test [86] to test language models' ability to predict different forms of unfamiliar words in a wide range of natural languages. Indeed, we find that the Wug Test accuracy negatively correlates with the degree of irregularity of the language (Spearman's \(\rho=-0.96\), \(p<10^{-15}\); Kendall's \(\tau=-0.86,p<10^{-14}\)). Figure 4: Memorization error analysis for human participants _(Left)_, recurrent neural networks _(Center)_, and GPT-3 _(Right)_. The error rates are 33.30% for humans, 13.87% for NNs, and 7.39% for GPT-3. The x-axis shows the structure score of the input language. Error regions show 95% confidence intervals estimated via bootstrapping. This strong negative correlation suggests that natural languages with fewer irregularities, i. e. more structured natural languages, are indeed easier to learn. Moreover, our results have direct implications for the natural language processing of low-resource languages, i. e. languages for which there is only very little training data available. Low-resource languages are typically spoken by smaller communities, and cross-linguistic and experimental work shows that such languages typically have less structured languages with more irregularities [87, 88, 89, 90]. Since our study predicts that more structured natural languages would be easier to learn than less structured ones, this would result in a double whammry for natural language processing of small communities' languages: Not only is fewer data available for languages spoken by smaller communities but also these languages tend to be harder to learn for machine learning models due to their tendency of having a lower degree of structure. Finally, our results are of high relevance to the field of emergent communication, which simulates the evolution of language with multi-agent reinforcement learning [48, 49, 50, 51, 52, 53, 54, 55, 56]. As argued in the introduction, certain linguistic phenomena of natural language appear to be hard to replicate with multi-agent reinforcement learning [57, 58, 59, 60], which raises the question whether compositionality is helpful for neural networks at all. We hypothesize that these mismatches are caused by the lack of cognitive constraints [57] eradicating the learnability pressure that underlies human language evolution [62]. Previous work has already shown that, by introducing an artificial learnability pressure, the advantage of structured languages can be restored [50, 52, 54]. This leaves us with the _hypothesis_ that structured languages are easier to learn for deep networks. Our results confirm this hypothesis for recurrent neural networks and GPT-3 as a transformer-based large language model. We find that more structured languages lead to more systematic generalization, more agreement between different networks, and more similarity to humans. Therefore, our findings support the importance of a learnability pressure for compositional languages to emerge. By replicating a result previously found in humans [32] with neural network agents, we take the first steps to bring emergent communication closer to the field of language evolution, supporting the computational modeling of language evolution with neural networks. Limitations and Future WorkOne potential limitation of our work is that we had to make certain decisions about the neural network architecture design, optimization procedure, and hyperparameters. All these decisions may impact the results. However, we have varied all relevant hyperparameter settings and found that the results are robust to specific settings (see Supporting Information). Another potential caveat is that we used a simplified input representation for the neural networks: while humans saw videos of shapes moving in a direction, our neural agents received an attribute vector that disentangles key features. Since pixel input would be more challenging (as neural networks would first need to learn disentangled representations themselves [91]), here we focused on the ability of systematic generalization in language learning rather than the ability to learn disentangled representations. The latter is a long-standing endeavor in deep learning research [92, 93, 94], and future work can incorporate an appropriate vision module as the encoder for input scenes. Lastly, we have intentionally limited this study to purely supervised learning in order to shed new light on the relationship between language structure and the generalization performance of neural network models. In future work, we intend to extend the present results by analyzing how such neural network models engage in a collaborative communication game in which they are made to invent a new communication protocol. ## 4 Conclusion Our findings shed light on the relationship between language and language-learning systems, showing that linguistic structure is crucial for language learnability and systematic generalization. More structured languages are easier to learn, regardless of the learning system: a human participant, a small recurrent neural network model, or a large language model. Thus, generalization capabilities are heavily influenced by language structure, with both biological and artificial learning systems benefiting from more structured input by facilitating more systematic and transparent generalizations. ## 5 Materials and Methods ### Materials Input LanguagesThe input languages come from a previous communication study in which groups of interacting participants took turns producing and guessing labels for different dynamic scenes, creating new artificial languages over time [90]. The final languages created by these groups then served as input languages for a follow-up study on language learnability with humans [32]. For our experiments, we used the same ten input languages. These input languages are considered the ground truth. Each of the ten input languages contains a set of 23 label-scene mappings. Each scene is composed of one of four different shapes moving in different directions between 0 and 360 degrees. Crucially, the ten input languages have different degrees of structure, ranging from languages with no structure to languages with consistent, systematic grammar. Each language has a structure score represented by topographic similarity [95], quantifying the degree to which similar labels describe similar meanings. The topographic similarity is measured as the correlation between all labels' pairwise length-normalized edit distances and their corresponding pairwise semantic differences. The semantic difference between two scenes is calculated as the sum of the difference in shape and the difference in angles [32]. The difference in shape is zero if the two scenes contain the same shape, and one otherwise. The difference in angles is calculated as the absolute difference divided by 180. The topographic similarity of a language is then calculated as the pairwise correlation between all semantic differences and all normalized edit distances. Human Learning DataAside from the input languages, we have data from 100 participants who learned these input languages. These participants are different from the participants who created the languages. A hundred participants, ten per input language, engaged in repeated learning blocks consisting of passive exposure (in which the target label-meaning mappings were presented on the screen one by one), guessing trials (in which participants needed to pick the right scene from a set of possible distractors), and production trials (in which participants needed to generate a descriptive label for a target scene based on what they had learned). During training, humans received feedback on their performance. Input RepresentationThe scenes were shown to human participants as short videos [32]. For the neural agents, we use a simplified input representation for the scenes: a one-hot encoding of the shape concatenated with a sine and a cosine transformation of the angle. The sine-cosine transformation promotes a similar treatment of angles that are close to each other, while each unique angle can be distinguished. For example, shape 2 (between 1 and 4) moving at a 90-degree angle is converted to a vector \((0,1,0,0,1,0)\), shape 3 with 45 degrees is converted to \((0,0,1,0,0.71,0.71)\), and shape 4 with 135 degrees is converted to \((0,0,0,1,0.71,-0.71)\). We refer to the resulting 6-dimensional vector representation of the input as a scene \(\mathbf{x}\). ### Methods Neural Network Architecture Generative ComponentThe input scene \(\mathbf{x}\) is encoded to a latent representation \(\mathbf{h}\) by Encoder, a feedforward network (i.e., multilayer perceptron), such that \(\mathbf{h}=\textsc{Encoder}(\mathbf{x})\). This latent representation \(\mathbf{h}\) is then used as the initial state of a recurrent generative network Writer. The Writer sequentially produces a label, a sequence of characters, as the output. This Writer consists of three modules: an input embedding for previously produced characters, a long short-term memory cell [73], and an output layer that produces the next character. Contrastive ComponentFor the exposure and guessing tasks, we have another recurrent module Reader that reads a label \(\mathbf{m}\) sequentially (i. e., character by character) while updating its state. A feedforward layer then transforms the final state into a latent representation \(\mathbf{z}\), such that \(\mathbf{z}=\textsc{Reader}(\mathbf{m})\). These reading components are used for contrastive learning, i. e. they are trained so that the hidden representation of the label \(\mathbf{z}\) matches the representation of the corresponding scene \(\mathbf{h}\), which is used as the initial hidden state of the generative Writer module. Shared ParametersTo ensure that the contrastive training procedure affects the generative component, we couple the two components: First, the embedding (i. e., the mapping between the agent's alphabet and the first latent representation) parameters are shared between the input layer of Reader, the input layer of Writer, and the output layer of Writer. Second, the same encoder module is used in both the generative and the contrastive components (see Figure 1). HyperparametersThe output dimension of Encoder, the hidden state sizes of Reader and Writer, and the embedding size are all set to 50. Training Procedure We train the model for multiple training rounds: as in human experiments [32], each training round consists of three blocks: exposure, guessing, and production block, described in detail in the following. As typical in neural network training, we train the network with backpropagation and stochastic gradient descent, where the gradient is estimated based on a small number of examples (minibatches) [96, 2]. The batch size is set to 5, except for the guessing block, in which we use a batch size of 1. Exposure BlockIn the exposure block, human participants were exposed to scenes with the corresponding target labels. Therefore, we train the deep learning models using a loss function with two terms: a generative and a contrastive loss term. The generative loss, \(\mathcal{L}_{\mathrm{gen}}\), is a tokenwise cross-entropy with the ground-truth label of the original language. The contrastive loss, \(\mathcal{L}_{\mathrm{con}}\), promotes similar latent representations of scenes and labels that correspond to each other and contrasts representations that do not. Specifically, we use the NTXent loss [74]. We use other scenes in the same batch as distractors for the contrastive loss. The final loss function is \(\mathcal{L}=\mathcal{L}_{\mathrm{gen}}+\alpha_{\mathrm{con}}\mathcal{L}_{ \mathrm{con}}\). The factor \(\alpha\) determines the relative weight of the loss terms. For the main experiment, we use \(\alpha=0.1\). We used a batch size of 5 to reflect human short-term memory constraints [97]. Guessing BlockIn the guessing block, we use the same loss function as in the exposure block. The contrastive loss term \(\mathcal{L}_{\mathrm{con}}\) mirrors the task in which human participants had to select the correct scene against the distractors given a label. The generative loss term \(\mathcal{L}_{\mathrm{gen}}\) is used so that the model does not "forget" how to generate [98]. Again, we use the same factor \(\alpha_{\mathrm{con}}=0.1\) to weight the loss terms. In more detail, the latent representation \(\mathbf{z}=\textsc{Encoder}(\mathbf{x})\) of the scene \(\mathbf{x}\) should be closest to the latent representation \(\mathbf{z}^{\prime}=\textsc{Reader}(\mathbf{m})\) of the corresponding label \(\mathbf{m}\). The difference from exposure training is that in the guessing block, we use the identical distractors used in experiments with humans, whereas, in the exposure block, we use the other scenes from the same batch. Production BlockIn the production block, a scene was presented to human participants, who had to produce a label. We again use the same generative loss as in the previous block, \(\mathcal{L}_{\mathrm{gen}}\), to model the production block. In the production block, however, we omit the contrastive loss term and train only on generation. Thus, the loss function is \(\mathcal{L}=\mathcal{L}_{\mathrm{gen}}\). Initialization and OptimizationThe parameters are randomly initialized by _He initialization_[99], the default in PyTorch [100]. We employ the widely used _Adam optimizer_[101] to optimize the loss function with the default learning rate of \(10^{-3}\). ### Measures and Evaluation Following experiments with human participants [32], we tested memorization and generalization. In the memorization test, we have neural agents produce labels for scenes that were part of the training data. In the generalization test, we have neural agents produce labels for scenes they have never seen, i. e., not in the training data. We performed these tests after each of the 100 rounds. To account for the random effects of the parameter initialization and training procedure, we ran 100 experiments with different random seeds for each input language. The measures are described in the following. Production SimilarityProduction similarity measures the overlap between two sets of labels. It is computed as one minus the normalized edit distance between pairs of labels. For our analysis, we use production similarity once to quantify the similarity between the generated labels and the ground truth of the input languages, and once to quantify the similarity of labels generated by neural network agents with labels produced by human learners. Generalization ScoreThe generalization score measures the degree of systematicity during the generalization test [32]. We take two sets of scenes: a training set, on which the agents were trained, and a test set, on which the agents were not trained. We then do the following for each agent. First, we take two sets of labels: one previously generated for each training scene by the agent and another that we let the agent generate for each test scene. Second, the difference between train and test scenes is measured by pairwise semantic difference. Semantic difference is calculated as described above under Input Languages. Third, the difference between train and test labels is measured by pairwise normalized edit distance. Finally, we compute the Pearson correlation between these two differences across all scenes. Then, we take the average correlation coefficient across all agents as the generalization score. Convergence ScoreThe convergence score measures the similarity in the generalization test between agents that learned the same language. We take a test set of scenes on which the agents have not been trained and let each agent produce a label for each scene. We compute the pairwise normalized edit distance between all generated labels per scene so that if we have \(n\) test scenes and \(k\) agents, we compute \(n\cdot\frac{k(k-1)}{2}\) distances. We then compute the average distance across both scenes and labels and take one minus the average distance as the convergence score. Therefore, if all agents produce the same label for each test scene, we would get a convergence score of 1. ### Large Language Models We use the following procedure to generate the results of large language models. We employ GPT-3 [7] (version text-davinci-003), or Generative Pre-trained Transformer, an autoregressive language model trained to predict the next token in a sequence of tokens using web-scale text data. GPT-3 is capable of few- and zero-shot learning. This means that only a few examples are sufficient for GPT-3 to tackle a new task. This ability, sometimes referred to as in-context learning, allows us to evaluate GPT-3's performance on our object description task without the need for fine-tuning. Thus, we supplied the training data of the respective input language to GPT-3: 23 shape, angle, and word triples. These 23 lines were followed by a single line, with only shape and angle, and GPT-3 was asked to predict the corresponding word. In the memorization task, the target word appears at an earlier location in the training data, which means that the perfect solution is to choose this word. In the generalization task, we gave GPT-3 a combination of shape and angle that is not present in the training data. The model generated the most likely descriptive word for the new shape and angle pair. We had to make certain technical choices when using GPT-3. First, we chose not to supply an instructive description of the task because GPT-3 is sensitive to varying input. Second, we set the sampling temperature to zero, which controls the randomness of the generation, such that we obtain deterministic generations. Third, we do not impose any restrictions on the characters that can be generated but rely on its ability to detect this from the training data. Fourth, we do not feed GPT-3 its previous predictions for memorization or generalization. Lastly, GPT-3's tokenization procedure (how text is split into subword tokens) could have been problematic for applying it to our artificial languages. However, we found that GPT-3 still reaches high memorization performance, which suggests that tokenization is not a problem. ### Statistical Analyses For each of the ten input language, we trained 100 differently-initialized neural network models over 100 rounds. The testing in each round consisted of 23 memorization and 13 generalization examples. This makes a total of 2.3M memorization and 1.3M generalization test results subject to statistical analyses. Significance was tested using linear mixed-effects models, as implemented in the Python package statsmodels [102], for production similarity (LME 1), generalization score (LME 3), generalization convergence (LME 4), as well as production similarity to humans in memorization (LME 2) and generalization (LME 5). We use the structure score and the logarithmized round number in all measures as a fixed effect. The number of rounds was logarithmized in accordance with the scaling laws of neural language models [103]. Both the structure score and the logarithmized round number were centered and scaled As random effects, all statistical models use the random seed that was used for random initialization, which also determines the input language, and the specific scene. to unit standard deviation. For LME 5, scaling the log-transformed round number to unit variance hindered convergence, so the log rounds were only centered. AcknowledgementsWe thank Yosef Prat, Tal Simon, Mitja Nikolaus, Marieke Woensdregt, Kadine Saraiva de Carvalho, and Sergio Pereira Soares for their comments and discussions. We thank Shijie Wu for sharing their data.
2307.03475
Freezing of Gait Prediction From Accelerometer Data Using a Simple 1D-Convolutional Neural Network -- 8th Place Solution for Kaggle's Parkinson's Freezing of Gait Prediction Competition
Freezing of Gait (FOG) is a common motor symptom in patients with Parkinson's disease (PD). During episodes of FOG, patients suddenly lose their ability to stride as intended. Patient-worn accelerometers can capture information on the patient's movement during these episodes and machine learning algorithms can potentially classify this data. The combination therefore holds the potential to detect FOG in real-time. In this work I present a simple 1-D convolutional neural network that was trained to detect FOG events in accelerometer data. Model performance was assessed by measuring the success of the model to discriminate normal movement from FOG episodes and resulted in a mean average precision of 0.356 on the private leaderboard on Kaggle. Ultimately, the model ranked 8th out of 1379 teams in the Parkinson's Freezing of Gait Prediction competition. The results underscore the potential of Deep Learning-based solutions in advancing the field of FOG detection, contributing to improved interventions and management strategies for PD patients.
Jan Brederecke
2023-07-07T09:28:04Z
http://arxiv.org/abs/2307.03475v1
###### Abstract ###### Abstract _Freezing of Gait (FOG) is a common motor symptom in patients with Parkinson's disease (PD). During episodes of FOG, patients suddenly lose their ability to stride as intended. Patient-worn accelerometers can capture information on the patient's movement during these episodes and machine learning algorithms can potentially classify this data. The combination therefore holds the potential to detect FOG in real-time. In this work I present a simple 1-D convolutional neural network that was trained to detect FOG events in accelerometer data. Model performance was assessed by measuring the success of the model to discriminate normal movement from FOG episodes and resulted in a mean average precision of 0.356 on the private leaderboard on Kaggle. Ultimately, the model ranked 8th out of 1379 teams in the Parkinson's Freezing of Gait Prediction competition. The results underscore the potential of Deep Learning-based solutions in advancing the field of FOG detection, contributing to improved interventions and management strategies for PD patients._ **Freezing of Gait Prediction From Accelerometer Data Using a** **Simple 1D-Convolutional Neural Network** **-** **8th Place Solution for Kaggle's Parkinson's Freezing of Gait Prediction Competition** Jan Brederecke Department of Cardiology, University Heart & Vascular Center Hamburg, University Medical Center Hamburg-Eppendorf, Hamburg, Germany j.brederecke [at] uke.de **Keywords:** Deep Learning, Parkinson's Disease, Freezing of Gait, Convolutional Neural Network, Kaggle ## 1 Introduction The Parkinson's Freezing of Gait Prediction competition was a machine learning competition hosted on Kaggle from March 9, 20231. Footnote 1: [https://www.kaggle.com/competitions/tlvmc-parkinsons-freezing-gait-prediction/](https://www.kaggle.com/competitions/tlvmc-parkinsons-freezing-gait-prediction/) Parkinson's Disease and Freezing of Gait Parkinson's disease (PD) is a neurodegenerative disorder characterized among others by motor symptoms, including freezing of gait (FOG), which can severely impact patients' quality of life (Perez-Lloret et al., 2014). FOG is characterized by _"an episodic inability (lasting seconds) to generate effective stepping in the absence of any known cause other than parkinsonism or high-level gait disorders. It is most commonly experienced during turning and step initiation but also when faced with spatial constraint, stress, and distraction. Focused attention and external stimuli (cues) can overcome the episode"_(Giladi & Nieuwboer, 2008). With progression of PD, occurrence of FOG in normal walking increases (Falla et al., 2022). The FOG episodes usually last few seconds but can continue for more than 30 s (Schaafsma et al., 2003). FOG leads to mobility impairment and an increased risk of falls in patients with PD, therefore accurate and timely detection of FOG events plays a critical role in providing effective interventions and enhancing the quality of life for individuals with PD. _The Parkinson's Freezing of Gait Prediction Competition_ The objective of the competition was to identify the start and stop of FOG episodes by detecting the occurrence of three types of FOG events: start hesitation (_StartHesitation_), turning (_Turn_), and walking (_Walking_). For this purpose, lower-back 3D accelerometer data from subjects exhibiting FOG episodes was provided. _Competition Data_ Three datasets collected in different settings were available for model training: - The tDCS FOG (_tdcsfog_) dataset, collected in the lab, as participants completed a FOG-provoking protocol - The DeFOG (_defog_) dataset, collected in the participant's home, as subjects completed a FOG-provoking protocol - The Daily Living (_daily_) dataset, collected through one week of continuous 24/7 recordings The _tdcsfog_ and _defog_ datasets were annotated by expert reviewers that watched videos of the trials and documented the FOG events. Series in the _daily_ dataset were not annotated and it was not used for the development of the presented solution. Each dataset contained three variables related to the acceleration on three axes: V - vertical, ML - mediolateral, AP - anteroposterior. The used sensor data was measured in units of \(\frac{\mathrm{m}}{s2}\) for _tdcsfog_ data and \(g\) (9.81 \(\frac{\mathrm{m}}{s2}\)) for _defog_ data. Additionally, the _tdcsfog_ dataset was recorded at 128 Hz, while the _defog_ dataset was recorded using a 100 Hz time resolution. Detailed information on the data and the study population is presented in the competition documentation on Kaggle2. Footnote 2: [https://www.kaggle.com/competitions/tvmc-parkinsons-freezing-gait-prediction/overview/data](https://www.kaggle.com/competitions/tvmc-parkinsons-freezing-gait-prediction/overview/data) _Evaluation_ The competition's goal was to detect FOG episodes in withheld test data collected as part of the _tdcsfog_ and _defog_ settings. No data of patients in the test dataset was provided with the training data to prevent leakage. A solution's performance was measured using the mean average precision score (mAP) across all three outcomes: _StartHesitation_, _Turn_, and _Walking_. The mAP score was calculated as the arithmetic mean of the three average precision scores on the given outcomes. Results are reported on a leaderboard (LB) which is divided into a public LB that provides the score on 32% of the test-data, and the private LB, which provides the score on the remaining hidden test-data (68%). Participants get feedback from the public LB while the private LB score is revealed only after the competition ends. The score on the private LB is what ultimately decides the ranking in the competition. ## 2 Methods In this section, my solution to the Parkinson's Freezing of Gait Prediction competition is presented. The solution is based on a 1-dimensional convolutional neural network (1D-CNN), that was trained on a combination of the _tdcsfog_ and _defog_ datasets. _Preprocessing_ Even though the two data sources had different units and slightly different sample rates, data was not transformed to the same unit or normalized. Moreover, no augmentation was used in the training process. For both training and inference, sequences of 1000 timepoints were sampled, 50 of which were located after the events, i.e., in the future. The _defog_ data contained entries with no events, these were excluded for the training. An illustration of the data loader used during training is shown in Figure 1. #### Model Architecture A ResNet (He et al., 2015) with 1D-CNN layers was used. The model contained six residual block layers with increasing numbers of input / output filters: 32, 64, 128, 256, 384, 512. At the same time the number of input / output samples was decreased: 1000, 500, 250, 125, 25, 5. The model had three input channels, one for each of the variables collected by the sensor. The kernel size was 17. The model was configured to predict the three outcomes _StartHesitation, Turn,_ and _Walking_. #### Model Training Model training was performed in Python 3.8.163 using PyTorch 2.0.1 (Paszke et al., 2017). The source code is available under MIT license on the author's GitHub profile4. To prevent overfitting, a five-fold cross-validation (CV) scheme was utilized. The CV-scheme used was _Stratified-GroupKFold_ from the sci-kit learn (Pedregosa et al., 2011) library which had the additional benefit of preventing the leakage of the same person in the training to the validation splits as the subject was used as the group. For a simplified illustration of the CV see Figure 2. Footnote 3: [http://www.python.org/](http://www.python.org/) Footnote 4: [https://github.com/janbrederecke/fog](https://github.com/janbrederecke/fog) Footnote 5: [https://discuss.pytorch.org/t/bceloss-vs-bcewithlogitsloss/33586/29](https://discuss.pytorch.org/t/bceloss-vs-bcewithlogitsloss/33586/29) Because the task was interpreted as a multi-label classification problem, the loss function used was binary cross entropy for each outcome. PyTorch's _BCEWithLogitsLoss_ was therefore utilized due to its known advantages over _BinaryCrossEntropy5_. Footnote 6: [https://pytorch.org/docs/stable/generated/torch.optim_lr_scheduler.ReduceLROnPlateau.html](https://pytorch.org/docs/stable/generated/torch.optim_lr_scheduler.ReduceLROnPlateau.html) An NVIDIA RTX-3060 GPU with 12 GB VRAM was used for training of the models. All models were trained for a single epoch while limiting the training data to randomly selected five million samples from the respective training folds. A batch-size of 1024, an AdamW optimizer (Loshchilov and Hutter, 2019), and a learning rate scheduler (_ReduceLROnPlateau6_) with a starting value of 0.001 were used. Footnote 7: [https://pytorch.org/tutorials/recipes/recipes/amp_recipe.html](https://pytorch.org/tutorials/recipes/recipes/amp_recipe.html) Additionally, Pytorch's integrated ability to use automatic mixed precision7 was utilized to decrease the overall training time. Figure 1: Illustration of the Data Loader Used During Training. Figure 2: Illustration of the Cross-Validation Scheme Used. ### Ensembling As the CV resulted in five final models, the prediction on the test data was calculated using the simple average of the five individual predictions (see Figure 2). ## 3 Results The presented solution achieved a mAP score of 0.357 on the public and of 0.356 on the private LB in Kaggle's competition. The local CV resulted in mAP scores ranging from 0.185 to 0.309 (see Table 1). As no other indices could be retrieved from the test data on Kaggle, all other calculations were done using only the local CV scheme. As is shown in Table 1, the individual average precision (AP) for each of the three outcomes in the individual folds ranges from 0.010 to 0.063 for _StartHesitation_, 0.420 to 0.682 for _Turn_, and 0.023 to 0.252 for _Walking_. ## 4 Discussion In order to improve the quality of life of PD patients, reliable automatic FOG detection is an important aspect to consider. The present study reported a highly ranked solution to the Parkinson's Freezing of Gait competition. Results show that a simple 1D-CNN can be successfully used to detect FOG related events in accelerometric data from different settings without applying sophisticated preprocessing. ### Limitations While the presented solution achieved a winning place in the competition, it is important to acknowledge that the best-performing models in the competition outperformed my solution significantly. The top-ranking models demonstrated superior mAP (1st place private LB mAP: 0.514), indicating these other approaches may yield better results in overall FOG detection. Especially models that used recurrent neural networks and transformer architectures did well, highlighting their possible superiority over the CNN architecture in FOG prediction from accelerometer data. Another limitation of the presented solution is the inability to calculate and compare additional performance metrics on the test data. As per the competition guidelines, the test data remain confidential, accessible only to the competition organizers. Consequently, I was unable to calculate common metrics on the individual outcomes such as AUC, ROC curves, or F1 score, which could have provided a more comprehensive evaluation of my model's performance on the test data. Moreover, while my model performed well in the competition, it is essential to point out the significant differences in AP for the FOG event types. While the model confidently detects _Turn_ events across folds, the other events are predicted with comparatively low AP. Future work would need to try to raise individual AP to the level of _Turn_. In addition to the given limitations, it is important to address that I included 50 consecutive timepoints following the predicted FOG events in my analysis. However, including future timepoints would not be feasible for real-time application, therefore making evaluation of the model on past data only necessary for this purpose. \begin{table} \begin{tabular}{c c c c c} \hline \hline \multicolumn{2}{c}{mAP\({}^{2}\)} & \multicolumn{2}{c}{AP\({}^{3}\)} \\ \cline{3-5} & \multicolumn{2}{c}{_Start Hesitation_} & _Turn_ & _Walking_ \\ \hline \(1^{1}\) & 0.277 & 0.063 & 0.682 & 0.085 \\ \(2^{1}\) & 0.261 & 0.010 & 0.562 & 0.212 \\ \(3^{1}\) & 0.185 & 0.054 & 0.420 & 0.082 \\ \(4^{1}\) & 0.309 & 0.029 & 0.644 & 0.252 \\ \(5^{1}\) & 0.203 & 0.013 & 0.575 & 0.023 \\ \hline \hline \multicolumn{5}{l}{_Notes._\({}^{1}\)Number of fold. \({}^{2}\)Mean average precision. \({}^{3}\)Average precision.} \\ \end{tabular} \end{table} Table 1: Results of the Cross-Validation. #### Strengths Despite the limitations, the reported solution shines through its simplicity. By utilizing a straightforward Deep Learning architecture like the 1D-ResNet, I demonstrate that achieving competitive results in FOG detection can be accomplished without the need for overly complex models, pre-processing or extensive computational resources. This simplicity not only facilitates ease of implementation but also allows other interested researchers to adopt and build upon the reported methodology with relative ease. #### Conclusions I present a comparatively simple yet effective event detection and classification pipeline for detection of FOG that took 8th place of 1379 teams at the Parkinson's Freezing of Gait Prediction competition. The fact that such an effective model could be trained despite the few preprocessing steps speaks once again for the capability of the ResNet architecture that has been demonstrated numerous times in the past. Moreover, as the CV score on the training dataset did not differ much from the final competition scores on unseen data, local CV has once again been shown to be an effective tool in preventing overfitting. ## Acknowledgements I would like to thank Kaggle and The Michael J. Fox Foundation for hosting the Parkinson's Freezing of Gait Prediction Competition. Moreover, I thank the three research groups that collected the data: The Center for the Study of Movement, Cognition and Mobility, The Neuro-rehabilitation Research Group at Katholieke Universiteit Leuven in Belgium, and the Mobility and Falls Translational Research Center at the Hinda and Arthur Marcus Institute for Aging, affiliated with Harvard Medical School in Boston. I also thank the participants of the competition for sharing ideas, insights, and code. A special thank you goes out to Mayukh Bhattacharyya who generously provided an incredible public baseline in the discussions section that kickstarted the solution presented in this article. Moreover, I thank Carla Reinbold, Marius Knorr, Jan Bremer, and Tim Brederecke for their diverse support whilst writing this article.
2307.01504
All in One: Multi-task Prompting for Graph Neural Networks
Recently, ''pre-training and fine-tuning'' has been adopted as a standard workflow for many graph tasks since it can take general graph knowledge to relieve the lack of graph annotations from each application. However, graph tasks with node level, edge level, and graph level are far diversified, making the pre-training pretext often incompatible with these multiple tasks. This gap may even cause a ''negative transfer'' to the specific application, leading to poor results. Inspired by the prompt learning in natural language processing (NLP), which has presented significant effectiveness in leveraging prior knowledge for various NLP tasks, we study the prompting topic for graphs with the motivation of filling the gap between pre-trained models and various graph tasks. In this paper, we propose a novel multi-task prompting method for graph models. Specifically, we first unify the format of graph prompts and language prompts with the prompt token, token structure, and inserting pattern. In this way, the prompting idea from NLP can be seamlessly introduced to the graph area. Then, to further narrow the gap between various graph tasks and state-of-the-art pre-training strategies, we further study the task space of various graph applications and reformulate downstream problems to the graph-level task. Afterward, we introduce meta-learning to efficiently learn a better initialization for the multi-task prompt of graphs so that our prompting framework can be more reliable and general for different tasks. We conduct extensive experiments, results from which demonstrate the superiority of our method.
Xiangguo Sun, Hong Cheng, Jia Li, Bo Liu, Jihong Guan
2023-07-04T06:27:31Z
http://arxiv.org/abs/2307.01504v2
# All in One: Multi-Task Prompting for Graph Neural Networks ###### Abstract. Recently, "pre-training and fine-tuning" has been adopted as a standard workflow for many graph tasks since it can take general graph knowledge to relieve the lack of graph annotations from each application. However, graph tasks with node level, edge level, and graph level are far diversified, making the pre-training pretext often incompatible with these multiple tasks. This gap may even cause a "negative transfer" to the specific application, leading to poor results. Inspired by the prompt learning in natural language processing (NLP), which has presented significant effectiveness in leveraging prior knowledge for various NLP tasks, we study the prompting topic for graphs with the motivation of filling the gap between pre-trained models and various graph tasks. In this paper, we propose a novel multi-task prompting method for graph models. Specifically, we first unify the format of graph prompts and language prompts with the prompt token, token structure, and inserting pattern. In this way, the prompting idea from NLP can be seamlessly introduced to the graph area. Then, to further narrow the gap between various graph tasks and state-of-the-art pre-training strategies, we further study the task space of various graph applications and reformulate downstream problems to the graph-level task. Afterward, we introduce meta-learning to efficiently learn a better initialization for the multi-task prompt of graphs so that our prompting framework can be more reliable and general for different tasks. We conduct extensive experiments, results from which demonstrate the superiority of our method. pre-training; prompt tuning; graph neural networks + Footnote †: journal: Computer Science and Technology, Tongji [email protected] + Footnote †: journal: Computer Science and Technology, Tongji Universityjhguan@tongji. A promising solution to the above problems is to extend "pre-training and fine-tuning" to "pre-training, prompting, and fine-tuning". Prompt learning is a very attractive idea derived from natural language processing (NLP) and has shown notable effectiveness in generalizing pre-trained language models to a wide range of language applications [20]. Specifically, a language prompt refers to a piece of text appended to the rear of an input text. For example, a sentiment task like "_KDD2023 will witness many high-quality papers_. I feel so [MASK]" can be easily transferred to a word prediction task via a preset prompt ("I feel so [MASK]"). It is highly expected that the language model may predict "[MASK]" as "excited" rather than "upset" without further optimizing parameters for the new sentiment task because this model has already been pre-trained via the pretext of masked words prediction and contains some useful knowledge to answer this question. By this means, some downstream objectives can be naturally aligned with the pre-training target. Inspired by the success of the language prompt, we hope to introduce the same idea to graphs. As shown in Figure 1, prompt tuning in the graph domain is to seek some light-weighted prompt, keep the pre-training model frozen, and use the prompt to reformulate downstream tasks in line with the pre-training task. In this way, the pre-trained model can be easily applied to downstream applications with highly efficient fine-tuning or even without any fine-tuning. This is particularly useful when the downstream task is a few-shot setting. However, designing the graph prompt is more intractable than language prompts. First, classic language prompts are usually some preset phrases or learnable vectors attached at the end of input texts. As shown in Figure 2, we only need to consider the content for the language prompt, whereas the graph prompt not only requires the prompt "content" but also needs to know how to organize these prompt tokens and how to insert the prompt into the original graph, both of which are undefined problems. Second, there is a huge difficulty in reconciling downstream problems to the pre-training task. In the NLP area, we usually pre-train a language model via masked prediction and then transfer it to various applications like question answering [22], sentiment classification [17]. The underlying support [21] is that these language tasks usually share a large overlapping task sub-space, making a masked language task easily transferred to other applications. However, how much does the same observation exist (if truly exists) in graph learning? It is crucial but difficult to decide on an appropriate pre-training task and reformulate downstream tasks to improve the capability of model generalization. Currently, we only find very few works [27] studying the graph prompt issue. However, it can only deal with a single-type task (e.g., node classification) using a specific pretext (e.g., edge prediction), which is far from addressing the multi-task setting with different-level tasks. Last but not least, learning a reliable prompt usually needs huge manpower and is more sensitive to prompt initialization in the multi-task setting [18]. Although there are some works [14; 38] in the NLP area trying to initialize the prompt via hand-crafted content or some discrete features, these methods are task-bounded, which is not sufficient when we confront a new task. This problem may be even worse in our multi-task graph area since graph features vary a lot in different domains and tasks. _Presented work._ To further fill the gap between graph pre-training and downstream tasks, we introduce the prompt method from NLP to graphs under the multi-task background. Specifically, to address the first challenge, we propose to unify the format of the language prompt and graph prompt in one way so that we can smoothly transfer the prompt idea from NLP to graphs, then we design the graph prompt from prompt tokens, token structures, and prompt inserting patterns. To address the second challenge, we first study the task subspace in graphs and then propose to reformulate node-level and edge-level tasks to graph-level tasks by induced graphs from original graphs. To address the third challenge, we introduce the meta-learning technique over multiple tasks to learn better prompts. We carefully evaluate our method with other approaches and the experimental results extensively demonstrate our advantages. _Contributions:_ * We unify the prompt format in the language area and graph area, and further propose an effective graph prompt for multi-task settings (section 3.3). * We propose an effective way to reformulate node-level and edge-level tasks to graph-level tasks, which can further match many pre-training pretexts (section 3.2). * We introduce the meta-learning technique to our graph prompting study so that we can learn a reliable prompt for improving the multi-task performance (section 3.4). * We carefully analyze why our method works (section 3.5) and confirm the effectiveness of our method via extensive experiments (section 4). Figure 1. Fine-tuning, Pre-training, and Prompting. Figure 2. Our graph prompt inspired by the language prompt. ## 2. Background **Graph Neural Networks.** Graph neural networks (GNNs) have presented powerful expressiveness in many graph-based applications (Golovolovolov et al., 2012; Kipf and Welling, 2015; Kipf and Welling, 2016; Kipf and Welling, 2017). The nature of most GNNs is to capture the underlying message-passing patterns for graph representation. To this end, there are many effective neural network structures proposed such as graph attention network (GAT) (Gatani and Vedaldi, 2017), graph convolution network (GCN) (Srivastava et al., 2014), Graph Transformer (Kipf and Welling, 2016). Recent works also consider how to make graph learning more adaptive when data annotation is insufficient or how to transfer the model to a new domain, which triggered many graph pre-training studies instead of traditional supervised learning. **Graph Pre-training.** Graph pre-training (Golovolov et al., 2012) aims to learn some general knowledge for the graph model with easily accessible information to reduce the annotation costs of new tasks. Some effective pre-training strategies include node-level comparison like GCA (Grover et al., 2017), edge-level pretext like edge prediction (Golov et al., 2012), and graph-level contrastive learning such as GraphCL (Srivastava et al., 2014) and SimGRACE (Srivastava et al., 2014). In particular, GraphCL minimizes the distance between a pair of graph-level representations for the same graph with different augmentations whereas SimGRACE tries to perturb the graph model parameter spaces and narrow down the gap between different perturbations for the same graph. These graph-level strategies perform more effectively in graph knowledge learning (Golovolovolov et al., 2012) and are the default strategies of this paper. **Prompt Learning & Motivations.** Intuitively, the above graph-level pre-training strategies have some intrinsic similarities with the language-masked prediction task: aligning two graph views generated by node/edge/feature mask or other perturbations is very similar to predicting some vacant "blanks" on graphs. That inspires us to further consider: why can't we use a similar format prompt for graphs to improve the generalization of graph neural networks? Instead of fine-tuning a pre-trained model with an adaptive task head, prompt learning aims to reformulate input data to fit the pretext (Golovolovolov et al., 2012). Many effective prompt methods are firstly proposed in the NLP area, including some hand-crafted prompts like GPT-3 (Golovolov et al., 2012), discrete prompts like (Golov et al., 2012; Kipf and Welling, 2016), and trainable prompts in the continuous spaces like (Golov et al., 2012; Kipf and Welling, 2017). Despite significant results achieved, prompt-based methods have been rarely introduced in graph domains yet. We only find very few works like GPPT (Golovolov et al., 2012), trying to design prompts for graphs. Unfortunately, most of them are very limited and are far from sufficient to meet the multi-task demands. ## 3. Multi-Task Prompting on Graphs ### Overview of Our Framework #### Objective In this paper, we aim to learn a prompt graph that can be inserted into the original graph, through which we wish to further bridge the gap between a graph pre-training strategy and multiple downstream tasks, and further relieve the difficulties of transferring prior knowledge to different domains. **Overview:** To achieve our goal, we propose a novel multi-task prompting framework for graph models. First, we unify various graph tasks in the same format and reformulate these downstream tasks as graph-level tasks. Second, with the unified graph-level instances, we further narrow down the gap among multiple tasks by a novel prompt graph with learnable tokens, inner structures, and adaptive inserting patterns. Third, we build a meta-learning process to learn more adaptive graph prompts for multi-task settings. Next, we elaborate on the main components. ### Reformulating Downstream Tasks #### 3.2.1. Why Reformulate Downstream Tasks The success of the traditional "pre-training and fine-tuning" framework in the NLP area largely lies in the fact that the pre-training task and downstream tasks share some common intrinsic task subspace, making the pre-training knowledge transferable to other downstream tasks (Figure (a)a). However, things are a little complicated in the graph domain since graph-related tasks are far from similar. As shown in Figure (b)b, it is far-fetched to treat the edge-level task and the node-level task as the same one because node-level operations and edge-level operations are far more different (Golov et al., 2012). This gap limits the performance of pre-training models and might even cause negative transfer (Golov et al., 2012). The same problem also happens in our "pre-training, prompting, and fine-tuning" framework since we aim to learn a graph prompt for multiple tasks, which means we need to further narrow down the gap between these tasks by reformulating different graph tasks in a more general form. #### 3.2.2. Why Reformulate to the Graph Level With the above motivation, we revisit the potential task space on the graph and find their hierarchical relation as shown in Figure (b)b. Intuitively, many node-level operations such as "changing node features", "delete/add a node", or edge-level operations such as "add/delete an edge", can be treated as some basic operations at the graph level. For example, "delete a subgraph" can be treated as "delete nodes and edges". Compared with node-level and edge-level tasks, graph-level tasks are more general and contain the largest overlapping task sub-spaces for knowledge transfer, which has been adopted as the mainstream task in many graph pre-training models (Golov et al., 2012; Srivastava et al., 2014; Srivastava et al., 2014). This observation further inspires us to reformulate downstream tasks to look like the graph-level task and then leverage our prompting model to match graph-level pre-training strategies. #### 3.2.3. How to Reformulate Downstream Tasks Specifically, we reformulate node-level and edge-level tasks to graph-level tasks by building induced graphs for nodes and edges, respectively. As shown in Figure (a)a, an induced graph for a target node means its local area in the network within \(\tau\) distance, which is also known as its \(\tau\)-ego network. This subgraph preserves the node's local structure by neighboring node connections and its semantic context by neighboring node features, which is the main scope of most graph neural Figure 3. Task space in NLP and graph encoders. When we treat the target node's label as this induced graph label, we can easily translate the node classification problem into graph classification; Similarly, we present an induced graph for a pair of nodes in Figure 4b. Here, the pair of nodes can be treated as a positive edge if there is an edge connecting them, or a negative edge if not. This subgraph can be easily built by extending this node pair to their \(\tau\) distance neighbors. We can reformulate the edge-level task by assigning the graph label with the edge label of the target node pair. Note that for unweighted graphs, the \(\tau\) distance is equal to \(\tau\)-hop length; for weighted graphs, the \(\tau\) distance refers to the shortest path distance, where the induced graph can be easily found by many efficient algorithms (Bahdan et al., 2017; Chen et al., 2018). ### Prompt Graph Design #### 3.3.1. Prompting NLP and Graph in One Way To seamlessly transfer the prompting idea from NLP to the graph domain, we propose to unify NLP Prompt and Graph Prompt in one perspective. Having compared the demand of NLP and graph area as shown in Figure 2, we found that the prompt in NLP and graph areas should contain at least three components: _(1) prompt token_, which contains the vectorized prompting information with the same size as the input word/node vector; _(2) token structure_, which indicates the connection of different tokens. In the NLP area, prompt tokens (a.k.a prompt words) are preset as a linear relation like a sub-sentence or a phrase; whereas in the graph domain, the connections of different tokens are non-linear and far more complicated than NLP prompts; _(3) inserting pattern_, which presents how to add the prompt to the input data. In the NLP area, the prompt is usually added in the front or the back end of the input sentences by default. However, in the graph area, there are no explicit positions like a sentence to joint graph prompt, making the graph prompting more difficult. #### 3.3.2. Prompt Tokens Let a graph instance be \(\mathcal{G}=(\mathcal{V},\mathcal{E})\) where \(\mathcal{V}=\{v_{1},v_{2},\cdots,v_{N}\}\) is the node set containing \(N\) nodes; each node has a feature vector denoted by \(\mathbf{x}_{i}\in\mathbb{R}^{1\times d}\) for node \(v_{i}\); \(\mathcal{E}=\{(v_{i},v_{j})|v_{i},v_{j}\in\mathcal{V}\}\) is the edge set where each edge connects a pair of nodes in \(\mathcal{V}\). With the previous discussion, we here present our prompt graph as \(\mathcal{G}_{p}=(\mathcal{P},\mathcal{S})\) where \(\mathcal{P}=\{p_{1},p_{2},\cdots,p_{|\mathcal{P}|}\}\) denotes the set of prompt tokens and \(|\mathcal{P}|\) is the number of tokens. Each token \(p_{i}\in\mathcal{P}\) can be represented by a token vector \(\mathbf{p}_{i}\in\mathbb{R}^{1\times d}\) with the same size of node features in the input graph; Note that in practice, we usually have \(|\mathcal{P}|\ll N\) and \(|\mathcal{P}|\ll d_{h}\) where \(d_{h}\) is the size of the hidden layer in the pre-trained graph model. With these token vectors, the input graph can be reformulated by adding the \(j\)-th token to graph node \(v_{i}\) (e.g., \(\hat{\mathbf{x}}_{i}=\mathbf{x}_{i}+\mathbf{p}_{j}\)). Then, we replace the input features with the prompted features and send them to the pre-trained model for further processing. #### 3.3.3. Token Structures \(\mathcal{S}=\{(p_{i},p_{j})|p_{i},p_{j}\in\mathcal{P}\}\) is the token structure denoted by pair-wise relations among tokens. Unlike the NLP prompt, the token structure in the prompt graph is usually implicit. To solve this problem, we propose three methods to design the prompt token structures: (1) the first way is to learn tunable parameters: \[\mathcal{A}=\bigcup_{\begin{subarray}{c}i=1\\ j=i+1\end{subarray}}^{|\mathcal{P}|-1}\{a_{ij}\}\] where \(a_{ij}\) is a tunable parameter indicating how possible the token \(p_{i}\) and the token \(p_{j}\) should be connected; (2) the second way is to use the dot product of each prompt token pair and prune them according to the dot value. In this case, \((p_{i},p_{j})\in\mathcal{S}\) iff \(\sigma(p_{i},p_{j})<\delta\) where \(\sigma(\cdot)\) is a sigmoid function and \(\delta\) is a pre-defined threshold; (3) the third way is to treat the tokens as independent and then we have \(\mathcal{S}=\emptyset\). #### 3.3.4. Inserting Patterns Let \(\psi\) be the inserting function that indicates how to add the prompt graph \(\mathcal{G}_{p}\) to the input graph \(\mathcal{G}\), then the manipulated graph can be denoted as \(\mathcal{G}_{m}=\psi(\mathcal{G},\mathcal{G}_{p})\). We can define the inserting pattern as the dot product between prompt tokens and input graph nodes, and then use a tailored connection like \(\hat{\mathbf{x}}_{i}=\mathbf{x}_{i}+\sum_{k=1}^{|\mathcal{P}|}w_{ik}\mathbf{ p}_{k}\) where \(w_{ik}\) is a weighted value to prune unnecessary connections: \[w_{ik}=\left\{\begin{array}{cc}\sigma(\mathbf{p}_{k}\cdot\mathbf{x}_{i}^{T} ),&\text{if }\sigma(\mathbf{p}_{k}\cdot\mathbf{x}_{i}^{T})>\delta\\ 0,&\text{otherwise}\end{array}\right. \tag{1}\] As an alternative and special case, we can also use a more simplified way to get \(\hat{\mathbf{x}}_{i}=\mathbf{x}_{i}+\sum_{k=1}^{|\mathcal{P}|}\mathbf{p}_{k}\). ### Multi-task Prompting via Meta Learning #### 3.4.1. Constructing Meta Prompting Tasks Let \(\tau_{i}\) be the \(i\)-th task with supporting data \(\mathcal{D}_{\tau_{i}}^{s}\) and query data \(\mathcal{D}_{\tau_{i}}^{q}\); Specifically, for the graph classification task, \(\mathcal{D}_{\tau_{i}}^{s}\) and \(\mathcal{D}_{\tau_{i}}^{q}\) contain labeled graphs; for the node classification task, we generate an induced graph for each node as mentioned in section 3.2.3, align the graph label with the target node label, and treat this graph as a member in \(\mathcal{D}_{\tau_{i}}^{s}\) or \(\mathcal{D}_{\tau_{i}}^{q}\), for the edge classification task, we first generate edge induced graphs for training and testing and the edge label is up to its two endpoints. #### 3.4.2. Applying Meta-learning to Graph Prompting Let \(\theta\) be prompt parameters, \(\pi^{\pi}\) be the fixed parameters of the pre-trained graph backbone, and \(\phi\) be the tasker's parameters. We use \(f_{\phi,\phi|\pi^{\pi}}\) to denote the pipeline with prompt graph (\(\theta\)), pre-trained model (\(\pi^{*}\), fixed), and downstream tasker (\(\phi\)). Let \(\mathcal{L}_{\mathcal{D}}(f)\) be the task loss with pipline \(f\) on data \(\mathcal{D}\). Then for each task \(\tau_{i}\), the corresponding parameters Figure 4. Induced graphs for nodes and edges can be updated as follows: \[\begin{split}\theta_{i}^{k}&=\theta_{i}^{k-1}-\alpha \nabla_{\theta_{i}^{k-1}}\mathcal{L}_{\mathcal{D}_{i_{t}}^{n}}\left(\theta_{ \theta_{i}^{k-1},\phi_{i}^{k-1}|\pi^{*}}\right)\\ \phi_{i}^{k}&=\phi_{i}^{k-1}-\alpha\nabla_{\phi_{i}^ {k-1}}\mathcal{L}_{\mathcal{D}_{i_{t}}^{n}}\left(\theta_{\theta_{i}^{k-1},\phi_ {i}^{k-1}|\pi^{*}}\right)\end{split} \tag{2}\] where the initialization is set as: \(\theta_{i}^{0}=\theta\), and \(\phi_{i}^{0}=\phi\). The goal of this section is to learn effective initialization settings \((\theta,\phi)\) for meta prompting tasks, which can be achieved by minimizing the meta loss on various tasks: \[\theta^{*},\phi^{*}=\operatorname*{arg\,min}_{\theta,\phi}\sum_{\tau_{i}\in \mathcal{T}}\mathcal{L}_{\mathcal{D}_{i_{t}}^{q}}\left(\theta_{\theta_{i}, \phi_{i}|\pi^{*}}\right) \tag{3}\] where \(\mathcal{T}\) is the task set. According to the chain rule, we use the second-order gradient to update \(\theta\) (or \(\phi\)) based on query data: \[\begin{split}\theta\!\leftarrow&\theta-\beta\cdot \beta_{\theta}^{\text{\emph{second}}}\\ =&\theta-\beta\cdot\sum_{\tau_{i}\in\mathcal{T}} \nabla_{\theta_{i}}\mathcal{L}_{\mathcal{D}_{i_{t}}^{q}}\left(\theta_{\theta_{ i},\phi_{i}|\pi^{*}}\right)\end{split} \tag{4}\] where \(\mathbf{H}_{\theta}(\mathcal{L})\) is the Hessian matrix with \((\mathbf{H}_{\theta}(\mathcal{L}))_{ij}=\vartheta^{2}\mathcal{L}/\partial \theta_{i}\theta_{j}\); and \(\phi\) can be updated in the same way. Kindly note that in the prompt learning area, the task head is also known as the answering function, which connects the prompt to the answers for downstream tasks to be reformulated. The answering function can be both tunable or hand-craft templates. In section 3.5, we also propose a very simple but effective hand-crafted prompt answering template without any tunable task head. #### 3.4.3. Overall Learning Process To improve the learning stability, we organize these tasks as multi-task episodes where each episode contains batch tasks including node classification ("\(n\)" for short), edge classification ("\(\ell\)" for short), and graph classification ("\(g\)" for short). Let \(\mathcal{E}_{i}=(\mathcal{T}_{\mathcal{E}_{i}},\mathcal{L}_{\mathcal{E}_{i}}, \mathcal{S}_{\mathcal{E}_{i}},\mathcal{Q}_{\mathcal{E}_{i}})\) be a multi-task episode. We define task batch \(\mathcal{T}_{\mathcal{E}_{i}}=\{\mathcal{T}_{\mathcal{E}_{i}}^{(g)},\mathcal{T }_{\mathcal{E}_{i}}^{(n)},\mathcal{T}_{\mathcal{E}_{i}}^{(\ell)}\}\) where each subset \(\mathcal{T}_{\mathcal{E}_{i}}^{(\ast)}=\{\tau_{\alpha_{1}},\cdots,\tau_{\alpha_ {\ell}}\}\); loss function sets \(\mathcal{L}_{\mathcal{E}_{i}}=\{\mathcal{L}^{(g)},\mathcal{L}^{(n)},\mathcal{L }^{(\ell)}\}\), supporting data \(\mathcal{S}_{\mathcal{E}_{i}}=\{\mathcal{S}_{\mathcal{E}_{i}}^{(g)},\mathcal{S }_{\mathcal{E}_{i}}^{(n)},\mathcal{S}_{\mathcal{E}_{i}}^{(\ell)}\}\) where each subset \(\mathcal{S}_{\mathcal{E}_{i}}^{(\ast)}=\{\mathcal{D}_{\mathcal{E}_{i}}^{g}, \cdots,\mathcal{D}_{\mathcal{E}_{\tau_{\alpha_{\ell}}}}^{s}\}\), and query data \(\mathcal{Q}_{\mathcal{E}_{i}}=\{\mathcal{Q}_{\mathcal{E}_{i}}^{(g)},\mathcal{Q }_{\mathcal{E}_{i}}^{(n)},\mathcal{Q}_{\mathcal{E}_{i}}^{(\ell)}\}\) where \(\mathcal{S}_{\mathcal{E}_{i}}^{(\ast)}=\{\mathcal{D}_{\mathcal{E}_{i}}^{g}, \cdots,\mathcal{D}_{\mathcal{E}_{\tau_{\alpha_{\ell}}}}^{s}\}\). Then the multi-task prompting is presented in Algorithm 1. We treat each node/edge/graph class as a binary classification task so that they can share the same task head. Note that our method can also deal with other tasks beyond classification with only a few adaptations (see Appendix A). ``` Input: Overall pipeline \(\mathcal{f}_{\theta,\phi|\pi^{*}}\) with prompt parameter \(\theta\), pre-trained model with frozen parameter \(\pi^{*}\), and task head parameterized by \(\phi\); Multi-task episodes \(\mathcal{E}=\{\mathcal{E}_{1},\cdots,\mathcal{E}_{n}\}\); Output: Optimal pipeline \(\mathcal{f}_{\theta^{*},\phi^{*}|\pi^{*}}\) 1 Initialize \(\theta\) and \(\phi\) 2whilenot donedo// inner adaptation Sample \(\mathcal{E}_{i}\in\mathcal{E}\) where \(\mathcal{E}_{i}=(\mathcal{T}_{\mathcal{E}_{i}},\mathcal{L}_{\mathcal{E}_{i}}, \mathcal{S}_{\mathcal{E}_{i}},\mathcal{Q}_{\mathcal{E}_{i}})\) for\(\tau_{\alpha}\in\mathcal{T}_{\mathcal{E}_{i}}\); \(=g,n,\ell\)do\(\theta_{\tau_{\alpha}},\phi_{\tau_{\alpha}}\leftarrow\theta,\phi\) \(\theta_{\tau_{\alpha}}\leftarrow\theta_{\tau_{\alpha}}-\alpha\nabla_{\theta_{ \tau_{\alpha}}}\mathcal{L}_{\mathcal{D}_{\tau_{\alpha}}^{(\ast)}}^{(\ast)}\left( \theta_{\theta_{\tau_{\alpha}},\phi_{\tau_{\alpha}}|\pi^{*}}\right)\) \(\phi_{\tau_{\alpha}}\leftarrow\phi_{\tau_{\alpha}}-\alpha\nabla_{\phi_{\tau_{ \alpha}}}\mathcal{L}_{\mathcal{D}_{\tau_{\alpha}}^{(\ast)}}^{(\ast)}\left( \theta_{\theta_{\tau_{\alpha}},\phi_{\tau_{\alpha}}|\pi^{*}}\right)\) end for // outer meta update Update \(\theta,\phi\) by Equation (4) on \(\mathcal{Q}_{\mathcal{E}_{i}}=\{\mathcal{D}_{\tau_{\alpha}}^{g}|\tau_{\alpha} \in\mathcal{T}_{\mathcal{E}_{i}},\ast=g,n,\ell\}\) 3 end while return\(\mathcal{f}_{\theta^{*},\phi^{*}|\pi^{*}}\) ``` **Algorithm 1**Overall Learning Process ### Why It Works? #### 3.5.1. Connection to Existing Work A prior study on graph prompt is proposed by (Kang et al., 2017), namely GPPT. They use edge prediction as a pre-training pretext and reformulate node classification to the pretext by designing labeled tokens added to the original graph. The compound graph will be sent to the pre-trained model again to predict the link connecting each node to the label tokens. Their work somehow is a special case of our method when our prompt graph only contains isolated tokens, each of which corresponds to a node category. However, there are at least three notable differences: (1) GPPT is not flexible to manipulate original graphs; (2) GPPT is only applicable for node classification; and (3) GPPT only supports edge prediction task as the pretext but is not compatible with more advanced graph-level pre-training strategies such as GraphCL (Wang et al., 2019), UGRAPHEMB (Chen et al., 2019), SimGRACE (Wang et al., 2019) etc. We further discuss these issues w.r.t. flexibility, efficiency, and compatibility as below. #### 3.5.2. Flexibility The nature of prompting is to manipulate the input data to match the pretext. Therefore, the flexibility of data operations is the bottleneck of prompting performance. Let \(g\) be any graph-level transformation such as "changing node features", "adding or removing edges/subgraphs" etc., and \(\varphi^{*}\) be the frozen pre-trained graph model. For any graph \(\mathcal{G}\) with adjacency matrix \(\mathbf{A}\) and node feature matrix \(\mathbf{X}\), Fang et al. (Fang et al., 2019) have proved that we can always learn an appropriate prompt token \(p^{*}\) making the following equation stand: \[\varphi^{*}\left(\mathbf{A},\mathbf{X}+p^{*}\right)=\varphi^{*}(g(\mathbf{A}, \mathbf{X}))+O_{p\varphi} \tag{5}\] This means we can learn an appropriate token applied to the original graph to imitate any graph manipulation. Here \(O_{p\varphi}\) denotes the error bound between the manipulated graph and the prompting graph w.r.t. their representations from the pre-trained graph model. This error bound is related to some non-linear layers of the model (_unchangeable_) and the quality of the learned prompt (_changeable_), which is promising to be further narrowed down by a more advanced prompt scheme. In this paper, we extend the standalone token to a prompt graph that has multiple prompt tokens with learnable inner structures. Unlike the indiscriminate inserting in Equation (5) ("\(\mathbf{x}+p^{*}\)" means the prompt token should be added to every node of the original graph), the inserting pattern of our proposed prompt graph is highly customized. Let \(\psi(\mathcal{G},\mathcal{G}_{p})\) denote the inserting pattern defined in section 3.3; \(\mathcal{G}\) is the original graph, and \(\mathcal{G}_{p}\) is the prompt graph, then we can learn an optimal prompt graph \(\mathcal{G}_{p}^{*}\) to extend Equation (5) as follows: \[\varphi^{*}\left(\mathcal{V}(\mathcal{G},\mathcal{G}_{p}^{*})\right)=\varphi^{* }(\mathbf{g}(\mathbf{A},\mathbf{X}))+O_{p\varphi}^{*} \tag{6}\] By efficient tuning, the new error bound \(O_{p\varphi}^{*}\) can be further reduced. In section 4.6, we empirically demonstrate that \(O_{p\varphi}^{*}\) can be significantly smaller than \(O_{p\varphi}\) via efficient training. That means our method supports more flexible transformations on graphs to match various pre-training strategies. #### 3.5.3. Efficiency Assume an input graph has \(N\) nodes and \(M\) edges and the prompt graph has \(n\) tokens with \(m\) edges. Let the graph model contain \(L\) layers and the maximum dimension of one layer be \(d\). The parameter complexity of the prompt graph is only \(O(nd)\). In contrast, some typical graph models (e.g., GAT (Srivastava et al., 2015)) usually contain \(O(Lkd^{2}+LKd)\) parameters to generate node embedding and additional \(O(Kd)\) parameters to obtain the whole graph representation (\(K\) is the multi-head number). The parameters may be even larger in other graph neural networks (e.g., graph transformer (K are also included as the backbones of our prompt methods. **(2) Pre-training with fine-tuning**: These methods first pre-train a GNN model in a self-supervised way such as GraphCL (Zhu et al., 2017) and SimGRACE (Zhu et al., 2017), then the pre-trained model will be fine-tuned for a new downstream task. **(3) Prompt methods**: With a pre-trained model frozen and a learnable prompt graph, our prompt method aims to change the input graph and reformulate the downstream task to fit the pre-training strategies. #### 4.1.3. Implementations We set the number of graph neural layers as 2 with a hidden dimension of 100. To study the transferability across different graph data, we use SVD (Singular Value Decomposition) to reduce the initial features to 100 dimensions. The token number of our prompt graph is set as 10. We also discuss the impact of token numbers in section 4.4 where we change the token number from 1 to 20. We use the Adam optimizer for all approaches. The learning rate is set as 0.001 for most datasets. In the meta-learning stage, we split all the node-level, edge-level, and graph-level tasks randomly in 1:1 for meta-training and meta-testing. Reported results are averaged on all tested tasks. More implementation details are shown in Appendix A, in which we also analyze the performance on more datasets and more kinds of tasks such as regression, link prediction, and so on. ### Multi-Task Performance with Few-shot Learning Settings (RQ1) We compared our prompt-based methods with other mainstream training schemes on node-level, edge-level, and graph-level tasks under the few-shot setting. We repeat the evaluation 5 times and report the average results in Table 2, Table 12 (Appendix A), and Table 13 (Appendix A). From the results, we can observe that most supervised methods are very hard to achieve better performance compared with pre-train methods and prompt methods. This is because the empirical annotations required by supervised frameworks in the few-shot setting are very limited, leading to poor performance. In contrast, pre-training approaches contain more prior knowledge, making the graph model rely less on data labels. However, to achieve better results on a specific task, we usually need to carefully select an appropriate pre-training approach and carefully tune the model to match the target task, but this huge effort is not ensured to be applicable to other tasks. The gap between pre-training strategies and downstream tasks is still very large, making the graph model very hard to transfer knowledge on multi-task settings (we further discuss the transferability in section 4.3) Compared with pre-training approaches, our solutions further improve the compatibility of graph models. The reported improvements range from 1.10% to 8.81% on node-level tasks, 1.28% to 12.26% on edge-level tasks, and 0.14% to 10.77% on graph-level tasks. In particular, we also compared our node-level performance with the previously mentioned node-level prompt model GPPT in Table 2. Kindly note that our experiment settings are totally different from GPPT. In GPPT, they study the few-shot problem by masking 30% or 50% data labels. However, in our paper, we propose a more challenging problem: how does the model perform if we further reduce the label data? So in our experiment, each class only has 100 labeled samples. This different setting makes our labeled ratio approximately only 25% on Cora, 18% on CiteSeer, 1.7% on Reddit, 7.3% on Amazon, and 1.5% on Pubmed, which are far less than the reported GPPT (50% labeled). ### Transferability Analysis (RQ2) To evaluate the transferability, we compared our method with the hard transfer method and the fine-tuning method. Here the hard transfer method means we seek the source task model which has the same task head as the target task and then we directly conduct the model inference on the new task. The fine-tune method means we load the source task model and then tune the task head for the new task. We evaluate the transferability from two perspectives: (1) how effectively is the model transferred to different tasks within the same domain? and (2) how effectively is the model transferred to different domains? #### 4.3.1. Transferability to Different Level Tasks Here we pre-train the graph neural network on Amazon, then conduct the model on two source tasks (graph level and node level), and further evaluate the performance on the target task (edge level). For simplicity, both source tasks and the target task are built as binary classifications with \(1:1\) positive and negative samples (we randomly select a class as the positive label and sample negatives from the rest). We report the results in Table 3, from which we have two observations: First, our prompt method significantly outperforms the other approaches and the prediction results make sense. In contrast, the problem of the hard transfer method is that the source model sometimes can not well decide on the target tasks because the target classes may be far away from the source classes. This may even cause negative transfer results (results that are lower than random guess). In most cases, the fine-tuning method can output meaningful results with a few steps of tuning but it can still encounter a negative transfer problem. Second, the graph-level task has better adaptability than the node-level task for the edge-level target, which is in line with our previous intuition presented in Figure 3 (section 3.2). #### 4.3.2. Transferability to Different Domains We also conduct the model on Amazon and PubMed as source domains, then load the model states from these source domains and report the performance on the target domain (Cora). Since different datasets have various input feature dimensions, we here use SVD to unify input features from all domains as 100 dimensions. Results are shown in Table 4, from which we can find that the good transferability of our prompt also exists when we deal with different domains. ### Ablation Study (RQ3) In this section, we compare our complete framework with four variants: "w/o meta" is the prompt method without meta-learning \begin{table} \begin{tabular}{l|c|c|c|c} \hline \hline Dataset & \#Nodes & \#Edges & \#Features & \#Labels \\ \hline Cora & 2,708 & 5,429 & 1,433 & 7 \\ CiteSeer & 3,327 & 9,104 & 3,703 & 6 \\ Reddit & 232,965 & 23,213,838 & 602 & 41 \\ Amazon & 13,752 & 491,722 & 767 & 10 \\ Pubmed & 19,717 & 88,648 & 500 & 3 \\ \hline \hline \end{tabular} \end{table} Table 1. Statistics of datasets. step; "w/o h" is our method without task head tuning, which is previously introduced in section 3.5.4; "w/o token structure" is the prompt where all the tokens are treated as isolated without any inner connection; and "w/o inserting" is the prompt without any across links between prompt tokens and the input graphs. We report the performance in Figure 5, from which we can find the meta-learning and token structure all contribute significantly to the final results. In particular, the inserting pattern between a prompt graph and the input graph plays a very crucial role in the final performance. As previously discussed, the purpose of the prompt-based method is to relieve the difficulty of traditional "pre-train, fine-tuning" by filling the gap between the pre-training model and the task head. This means the prompt graph is proposed to further improve the fine-tuning performance. This is particularly important when we transfer the model across different tasks/domains, which proposes harder demand for the task head. As suggested in Figure 5, even when we totally remove the tunable task head, the "w/o h" variant can still perform very competitively, which suggests the powerful capability of bridging upstream and downstream tasks. ### Efficiency Analysis (RQ4) Figure 6 presents the impact of increasing token number on the model performance, from which we can find that most tasks can reach satisfactory performance with very limited tokens, making \begin{table} \begin{tabular}{l l|c c c} \hline \hline Source task & Methods & Accuracy & F1-score & AUC score \\ \hline \multirow{3}{*}{graph level} & hard & 51.50 & 65.96 & 40.34 \\ & fine-tune & 62.50 & 70.59 & 53.91 \\ & prompt & 70.50 & 71.22 & 74.02 \\ \hline \multirow{3}{*}{node level} & hard & 40.50 & 11.85 & 29.48 \\ & fine-tune & 46.00 & 54.24 & 37.26 \\ & prompt & 59.50 & 68.73 & 55.90 \\ \hline \hline \end{tabular} \end{table} Table 4. Transferability (%) from different domains. Source domains: Amazon and PubMed. Target domain: Cora \begin{table} \begin{tabular}{l l|c c|c c c|c c c|c c c|c c c} \hline \hline Training & \multirow{2}{*}{Methods} & \multicolumn{3}{c|}{Cora} & \multicolumn{3}{c|}{CiteSeer} & \multicolumn{3}{c|}{Reddit} & \multicolumn{3}{c|}{Amazon} & \multicolumn{3}{c}{Pubmed} \\ schemes & & Acc & F1 & AUC & Acc & F1 & AUC & Acc & F1 & AUC & Acc & F1 & AUC & Acc & F1 & AUC \\ \hline \multirow{3}{*}{supervised} & GAT & 74.45 73.21 & 82.97 & 83.00 & 83.20 & 89.33 & 55.64 & 62.03 & 65.38 & 79.00 & 73.42 & 97.81 & 75.00 & 77.56 & 79.72 \\ & GCN & 77.55 77.45 & 83.71 & 88.00 & 81.79 & 94.79 & 54.38 & 52.47 & 56.82 & 95.36 & 93.99 & 96.23 & 53.64 & 66.67 & 69.89 \\ & GT & 74.25 75.21 & 82.04 & 86.33 & 85.62 & 90.13 & 61.50 & 61.38 & 65.56 & 85.50 & 86.01 & 93.01 & 51.50 & 67.34 & 71.91 \\ \hline \multirow{6}{*}{pre-train} & GraphCL+GAT & 76.05 & 76.78 & 81.96 & 87.64 & 88.40 & 89.93 & 57.37 & 66.42 & 74.73 & 76.87 & 72.26 & 95.65 & 76.03 & 70.75 & 80.02 \\ & GraphCL+GCN & 78.75 & 79.13 & 84.90 & 87.49 & 89.36 & 90.25 & 55.00 & 65.52 & 74.65 & 96.00 & 95.92 & 98.93 & 69.70 & 70.04 & 74.74 \\ & GraphCL+GT & 73.80 & 74.12 & 82.87 & 88.50 & 88.92 & 91.25 & 63.50 & 66.06 & 66.08 & 80.44 & 93.93 & 96.92 & 69.97 & 75.00 & 74.74 \\ & SimGRACE+GAT & 76.85 & 77.48 & 83.97 & 90.50 & 91.00 & 91.56 & 56.59 & 65.47 & 67.77 & 84.50 & 84.73 & 89.69 & 77.20 & 68.21 & 81.97 \\ & SimGRACE+GCN & 77.20 & 76.39 & 83.13 & 83.50 & 83.21 & 93.22 & 58.00 & 55.81 & 56.93 & 95.00 & 94.50 & 98.03 & 77.50 & 75.71 & 87.53 \\ & SimGRACE+GT & 77.40 & 78.11 & 82.95 & 87.50 & 87.05 & 91.85 & 66.00 & 69.95 & 70.03 & 79.00 & 73.42 & 97.58 & 70.50 & 73.30 & 74.22 \\ \hline \multirow{6}{*}{prompt} & GraphCL+GAT & 76.50 & 77.72 & 82.99 & 88.00 & 90.52 & 91.82 & 75.84 & 67.02 & 75.33 & 80.01 & 75.62 & 97.96 & 77.50 & 78.26 & 83.02 \\ & GraphCL+GCN & 79.20 & 76.05 & 85.29 & 85.80 & 91.59 & 91.94 & 56.00 & 68.57 & 78.82 & 96.50 & 96.37 & 89.70 & 72.50 & 76.24 & 79.57 \\ & GraphCL+GT & 75.00 & 76.00 & 83.36 & 91.00 & 90.10 & 90.29 & 65.50 & 66.08 & 86.86 & 95.50 & 95.43 & 97.56 & 76.70 & 79.11 & 76.00 \\ & SimGRACE+GAT & 76.95 & 78.51 & 83.55 & 93.00 & 93.14 & 92.44 & 57.63 & 66.64 & 69.43 & 95.00 & 95.43 & 97.56 & 73.00 & 74.04 & 81.89 \\ & SimGRACE+GCN & 77.85 & 76.57 & 83.79 & 90.00 & 89.47 & 94.87 & 59.50 & 55.97 & 59.46 & 95.00 & 95.24 & 98.42 & 78.00 & 78.22 & 87.66 \\ & SimGRACE+GT & 78.75 & 79.53 & 85.03 & 91.00 & 91.26 & 95.62 & 69.50 & 71.43 & 70.75 & 86.00 & 83.72 & 98.24 & 73.00 & 73.79 & 76.64 \\ \hline \multirow{6}{*}{reported Acc of GPTT (Label Ratio 50\%)} & 1.47 & 1.94 & 1.10 & 3.81 & 5.25 & 2.05 & 3.97 & 5.04 & 6.98 & 4.49 & 5.84 & 2.24 & 8.81 & 4.55 & 4.62 \\ \cline{1-1} & \multirow{2}{*}{reported Acc of GPTT (Label Ratio 50\%)} & 77.16 & \(-\) & 65.81 & \(-\) & 92.13 & \(-\) & \(-\) & 86.80 & \(-\) & \(-\) & 72.23 & \(-\) & \(-\) \\ \cline{1-1} & & \multirow{2}{*}{\(\sim\) 25\%} & & \(\sim\) 18\% & & \(\sim\) 1.7\% & & \(\sim\) 7.3\% & & \(\sim\) 1.5\% & \\ \hline \hline \end{tabular} \end{table} Table 2. Node-level performance (%) with 100-shot setting. IMP (%): the average improvement of prompt over the rest. Figure 5. Effectiveness of main components the complexity of the prompt graph very small. The limited token numbers make our tunable parameter space far smaller than traditional methods, which can be seen in Table 5. This means our method can be efficiently trained with a few steps of tuning. As shown in Figure 7, the prompt-based method converges faster than traditional pre-train and supervised methods, which further suggests the efficiency advantages of our method. ### Flexibility on Graph Transformation (RQ5) As discussed in section 3.5.2, the flexibility of data transformation is the bottleneck of prompt-based methods. Here we manipulate several graphs by dropping nodes, dropping edges, and masking features, then we calculate the error bound mentioned in Equation 5 and 6. We compare the original error with the naive prompt mentioned in Equation 5, and our prompt graph with 3, 5, and 10 tokens. As shown in Table 6, our designed prompt graph significantly reduces the error between the original graph and the manipulated graph. This means our method is more powerful to stimulate various graph transformations and can further support significant improvement for downstream tasks. This capability can also be observed in the graph visualization from two approaches. As shown in Figure 8, the graph representations from a pre-trained model present lower resolution to node classes compared with our prompted graph. ## 5. Conclusion In this paper, we study the multi-task problem of graph prompts with few-shot settings. We propose a novel method to reformulate different-level tasks to unified ones and further design an effective prompt graph with a meta-learning technique. We extensively evaluate the performance of our method. Experiments demonstrate the effectiveness of our framework.
2304.10159
Deep-Q Learning with Hybrid Quantum Neural Network on Solving Maze Problems
Quantum computing holds great potential for advancing the limitations of machine learning algorithms to handle higher dimensions of data and reduce overall training parameters in deep learning (DL) models. This study uses a trainable variational quantum circuit (VQC) on a gate-based quantum computing model to investigate the potential for quantum benefit in a model-free reinforcement learning problem. Through a comprehensive investigation and evaluation of the current model and capabilities of quantum computers, we designed and trained a novel hybrid quantum neural network based on the latest Qiskit and PyTorch framework. We compared its performance with a full-classical CNN with and without an incorporated VQC. Our research provides insights into the potential of deep quantum learning to solve a maze problem and, potentially, other reinforcement learning problems. We conclude that reinforcement learning problems can be practical with reasonable training epochs. Moreover, a comparative study of full-classical and hybrid quantum neural networks is discussed to understand these two approaches' performance, advantages, and disadvantages to deep-Q learning problems, especially on larger-scale maze problems larger than 4x4.
Hao-Yuan Chen, Yen-Jui Chang, Shih-Wei Liao, Ching-Ray Chang
2023-04-20T08:32:58Z
http://arxiv.org/abs/2304.10159v3
# Deep Reinforcement Learning Using Hybrid Quantum Neural Network ###### Abstract Quantum computation has a strong implication for advancing the current limitation of machine learning algorithms to deal with higher data dimensions or reducing the overall training parameters for a deep neural network (DNN) model. Based on a gate-based quantum computer, a parameterized quantum circuit (PQC) was designed to solve a model-free reinforcement learning problem with the deep-Q learning method. This research has provided a comprehensive investigation and evaluation of its potential to provide quantum advantage on quantum computers' current model and capability. Therefore, a novel PQC based on the latest Qiskit and PyTorch framework was designed and trained to compare with a full-classical deep neural network (DNN) with and without integrated PQC. At the end of the research, the research draws its conclusion and prospects on developing deep quantum learning in solving a maze problem or other reinforcement learning problems. Quantum Machine Learning, Hybrid Neural Networks, Deep Reinforcement Learning ## I Introduction Quantum machine learning is a novel and highly immature field of study. Its promising implication for combining two powerful areas in computer science and physics, quantum machine learning, has made an interesting topic for researchers to investigate to resolve various challenging problems. However, considering the limitations of Noisy Intermediate-Scale Quantum (NISQ) devices and machine learning algorithm designs, some experimental models haven't demonstrated strong effectiveness and eventually surpass the present performance of a full classical model. Therefore, this research would like to investigate the potential and possibility of integrating a parameterized quantum circuit with a deep neural network to solve a reinforcement learning problem. Ultimately, this research would like to provide some potential improvements that could be made within this hybrid deep learning model. Also, the study is based on the IBM Quantum Systems (IBM-Q) ecosystem to enable rapid testing and evaluation. The quantum computation experiments were tested and trained on the full-classical hardware with IBM Qiskit's Aer simulator. Current robotics devices could incorporate our quantum deep reinforcement learning model with this solution architecture. ### _Quantum Reinforcement Learning_ Based on the current quantum machine learning research, there are two approaches to the reinforcement learning problem; the first is to utilize a quantum walk algorithm and parameterized quantum circuit (PQC) to encode classical agents and environments into a quantum state of information. Unlike the previous method, the second approach incorporates the latest deep learning model and PQC to explore potential speed-up or model size reduction for the present deep learning models. #### I-A1 Full-Quantum Reinforcement Learning Quantum reinforcement learning using a full-quantum solution has been discussed before in 2022 [1]. In the paper [citation: QRL Maze], the research use a discrete-time quantum walk to map the state and action space into quantum states, resulting in a quantum maze problem. However, considering the constraints of NISQ devices, there is a limited practical application for this type of solution in the near term. Although the research contains limitations to the scalability, it has demonstrated substantial implications for the present full-quantum reinforcement learning algorithm that can provide speed-up for training under a small problem size, six by six maze size. #### I-A2 Trainable VQC Model Another approach to this problem is to build a deep neural network with a variational quantum circuit (VQC) [2]. The research, different from this paper, introduces a VQC as a trainable model without any conventional tensor layers for the frozen-lake environment, which is logically equivalent to the maze problem set used in this research. The research has demonstrated that a well-designed VQC is a trainable model for a reinforcement learning problem. Moreover, the model has shown a strong parameter reduction capability from \(O(n^{3})\) and \(O(n^{2})\) to \(O(n)\). Considering the limitations of NISQ devices, near-term engineering applications on the first approach will be regarded as impractical. However, the performance of a trainable VQC would massively depend on the circuit design. Therefore, the research proposed a novel architecture from the previous study [1] with the latest IBM Qiskit Quantum Primitive to explore other design variants. Therefore, this research suggested a novel integration of quantum gate primitive with the Qiskit framework and conventional tensor layers as the third scheme to solve this problem class as a much generalized deep learning algorithm. ## II Reinforcement Learning Reinforcement learning is the third paradigm of machine learning which is a type of machine learning that involves an agent learning to make a sequence of decisions in an environment to maximize a cumulative reward signal. The agent interacts with the environment by taking action and receiving rewards. The goal is to learn a policy that maps states to actions to maximize the expected cumulative reward over time. The fundamental mathematical reinforcement learning model can be formalized as a Markov decision-making process (MDP): At each time step t, the agent observes a state \(s_{t}\) of the environment. The agent selects an action \(a_{t}\) from a set of possible actions based on the observed state. The action is executed in the environment, and the agent receives a reward \(r_{t}\) and transitions to a new state \(s_{t+1}\). The agent updates its policy based on the observed state, selected action, received a reward, and new state, using a learning algorithm. A performance metric guides the reward signal learning algorithm, which assigns a scalar value to each state-action pair based on its desirability. The agent aims to learn a policy that maximizes the expected cumulative reward over time, defined as the sum of the rewards received over a finite or infinite horizon, discounted by a factor gamma. The mathematical model of RL can be represented as a Markov decision process (MDP), which is a tuple \[(S,A,P,R,\gamma) \tag{1}\] Where: S is a set of states where the environment can be. A is a set of actions that the agent can take. Given the current state and action, p is a probability distribution over the next state. R is a reward function that assigns a scalar reward to each state-action pair. Gamma is a discount factor that determines the importance of future rewards relative to immediate rewards. The goal of RL is to find a policy pi(s) that maps each state to a probability distribution over actions, such that the expected cumulative reward over time is maximized: \[J(pi)=E[R_{0}+\gamma_{1}+\gamma^{2}R_{2}+...|s_{0},pi], \tag{2}\] where\(R_{t}\) is the reward received at time step t, and\(s_{0}\)is the initial state of the computation. RL algorithms can be categorized into model-based and model-free approaches. Model-based approaches learn a model of the environment, including the transition probabilities and reward function, and use this model to compute an optimal policy. Model-free methods, such as Q-learning and SARSA, directly estimate the value of the state-action pairs and use this estimate to update the policy. In this research, the researcher proposed integrating a novel parameterized quantum circuit and hybrid neural network to better approximate the relation of state-action based on the model-free approach framework. ### _Q-Learning_ Q-learning is a model-free reinforcement learning algorithm that learns an optimal policy for an agent in an environment with discrete states and actions. It is called "Q-learning" because it learns an estimate of the Q-value function, which is the expected cumulative reward for taking a step in a given state and following the optimal policy afterward. The Q-value function is estimated using a table or function approximator. The Q-learning algorithm starts with an initial Q-value function, which is gradually updated as the agent interacts with the environment. The agent observes the current state of the environment, selects an action using an exploration-exploitation strategy (such as epsilon-greedy), and receives a reward from the environment. Based on this reward and the resulting state, the Q-value function is updated using the Bellman equation: \[Q(s_{t},a_{t})\leftarrow\] \[Q(s_{t},a_{t})+\alpha\left[r_{t+1}+\gamma\max_{a}Q(s_{t+1},a)-Q(s _{t},a_{t})\right] \tag{3}\] ### _Deep-Q Learning_ Deep Q-learning is a reinforcement learning algorithm that uses deep neural networks to approximate the Q-function, which measures the expected cumulative reward for taking action in a particular state. The Q-function is learned through an iterative process where the agent takes actions in the environment and receives rewards. The agent uses the experiences gathered from these interactions to update its estimates of the Q-function using a technique called temporal-difference learning. In deep Q-learning, a deep neural network approximates the Q-function. The neural network takes the state of the environment as input and outputs a vector of Q-values for each possible action. The agent then chooses the action with the highest Q-value and executes it in the environment. The neural network training minimizes the difference between the predicted and target Q-values obtained using the Bellman equation. The Bellman equation expresses the expected cumulative reward for taking action in a particular state as the sum of the immediate reward and the discounted expected cumulative reward from the next state. The loss function used to train the model adopts the mean square error function to calculate the loss of the deep neural network's current parameter configuration. \[L=\left(r+\gamma\max_{a^{\prime}}Q(s^{\prime},a^{\prime};\theta_{target})-Q(s, a;\theta)\right)^{2} \tag{4}\] The computational complexity of solving a maze problem using Q-learning and deep Q-learning depends on several factors such as the size of the maze, the complexity of the environment, the number of actions available to the agent, and the number of episodes or iterations required to converge to an optimal policy. In Q-learning, the agent learns the optimal policy by iteratively updating a Q-value table, which stores the expected reward for each state-action pair. The algorithm requires a significant amount of memory to store the Q-value table, which grows linearly with the size of the maze and the number of possible actions. The time complexity of Q-learning is proportional to the number of iterations required to converge to an optimal policy, which can be large for complex environments. On the other hand, deep Q-learning uses a deep neural network to approximate the Q-value function, reducing the memory requirement and allowing for more efficient learning. However, the time complexity of deep Q-learning is proportional to the number of training iterations required to train the neural network, which can be large for large-scale environments. In addition, the computational complexity increases with the neural network architecture's complexity and the input data's size. Solving a maze problem using Q-learning or deep Q-learning can be computationally expensive, especially for large-scale environments. However, advances in hardware and software technology have made it possible to implement these algorithms efficiently and effectively, making them useful for various applications in reinforcement learning and robotics. As parameterized quantum circuits (PQCs) and deep neural networks (DNNs) share some similarities in their architecture and learning processes, which makes them helpful in solving similar types of problems, the research integrates both models using Qiskit's PyTorch Connector interface to facilitate a hybrid deep neural network. The study would like to investigate the potential complexity reduction for using PQC-DNN architecture to reduce the amount of energy and computational resources needed for the training. Therefore, this research proposed a novel architecture to approach a deep-Q learning problem using a hybrid deep neural network in combination with a deep neural network and parameterized quantum circuit. The development process includes the following components, environment, and training agent. ### _Environment_ This is the system or simulation that the agent will interact with. The environment provides the agent with observations and receives actions from the agent. The environment can be anything from a simple game to a complex physical system. ### _Agent_ Firstly, state preparation is needed to encode the current state of the environment so that it can be fed into the agent's neural network. This can be done using a variety of techniques, such as raw pixels or more abstract features. Next, the agent uses its neural network to select an action based on the current state. The neural network takes the state as input and outputs a set of Q-values, which represent the expected future rewards for each possible action. The agent selects the action with the highest Q-value (or a random action with some probability, to encourage exploration). After that, the agent selects an action, the environment provides a reward signal based on the new state and the chosen action. This reward is used to update the neural network's Q-values. In addition, the agent could facilitate a replay-memory mechanism to store its experiences (state, action, reward, next state) in a replay buffer. The replay buffer is used to randomly sample past experiences, which are then used to update the neural network's Q-values. This helps to prevent the agent from over-fitting to recent experiences. The most critical part of the agent's training process is the neural network used to estimate deep-Q value. The agent's neural network is a deep neural network that takes the current state as input and outputs a set of Q-values for each possible action. The network is trained using a combination of supervised learning (to minimize the difference between the predicted Q-values and the actual rewards) and reinforcement learning (to encourage the network to learn from its own experiences). In the end, a complete training loop is needed to allow the agent interacts with the environment. The training loop is an iterative process to search for the optimal Q-value in this research. During the training loop, the agent interacts with the environment, stores its experiences in the replay buffer, samples experiences from the replay buffer to update the neural network, and updates the target network periodically. The training loop continues until the agent reaches a satisfactory level of performance. ## III Experiment Environment Next, the experiment is set up via a classic maze problem. A maze problem refers to finding a path from a starting point to a goal point in a maze or labyrinth. A maze can be represented as a grid of cells, where each cell can be either a wall or a passage. The goal of the maze problem is to find a path from the starting cell to the exit cell while avoiding the walls. The maze problem can be modeled mathematically using a graph with an adjacent matrix, where each node in the graph represents a location in the maze, and each edge represents a possible path between two locations. We can represent the graph using an adjacency matrix \(A\), where \(A_{ij}\) is one if there is a path from node \(i\) to node \(j\), and 0 otherwise. Maze problems are commonly used in computer science as a benchmark for path-finding algorithms. One common approach to solving a maze problem is to use graph-based algorithms, such as breadth-first search (BFS) or depth-first search (DFS), to explore the maze and find a path from the starting cell to the exit cell. However, a common problem of these algorithms is high computational complexity. However, Maze problems can also be solved using machine learning algorithms, such as reinforcement learning, which involves training an agent to find a path through the maze by rewarding it for reaching the goal and penalizing it for hitting walls or taking inefficient routes. Therefore, this research introduces a Fig. 1: Overall research architecture, the environment, and the agent are mostly at classical states of information with determining using binary encoding, however, the parameterized quantum circuit (PQC) is using quantum state of information to help the deep neural network estimates the optimal Q-value of the deep reinforcement learning problems. maze problem to understand the potential performance of our hybrid model suitable for this type of problem class. The maze size used in this research is 20 by 20 with a maze generator using depth-first search, which provides reproducible research results and performance evaluations. ## IV Hybrid Deep Neural Network The hybrid neural network developed in this research contains two primary components, conventional neural layers with multiple tensors included and the parameterized quantum circuit integrated into the last layer of the neural network. Therefore, developing a hybrid network requires PQC and deep neural model design to form a generalized model for deep-Q learning problems. ### _Deep Neural Network Architecture_ Table 1 shows the overall architecture of the hybrid deep neural network in this research. The deep neural network (DNN) for the research defines a fully connected neural network (fc nn layer) as a subclass of the nn.Module class in the PyTorch library. The neural network has four fully connected layers (dense layer) (fc1, fc2, fc3, and fc4) with the ReLU activation function applied after the first two layers. The input arguments specify the sizes of these layers to acquire the size of the maze as the dimension of the input layer. In addition, the neural network also has a Quantum Neural Network (QNN) layer, represented by the TorchConnector (QNN) interface. This object connects the QNN layer to the rest of the neural network and allows it to be trained along with the other layers. Additionally, the network has two linear layers (fc1 and fc5) that transform the output of the qnn layer into a final output. The fc1 layer has a single input and output, while the fc5 layer has a single input and four outputs. The class's forward method defines the neural network's forward pass. It takes an input tensor x and performs the following operations: applies the ReLU activation function to the output of the first two fully connected layers, then uses the remaining layers (fc3, fc4, qnn, fc1, and fc5) sequentially. The forward method returns the output tensor of the fc5 layer, which has a shape of (batch size, 4). Moreover, the model summary is shown below: ### _Parameterized Quantum Circuit_ Next, a parameterized quantum circuit is designed with the IBM Qiskit framework. This code sets up a quantum neural network (QNN) using IBM's latest Estimator-QNN module. The QNN consists of a quantum circuit created using the feature map and Ansatz modules and is defined over two qubits. #### Iv-B1 Quantum Feature Map The feature map module, \(ZZFeatureMap\), creates two qubits quantum circuit that applies a parameterized sequence of gates to the input state. This feature map is designed to encode classical input data into a quantum state that the quantum circuit can process. The ZZ feature map is a quantum circuit used in quantum machine learning that can encode classical input data into a quantum state. It consists of a sequence of single-qubit rotations and controlled Z gates. The controlled-Z gates apply a phase shift to the quantum state depending on the product of the two Fig. 3: An overall architecture of hybrid DNN. Fig. 2: An untrained maze path configuration, whereas the black cells represent the block within the maze and the white cell, represents all of the possible routes within the maze. The arrows in the maze present the current agent travel policy based on the current experiences. qubits' states, which is equivalent to using a phase shift of \(\exp(i*\theta)\) if the qubits are in the state --11?, where theta is a free parameter that can be learned during the training of the quantum circuit. The feature map module, \(ZZFeatureMap\) is a second-order Pauli-Z evolution circuit is a quantum circuit that applies a series of gates to a set of qubits to implement a unitary transformation. The circuit is constructed using two-qubit gates that act on pairs of qubits and single-qubit gates that act on individual qubits. Specifically, the second-order Pauli-Z evolution circuit is a sequence of gates that alternate between a controlled-Z gate (also known as a CZ gate) and a single qubit rotation gate around the Z-axis (also known as an RZ gate). The CZ gate acts on a pair of qubits and applies a conditional phase shift of -1 to the second qubit if the first qubit is in the state \(|1\!\!>\). The RZ gate applies a rotation around the Z-axis to a single qubit, with the angle of rotation determined by a parameter \(\theta\). \[U=e^{-i\theta/2\sum_{j=1}^{n}Z_{j}}\cdot\prod_{j=1}^{n-1}\left(\prod_{k=j+1}^{ n}CZ_{jk}\right) \tag{5}\] Equation 5 illustrates the mathematical model of the unitary operation of the quantum ZZ-Feature Map module. The circuit is called "second-order" because it is a generalization of the first-order Pauli-Z evolution circuit, which applies only CZ gates to implement a unitary transformation. By adding RZ gates to the circuit, the second-order Pauli-Z evolution circuit can implement a broader range of unitary transformations. As the second-order Pauli-Z evolution circuit is helpful for various quantum computing applications, including quantum error correction, quantum state preparation, and quantum simulation, the research adopts this feature map module to prepare and load the classical data into a quantum state for the unitary operation within a trainable quantum circuit. #### Iv-B2 Trainable Quantum Circuit After the state preparation stage, the first layer consists of single-qubit rotations, where each qubit is rotated by an angle that depends on the input data. The second layer consists of controlled Z gates that apply a phase shift to the quantum state depending on the product of the two qubits' states. The number of controlled-Z gates in the circuit equals the number of unique pairs of qubits. Moreover, the \(R_{z}\) gate, in the trainable quantum circuit is a single-qubit gate used in quantum circuits to perform a rotation around the Z-axis of the Bloch sphere. It is represented by the following matrix: \[Rz(\theta)=\begin{pmatrix}e^{-i\theta/2}&0\\ 0&e^{i\theta/2}\end{pmatrix} \tag{6}\] As \(R_{z}\) gate rotates the quantum around the Z-axis of the Bloch sphere is particularly useful and common in quantum machine learning to approximate the real value of the complex linear system to understand the behavior of the model, for example, the Q-function in this research. Also, since the classical data is encoded by using ZZ-Feature Map it would be helpful for us to facilitate a trainable model around Z-axis rotation. #### Iv-B3 Quantum States Measurement The Ansatz module, Real-Amplitudes, is a template circuit that applies layers of parametrized rotations and entangling gates to the input state. It has two qubits and one repetition of the circuit layer. The Quantum-Circuit(2) function defines an open quantum circuit of two qubits. Finally, the Estimator-QNN module defines a quantum neural network (QNN) that uses the quantum circuit as the model. The feature map and Ansatz parameters specify the circuit's input and weight parameters. The input gradient parameter is set to True, enabling the hybrid gradient backpropagation algorithm for training the QNN. This allows gradients to be backpropagated from the output of the QNN to the input parameters of the feature map module. ### _Training Algorithm_ The training algorithm for this hybrid deep neural network is a variant of the Q-learning algorithm, a widely used model-free reinforcement learning algorithm. The algorithm uses a deep neural network as a function approximator to estimate the optimal Q-value function, which maps state-action pairs to their expected future reward. Optimization minimizes the mean squared error between the predicted and target Q-values, computed using a Bellman equation. The algorithm also employs experience replay, where past transitions are stored in a buffer and sampled randomly during training. This reduces the correlation between consecutive samples and stabilizes the training process. The agent updates the neural network weights using the Adam optimizer, which adapts the learning rate based on the gradient data. The algorithm takes as input the size of the batch, the discount factor gamma, and the device for running the computations. The loss function is the Q-loss, which calculates the mean squared error between the predicted and target Q-values. The \(optimizer.zero_{g}rad()\) method clears the gradients of the optimizer, and the backward() method computes the gradients of the loss function to the neural network parameters. Finally, the optimizer.step() method updates the neural network weights using the calculated gradients. ## V Results The research was trained and evaluated on the local machine with NVIDIA's CUDA acceleration framework on the RTX 3080 Ti GPU. In addition to the training infrastructure, the research uses PyTorch and IBM Qiskit to develop the PQC and DNN used in the study. Fig. 4: An conceptual model of the parameterized quantum circuit for this research ### _Training Profile_ Firstly, the model training configuration is defined as an Epsilon profile. In reinforcement learning, an agent interacts with an environment and learns to take actions that maximize a cumulative reward signal. One common strategy for balancing the exploration of new actions with the exploitation of known good actions is the epsilon-greedy strategy. This strategy involves choosing a random action with probability epsilon and choosing the action with the highest expected reward with probability (1-epsilon). The value of epsilon is typically set to decrease over time, resulting in an "epsilon profile" that describes how the agent's exploration behavior changes as it gains more experience. Initially, the agent may explore more (i.e., set epsilon to a higher value) to discover new actions that may lead to high rewards. As the agent learns which actions are most likely to lead to high rewards, it may reduce its exploration (i.e., set epsilon to a lower value) to focus more on exploiting known good actions. In this context, the epsilon units are arbitrary and depend on the specific implementation of the reinforcement learning algorithm. The value of epsilon can range from 0 to 1, with a value of 0 meaning the agent always exploits known good actions and a value of 1 meaning the agent always explores new actions. The specific epsilon profile used will depend on the task being solved and the system's performance requirements. ### _Training Results_ Figure 5 shows the significant difference from the quantum deep neural network's training results. The figure on the right shows the initial environment setting without any training. However, the picture on the right demonstrates a path found in just 3000 epochs of training, combing both PQC and DNN. Ultimately, our hybrid deep neural network demonstrates the capability and potential of near-term quantum deep learning solutions using a generalized PQC design. The findings suggest that the proposed hybrid network can perform highly in various applications. Using a combination of classical and quantum machine learning techniques, the researchers demonstrated the potential for achieving improved performance in challenging problems. These results suggest hybrid deep learning approaches using generalized PQC designs could be vital in developing future quantum machine learning applications. Moreover, as this quantum-classical scheme, the solution can be trained on the GPU-accelerated hardware with IBM Aer and NVIDIA's cuQuantum library to explore future applications based on this model architecture. ## VI Discussion The research provides the third architecture for approaching quantum reinforcement learning problems using a hybrid neural network. This section provides a comparison to two other architectures, full-quantum and trainable VQC models. ### _Differences from full-quantum model_ The fundamental difference between this research and the full-quantum model is the state of action and environment. The full-quantum model encodes all the state and action space into a quantum state using a discrete-time quantum walk with a hopping mechanism. The research demonstrates a strong performance and high level of parallelism possible for a full-quantum solution. The degree of complexity reduction is \(O(\sqrt{n})\). However, this solution is most sensitive to the noise within the quantum devices with the lowest scalability potential. Fig. 5: Model’s Epsilon profile Fig. 6: Left: Initial States at zero epoch, Right: Final State of Training at 3000 epochs ### _Differences from trainable VQC model_ Therefore, a trainable quantum circuit model is proposed to estimate the Q-value for the Bellman equation. The model also provides a potential speed-up and parameter reduction from \(O(n^{2})\) and \(O(n^{3})\) to \(O(n)\). Unlike our research, the VQC's approach doesn't include any classical tensor layers within the trainable model, which increases the difficulty for the model to generalize into other problem sets. However, this research has provided a theoretical and empirical foundation for the logical similarity between VQC and DNN. ### _Hybrid Neural Network_ As a result, a hybrid deep neural network incorporating the PQC model is introduced to mitigate the challenges from the previous two related research. With multiple classical neural layers, the model could resolve many generalized problems with various input dimensions. Also, as this neural network is full-trainable and functional on the classical device, a strong implication and potential for near-term applications emerged. However, some technical constraints are still involved within this solution architecture, like quantum-classical gradient descent, accelerated computing devices for this model class, etc. ### _Outlook_ The present challenges of this research are to explore an efficient training method on both classical simulators and real quantum hardware. However, in light of current constraints to hardware accessibility and software architecture, it is challenging to train a hybrid model on a real quantum computer. However, a well-architected training scheme can be designed on the GPU cluster with NVIDIA cutQuantum, IBM Qiskit, and PyTorch framework to reduce the amount of intercommunication between cores and processors, which results in the slow training for this model based on the various iteration of this experiments. ## VII Challenges This research presents an introduction and technical demonstration of the quantum reinforcement learning algorithm with a hybrid neural network. The neural network comprises the latest circuit architecture with novel IBM Quantum Computing Primitive built-in. The results imply the future trajectory and application of parameterized quantum circuits (PQC) to accomplish an even more complex environment for deep reinforcement learning agent training. In addition, the research demonstrates how near-term quantum devices could provide potential speed-up or parameter reduction to the current deep learning model. In the end, the study would like to integrate a split-steps quantum walk circuit model with a deep neural network and PQC to load the classical state-space into a quantum state of information in which the current algorithm might provide a further advance in terms of speed and model size reduction for such applications. ## Acknowledgment The authors would like to present immense gratitude to the Ph.D. candidates, Yen-Jui Chang and Wei-Ting Wang at National Taiwan University for their support and advisory on this project. Also, a big thanks to Prof. Shih-Wei Liao, Prof. Ching-Ray Chang, and Prof. Horng Wen-bing for providing professional guidance on research trajectories.
2308.01381
Estimation of motion blur kernel parameters using regression convolutional neural networks
Many deblurring and blur kernel estimation methods use a maximum a posteriori (MAP) approach or deep learning-based classification techniques to sharpen an image and/or predict the blur kernel. We propose a regression approach using convolutional neural networks (CNNs) to predict parameters of linear motion blur kernels, the length and orientation of the blur. We analyze the relationship between length and angle of linear motion blur that can be represented as digital filter kernels. A large dataset of blurred images is generated using a suite of blur kernels and used to train a regression CNN for prediction of length and angle of the motion blur. The coefficients of determination for estimation of length and angle are found to be greater than or equal to 0.89, even under the presence of significant additive Gaussian noise, up to a variance of 10\% (SNR of 10 dB). Using our estimated kernel in a non-blind image deblurring method, the sum of squared differences error ratio demonstrates higher cumulative histogram values than comparison methods, with most test images yielding an error ratio of less than or equal to 1.25.
Luis G. Varela, Laura E. Boucheron, Steven Sandoval, David Voelz, Abu Bucker Siddik
2023-08-02T18:44:08Z
http://arxiv.org/abs/2308.01381v3
# Estimation of motion blur kernel parameters using regression convolutional neural networks ###### Abstract Many deblurring and blur kernel estimation methods use MAP or classification deep learning techniques to sharpen an image and predict the blur kernel. We propose a regression approach using neural networks to predict the parameters of linear motion blur kernels. These kernels can be parameterized by its length of blur and the orientation of the blur.This paper will analyze the relationship between length and angle of linear motion blur. This analysis will help establish a foundation to using regression prediction in uniformed motion blur images. ## 1 Introduction Linear motion blur has been studied as a model for camera shake, camera platform movement, and moving objects during imaging. This study was designed as a foundation to model atmospheric turbulence. The effects of atmospheric turbulence are generally modeled by a spatially-varying blurred image which can be modeled as a superposition of linear motion blurs [1, 2]. Linear motion blur kernels are parameterized by length and orientation. In this work, we study the ability to accurately estimate the length and angle parameters of a uniform linear motion blur. The results may then be used as a foundation upon which to build methods to estimate spatially-varying blur parameters and to serve as a baseline in subsequent studies. A uniform blurred image can be described by \[I_{b}=K*I_{s}+N, \tag{1}\] where \(I_{b}\) is the blurred image, \(K\) is the blur kernel, \(I_{s}\) is the sharp latent image, \(N\) is additive noise, and \(*\) is the convolution operator. Note that this formulation assumes a uniform blur since the same kernel \(K\) is used across the entire image. This paper presents an exploration in motion blur kernels including a scope outside of squared odd shaped kernels. The created dataset is used to train VGG16 [3] as a regression network to predict motion blur kernel parameters. The network is analyzed using the \(R^{2}\) score which is a common regression analysis as well as a deconvolved error ratio (the error ratio between deconvolving using the predicted vs actual blur kernel). The organization of this paper is as follows. In Section 2, we discuss previous work, including classical deblurring and deep learning deblurring methods. In Section 3, we describe in detail the exploration of the linear blur kernel parameter space as well as the creation of a blurred dataset for deep learning training. In Section 4, we discuss the process for regression blur parameter prediction and in Section 5, we present results of our regression prediction method and compare them to previous work. Finally, in Section 6, we conclude and briefly discuss our future work. ## 2 Related Work Deblurring and kernel blur estimation has been extensively studied in computer vision, with applications of recovering the sharp image from blurry images caused by camera shake, fast moving objects in frame, or atmospheric turbulence. Prior to deep learning methods, many researchers used a maximum a posteriori (MAP) approach for both blur kernel estimation and deblurring. Two commonly used varieties of MAP are implicit regularization as seen in [4; 5] and explicit edge prediction based approaches like those in [6; 7; 8; 9; 10]. While many approaches have used MAP to estimate both the latent image and the blur kernel, Levin et al. [11; 12] prove that this approach tends to favor the no-blur explanation (i.e., that the kernel is an impulse and the "deblurred" image is the blurry image) instead of converging to the true blur kernel and latent sharp image. Moreover, it is advocated that estimating only the blur kernel is a better approach since there are fewer parameters to estimate than if one were to also estimate the latent sharp image. They use an Expectation-Maximization (EM) framework to optimize their kernel prediction while using either a Gaussian or sparse prior. More recently methods have considered using deep learning approaches to estimate the blur kernel [13], estimate the latent sharp image [14], or both [15]. Edge based approaches in a MAP framework use extracted edges as an image prior in the MAP optimization. Cho et al. [6] introduce a gradient computation using derivatives of the image to compute edges. Money & Kang [8] use shock filters for edge detection. Cho et al. [7] use the Radon transform for edge based analysis; image deblurring may be achieved through the use of a MAP algorithm or by computing the inverse Radon transform informed by the detected edges. Jia [9] uses object boundary transparency as an estimation of edge location. Fergus et al. [10] introduce natural image statistics defined by distributions of image gradients as a prior. Implicit regularization MAP approaches use different regularization terms to enforce desired image priors. Xu et al. [4] incorporate a regularization term to approximate the \(L_{0}\) cost which improves computational speeds over alternative implicit sparse regularizations. This framework alternates between estimating the latent sharp image and the blur kernel in each iteration. Krishnan et al. [5] use a ratio of \(L_{1}/L_{2}\) norms as a regularization to estimate the kernel. This helps with the attenuation of high frequencies that blur introduces in an image. Although many of the previous works discussed above can estimate generalized blur kernels, some work specializes in motion blur kernel prediction. Whyte et al. [16] propose a new method of estimating motion blur by parametrizing a geometric model in terms of rotational velocity of the camera during exposure time. They modify the Fergus et al. [10] algorithm to implement non-uniform deblurring. Hirsch et al. [17] combine projective motion path blur models with efficient filter flow [18] to estimate motion blur at a patch level and deblur by modifying the Krishnan & Fergus [19] algorithm. Recent methods using deep learning have used various architectures including Convolutional Neural Networks (CNNs) [20; 21; 15; 13], Generative Adversarial Networks (GANs) [14], and Fully Convolutional Networks (FCNs) [22] to tackle the problem of blur kernel prediction and deblurring. Sun et al. [20] use a CNN to classify the best-fit motion blur kernel for each image patch. They use 73 different motion blur kernels and are able to expand up to 361 kernels by rotation of their input image. Gong et al. [22] use an FCN to predict a motion flow map where each pixel has its own motion blur parameters. Li et al. [15] uses a mixture of deep learning and MAP to deblur an image. They use a binary classification CNN which is trained to predict the probability of whether the input is blurry or sharp. The classifier is used as a regularization term of the latent image prior in their MAP framework. Yan & Shao [13] use a two step process to predict blur parameters. Their first step includes a deep neural network to classify the type of blur and their second step is a general regression neural network to predict the parameters of the blur predicted in step one. Gong et al. [22] use an FCN to predict a motion flow map of the blurred image and use non-blind deconvolution to recover the sharp image. While many of these approaches are able to handle spatially varying blur, we focus on a thorough exploration of motion kernel parameters in uniform blur; this will serve as a framework for spatially varying blur in future work. In this work we focus on motion blur kernels and expand on the complexity of defining a motion blur kernel. We analyze which motion blur kernels exist within different kernel shape sizes rather than using \(N\times N\) odd kernels as often implicitly assumed in the implementation, likely for ease of coding. By exploring all the motion blur kernel possibilities for a suite of length and angle combinations, we train a CNN which uses regression prediction instead of classification. We also expand the range of additive noise to analyze Gaussian noise up to a variance of 10%. ## 3 Blur Kernels and Blurred Dataset A linear blur kernel can be parametrized by the length \(r\) and orientation \(\theta\) of a line. To formulate a discrete blur kernel for application to a digital image using Equation (1), we carefully define the difference between a continuous line and a discrete pixel line. We also explore angle and length combinations that exist within linear motion blur kernels. Finally, we discuss how we use the 2014 COCO dataset to create a new blurred dataset for deep learning training purposes. ### Continuous and Pixel Lines In this and following discussions, we use the terminology "line" to refer to a line segment. We use \(r\) to denote a Euclidean distance (which could be defined for either a continuous or discrete line), \(r_{\infty}\) to denote a Chebyshev distance for a discrete line, \(\theta\in(-90,90]\) to denote the orientation (angle) of a continuous line in degrees, and \(\phi\in(-90,90]\) to denote the orientation (angle) of a discrete pixel line in degrees. A blur kernel has dimensions \(h\times w\) pixels. For a given length \(r\), we denote the set of possible continuous line angles as \(\Theta\in(-90,90]\) degrees and the set of possible discrete pixel line angles as \(\Phi\subseteq\Theta\). A line in a 2-dimensional (2D) continuous domain \(\mathbb{R}^{2}\) can be described as a 1-dimensional (1D) object with zero width and length \(r\). The orientation of a line can be described by the angle with respect to the horizontal axis; \(\theta=0\) thus corresponds to a horizontal line and \(\theta=90\) to a vertical line. A pixel line in a 2D discrete domain \(\mathbb{Z}^{2}\) is defined on a 2D discrete pixel grid which gives the line a non-zero width and length \(r\). Figure 1 illustrates a continuous line with parameters \((r,\theta)=(3,90)\) and a pixel line with parameters \((r,\phi)=(3,90)\). One limitation in defining pixel lines is the interrelation between length and angle of the line. In essence, a shorter pixel line will limit the number of unambiguous angles that a pixel line can have. Figure 2(a) illustrates how multiple continuous lines with angle \(\theta\in[0,30]\) can be interpreted by the same horizontal pixel line of Chebyshev length \(r_{\infty}=2\). Similarly if we move to a pixel line of Chebyshev length \(r_{\infty}=2\) and angle \(\phi=45\) (see Figure 2(c)) we can fit many intermediate lines with angles \(\theta\in[30,60]\). The four pixel lines illustrated in Figure 2 show the only four pixel lines that can be described for a Chebyshev length \(r_{\infty}=2\) pixel line. This means that for smaller length motion blurs, there will be gaps in the angles that can be represented. For example, a length \(r_{\infty}=2\) pixel line can only have angles of \(\phi\in\{-45,0,45,90\}\) as illustrated in Figure 2. We also note that blur kernels may have two additional characteristics different from common conventions in image filter kernels: they may be non-square in dimension and they may be even in one or more dimensions. The \(\phi=0\) and \(\phi=90\) kernels in Figure 2 are \(1\times 2\) and \(2\times 1\) pixels, respectively; these two kernels are non-square and even in one dimension. The \(\phi=\pm 45\) kernels in Figure 2 are both \(2\times 2\) pixels; these two kernels are square but even in both dimensions. The assumption of square or odd-sized convolution kernels in the blur model described in Equation (1) is not mathematically necessary. The preference for square kernels is related to the symmetry of features both horizontally and vertically. The preference for odd-sized kernels is that there is an unambiguous center point to the kernel. This center point is commonly assumed to be associated with the pixel that is being processed. ### Blur Kernel Creation We explore the gaps in angles resulting from representation of continuous lines as pixel lines. We study a range of Euclidean lengths \(r=2,3,\ldots,100\) and angles \(\theta=-89,-88,\ldots,90\), and gather the resulting and unique \((r,\phi)\) discrete line parameter pairs. We calculate the shape of an \(h\times w\) kernel corresponding to an \((r,\theta)\) continuous line as follows: \[h =\begin{cases}\lceil r\cos(\theta)\rceil,&\cos(\theta)\neq 0\\ 1,&\cos(\theta)=0\end{cases} \tag{2}\] \[w =\begin{cases}\lceil r\sin(\theta)\rceil,&\sin(\theta)\neq 0\\ 1,&\sin(\theta)=0,\end{cases} \tag{3}\] where \(\lceil\cdot\rceil\) is the ceiling operator. The cases for \(\cos(\theta)=0\) and \(\sin(\theta)=0\) are to define a height or width of one for the horizontal and vertical cases, respectively. We use \(r\) as the Euclidean distance labels which are drawn on top of the Figure 1: A continuous line (left) with parameters \((r,\theta)=(3,90^{\circ})\) and pixel line (right) with parameters \((r,\phi)=(3,90^{\circ})\). Note that the pixel line has a width of 1 due to its definition on a 2D discrete grid. 2D discrete grid. The ceiling operator introduces a quantization error, since \(r\) may result in a line ending mid-pixel. We include the pixel where \(r\) ends as part of the motion blur kernel using the ceiling operator. The worst case for this quantization error is at angle of \(\pm 45\) since the Euclidean length of a diagonal pixel is \(\sqrt{2}\). We use the line function from the skimage.draw library in python to draw a discrete line through the pixel grid. If \(\phi\) is positive we draw a line from the lower-left corner \((h,0)\) to the upper-right corner \((0,w)\) and if \(\phi\) is negative we draw a line from the upper-left corner \((0,0)\) to the lower-right corner \((h,w)\). For each length \(r=2,3,\ldots,100\), we generate a discrete blur kernel associated with a continuous line of length \(r\) and angle \(\theta=0,1,\ldots,90\). We then group all the angles \(\theta\in\Theta\) that resulted in the same pixel line (e.g., see Figure 2). We must define a unique single discrete angle \(\phi\) for each group of angles \(\Theta\) for use as a training label: \[\phi=\begin{cases}0,&0\in\Theta\\ 90,&90\in\Theta\\ \lceil\operatorname{median}(\Theta)\rceil,&else\end{cases}. \tag{4}\] Note that this definition of \(\phi\) has two special cases. If the collection contains \(\theta=0\), i.e., \(0\in\Theta\), we know that the kernel is consistent with a horizontal line (see Figure 2(a)) and we assign \(\phi=0\). Similarly, if the collection contains \(\theta=90\), i.e., \(90\in\Theta\), we know that the kernel is consistent with a vertical line (see Figure 2(b)) and we assign \(\phi=90\). These special cases avoid the median operator assigning an erroneous label to a horizontal or vertical line. Figure 2: Multiple continuous lines can be represented by the same pixel line of Chebyshev length \(r_{\infty}=2\). Example continuous lines are shown in red, overlaid on the pixel line kernel that describes those continuous lines. We compute all possible \((r,\phi)\) combinations by generating the blur kernel for \(r=2,3,\ldots,100\) and \(\theta=0,1,\ldots 90\) and computing the resulting blur kernel angle \(\phi\) using Equation (4). We span only positive angles \(\theta\in[0,90]\) since we know that the negative kernels will be symmetric versions of the positive kernels (see also Figure 2(c) and (d)). The resulting combinations of \((r,\phi)\) parameters are the parameters of the unique discrete pixel lines. These parameter values are also what will be used as labels to train a network to predict the blur parameters from a blurry image (Section 4), using \((r,\phi)=(1,0)\) as labels for a non-blurred image. Figure 3(a) illustrates the \((r,\phi)\) combinations as a scatter plot, where we note the existence of gaps where a continuous line cannot be described by a pixel line. As expected those gaps are larger for smaller lengths, indicating that there are limited unique pixel lines (blur kernels) for shorter blur lengths. Figure 3(b) plots the number of unique angles \(\phi\) versus length \(r\) where we note that we must have a line of approximately 70 pixels or larger in order to represent all orientations \(\phi=-89,-88,\ldots,90\). We denote the unique combinations as \((r_{u},\phi_{u})\) and use these values to create a blurred dataset. ### COCO Blurred Dataset We use the 2014 COCO dataset [23] to create a blurred dataset for training and validating a model for blind estimation of length and angle given only a blurry image. The 2014 COCO dataset consists of a training dataset with 82,783 images and a validation set of 40,504 images. We use the training dataset to create a blurred training dataset and we split (with no overlap) the validation dataset to create blurred validation and test datasets. We create the blurred dataset by creating a blur generator that loops through the labeled pairs \((r_{u},\phi_{u})\), creating the corresponding blur kernel, and convolving the blur kernel with an image from the COCO dataset. We choose a random COCO image (without replacement) for each length \(r_{u}\) to provide a variety of images in the blurred dataset. We encounter a dataset imbalance in lengths and/or angles represented in the blurred dataset due to the uneven representation of angles for shorter lengths (see Figure 3(b)). We improve the imbalance by creating a minimum of 175 blurred images per length. This implies that we end up using more unique COCO images for shorter blur lengths. Each run of the blur generator creates 21,789 blurred images. The creation of the training set used 12 parallel threads of the blur generator, each operating on a subset of the COCO dataset, creating a total of 261,468 blurred images. The validation and testing sets were each created with one run of the blur generator, creating a total of 21,789 blurred images for each. Figure 4 shows the number of unique COCO images versus length and angle for the training, validation, and testing datasets. We notice a spike in number of unique images for length \(r=1\) and for angle \(\phi=0\). This is due to the non-blurred images that are part of the dataset. We notice more unique images used for shorter lengths as the blur generator needs to loop through more images to complete the minimum threshold of images per length. We notice these small lengths create peaks in the angles of \(\phi=[-45,0,45,90]\). We note that there is an entanglement between angle and length, resulting in an inability to completely balance both length and angle in the blurred dataset. Figure 5 shows the distribution of labeled blurred images with respect to angle and length. Our choice to generate a minimum of 175 blurred images per length in the blur generator favors a more uniform length distribution [Figure 5(a)] This, however, results in peaks in the angle distribution [Figure 5(b)] due to the over-representation of certain angles for smaller lengths (see Figure 3). A choice to favor a more uniform angle distribution, however, would result in missing many shorter blur lengths, creating a more problematic data imbalance. While there are other choices that could be made regarding data imbalance here, we find that this blurred dataset can be used to train a network to accurately predict both length and angle. ## 4 Uniform Blur Prediction We formulate blur length and angle estimation as a deep learning regression problem using the VGG16 [3] architecture as the backbone of our model. We trained VGG16 from scratch with TensorFlow's default layer initializations to predict both the length and angle parameters for a linearly uniform motion blurred image. We modified the last layer of VGG16 to have two output nodes (corresponding to prediction of length and angle) with sigmoid activations. Since the sigmoid activation outputs values in the range \([0,1]\), we normalize length and angle to be in the range \([0,1]\) to train the model. The predicted length and angle parameters are re-scaled to their native ranges (\(r\in[1,100]\), \(\phi\in(-90,90]\)) for validation. Due to the fixed input size of VGG16 \((224\times 224)\), we created a TensorFlow data generator to randomly crop the blurred COCO images. We crop instead of resizing the image to maintain accuracy in the blur angle labels since a resize could change the aspect ratio of the image and thus the blur angle. If a blurred image was smaller than the input size for VGG16 then it was skipped and not used. In total there were 892 training, 5 validation, and 13 test images that were skipped. This results in less than \(0.3\%\) of images skipped for each dataset. Figure 3: Length and angle pairs \((r,\phi)\) that are describable by a discrete pixel line. (a) Length \(r\) and angle \(\phi\) for all possible discrete blur kernels for \(r\in[2,100]\) and \(\phi\in(-90,90]\). (b) Number of angles that can be represented for a given length kernel. Note that shorter length kernels have many fewer possible angles that they can represent, including the four possible angles of \(-45\), \(0\), \(45\), and \(90\) for \(r=2\). We use the Adam optimizer to with a learning rate of 0.1 and epsilon of 0.1. We use the mean squared error (MSE) as the loss function. We empirically determined that a batch size of 50 minimized convergence issues. We train for 50 epochs, saving the weights for the best model throughout training and terminating training if the MSE performance has not improved within the previous 5 epochs. Training takes about 25 minutes per epoch and about 12 hours to fully train on an NVIDIA RTX-3090. We performed multiple trainings of the network by adding different noise levels to each training. This resulted into four different models. The first model is trained with no noise and the other three models are trained with different levels of additive white Gaussian noise with variance \(\sigma^{2}\in\{0.001,0.01,0.1\}\). We added the noise in our data generator after the image was cropped and normalized to the range \([0,1]\). In testing we test each model with the noiseless test set and by adding the three noise levels to the test set for an additional three test runs. ## 5 Experiments and Results In this section, we present results using the \(R^{2}\) metric for evaluating the regression model. We present results of the effects of additive noise on our model's predictions. Finally we compare with other methods [11, 5] and evaluate using the error ratio score as introduced by [24]. Figure 4: Representation of COCO images versus length and angle. Figure 5: Distribution of blurred images for angle and length. ### Metrics We validate the performance of blur estimation using metrics that measure the accuracy of the parameter estimation itself and also the quality of an image deblurred using the estimated kernel. #### 5.1.1 Accuracy of Parameter Estimation In testing, we measure performance using the coefficient of determination, \(R^{2}\). The coefficient of determination, \(R^{2}\), measures the goodness of fit between actual known values of variable \(y_{i}\) and estimated values \(x_{i}\): \[R^{2}=1-\frac{\sum_{i=1}^{n}(y_{i}-x_{i})^{2}}{\sum_{i=1}^{n}(y_{i}-\bar{y})^{2 }}, \tag{5}\] where \(\bar{y}\) is the mean of the known variables \(y_{i}\) and \(n\) is the number of samples [25]. The numerator \(\sum_{i=1}^{n}(y_{i}-x_{i})^{2}\) is the sum of squares of the residual prediction errors and the denominator \(\sum_{i=1}^{n}(y_{i}-\bar{y})^{2}\) is proportional to the variance of the known data. A perfect model will have zero residual errors and thus an \(R^{2}=1\). A naive model that always predicts the average of the data \(\bar{y}\) will have equal numerator and denominator and thus an \(R^{2}=0\). Models that have predictions worse than the naive model will have \(R^{2}<0\). #### 5.1.2 Quality of Deblurred Image In addition to studying the accuracy of blur kernel estimation, we measure the quality of the image deblurred using the estimated blur kernel in a non-blind deblurring method (see Section 5.3). To measure the quality of the deblurred image, we use the error ratio as presented in [24]. The error ratio is motivated by the fact that, even with a perfectly estimated blur kernel, one may not be able to perfectly predict the latent sharp image. The error ratio \(E_{k}/E_{k}\) is computed by considering the error between the true sharp image and the latent sharp image recovered using the estimated blur kernel \(E_{k}\) and the error between the true sharp image and the latent sharp image recovered using the true blur kernel \(E_{k}\). An error ratio of 1 indicates that the images deblurred using the estimated and true kernel are identical. Any error metric can be used to define the error ratio, but we use the sum of squared differences (SSD) as in [24]. The error ratios are generally presented as a cumulative histogram for error ratios binned in the range \([1,4]\). As noted in [24], SSD error ratios above two tend to indicate significant perceptually noticeable distortion present in the image deconvolved with the estimated kernel. ### Accuracy of Parameter Estimation #### 5.2.1 Noise-Free Predictions A VGG-16 based model (see Section 4) was first trained on blurred images without any additive noise. Scatterplots of estimated versus actual length and angle are illustrated in Figure 6 along with the corresponding \(R^{2}\) scores. We find the model to be highly accurate for prediction of both length and angle as demonstrated by the \(R^{2}\) scores of 0.9869 and 0.9935, respectively. In Figure 6(a) we note a larger spread in estimated values as the length increases. This is not surprising, as larger blur lengths are expected to be more difficult to accurately estimate. In Figure 6(b) we note certain angles have a larger spread in estimated values. This is most notable for \(\phi\in\{0,\pm 45,90\}\), but can be noted for other angles. This is due to errors in prediction for the smaller length kernels which have a limited set of angles. It is important to recall, however, that many of these incorrect angle predictions will result in a correct blur kernel. As an example, an image blurred with kernel parameters \((r,\phi)=(2,0)\) may have an angle prediction of \(\hat{\phi}=27\). However, since blur kernels of length \(r=2\) can only be represented by \(\phi\in\{0,\pm 45,90\}\), the blur kernel created with parameters \((r,\phi)=(2,27)\) will generate the closest valid line of \((r_{u},\phi_{u})=(2,0)\). #### 5.2.2 Predictions with Additive Noise We used the model from Section 5.2.1, trained on noise-free blurred images, and tested it on images with additive white Gaussian noise with variance \(\sigma^{2}\in\{0.001,0.01,0.1\}\), corresponding to signal-to-noise (SNR) values of \(\{30,20,10\}\) dB, respectively. Results for this experiment are shown in the first row of Table 1 and Table 2 for length and angle prediction, respectively. We note the estimation of the length parameter is more susceptible to noise than angle, resulting in a complete failure of prediction (\(R^{2}\) scores less than 0) for even the smallest level of additive noise, \(\sigma^{2}=0.001\). We hypothesize that additive noise can alter the intensity distribution along the blur path in a blurry image, creating the appearance of artificially shorter or longer blur paths. Those blur paths, however, will likely retain more characteristics of their angle for the same level of noise. \begin{table} \begin{tabular}{l|l l l l} & \multicolumn{4}{c}{Testing \(\sigma^{2}\)} \\ Training \(\sigma^{2}\) & 0 & 0.001 & 0.01 & 0.1 \\ \hline 0 & 0.9869 & -0.26 & -3.17 & -3.17 \\ 0.001 & 0.9607 & 0.9557 & -1.14 & -3.12 \\ 0.01 & 0.9527 & 0.9539 & 0.9523 & -2.91 \\ 0.1 & 0.8923 & 0.8932 & 0.8960 & 0.8772 \\ \end{tabular} \end{table} Table 1: \(R^{2}\) score for length prediction for training and testing under different levels of additive noise. \begin{table} \begin{tabular}{l|l l l l} & \multicolumn{4}{c}{Testing \(\sigma^{2}\)} \\ Training \(\sigma^{2}\) & 0 & 0.001 & 0.01 & 0.1 \\ \hline 0 & 0.9935 & 0.8772 & 0.3935 & 0 \\ 0.001 & 0.9758 & 0.9754 & 0.6509 & -0.16 \\ 0.01 & 0.9733 & 0.9735 & 0.9682 & 0.0128 \\ 0.1 & 0.8999 & 0.9009 & 0.9010 & 0.8834 \\ \end{tabular} \end{table} Table 2: \(R^{2}\) score for angle prediction for training and testing under different levels of additive noise. Figure 6: Scatterplots of estimated versus actual values for (a) length and (b) angle along with corresponding \(R^{2}\) score. The individual estimates are represented as blue points and the best fit linear line is plotted in red. We trained three additional models using noisy blurred images with additive white Gaussian noise with variance \(\sigma^{2}\in\{0.001,0.01,0.1\}\) and tested each of those models on noise-free and noisy images, i.e., for \(\sigma^{2}\in\{0,0.001,0.01,0.1\}\). Results for those three models are in the second through fourth rows of Table 1 and Table 2 for length and angle prediction, respectively. We again note a higher sensitivity to noise in the prediction of length (Table 1) than angle (Table 2). We further note that the \(R^{2}\) score decreases by \(\sim 0.1\) for the model trained on the highest level of noise \(\sigma^{2}=0.1\) compared to the noise-free model, but that the same model is robust to varying levels of noise. Finally we note that the models trained on noisy data appear to be robust to noise levels less than or equal to the noise level on which they are trained. This implies that a single model trained on a single noise level can yield accurate predictions even for smaller noise levels not seen in training. In comparison to other methods that test under additive noise, most, e.g. [11, 7], test up to a Gaussian noise of \(\sigma^{2}=0.01\) to simulate sensor noise. Krishnan et al. [5] tests noise of up to \(\sigma^{2}=0.02\). Our model is tested up to \(\sigma^{2}=0.1\) and demonstrates a higher tolerance for noise which can be an advantage when modeling atmospheric turbulence. ### Quality of Deblurred Images #### 5.3.1 Deconvolution and Comparison Methods We quantify the performance of our blur parameter estimation by using the expected path log likelihood (EPLL) method [26] to deconvolve the images using our predicted motion blur kernel and the ground truth blur kernel. We used the python implementation available at [https://github.com/friedmanroy/torchEPLL](https://github.com/friedmanroy/torchEPLL). We replaced their Gaussian kernel with our linear motion blur kernel. EPLL only accepts square, odd-sized blur kernels. This means we must zero pad our predicted parameter kernel to a square, odd-sized blur kernel. We zero padded the shortest side of the kernel on both sides to keep the kernel centered and padded to match the size of the longest side. If the longest side is even, however, this would result into an even-sized square kernel. We used a similar approach to [27] where we create four odd-sized kernels each zero padded with the line asymmetrically offset toward a different corner. We deconvolve the blurred image with each of the four kernels and average the four deconvolved images as the resulting deblurred image. Additionally, we compare performance with other blur kernel estimation methods from Levin et al. [11] and Krishnan et al. [5]. Both Levin et al. [11] and Krishnan et al. [5] include methods for estimating the deblurred image. For fairness of comparisons, we use only the blur kernel estimate from both methods and use their blur kernel estimates in the same EPLL [26] deblurring framework as we use for our estimated blur kernels. For the method in [11], we used the Matlab implementation provided at [https://webee.technion.ac.il/people/anat.levin/](https://webee.technion.ac.il/people/anat.levin/). We used the deconv_diag_filt_sps function and set a kernel prediction size of \((101,101)\). This is to allow prediction of the largest kernel size in our blurred dataset. It should be noted that the method in [11] estimates a blur kernel for each of the three channels in a color image; we applied EPLL to each channel using the kernel estimated for that channel. For the method in [5], we used the Matlab implementation provided at www.cs.nyu.edu/~dilip/wordpress/?page_id=159, again with kernel size of \((101,101)\). #### 5.3.2 Reduced Test Set Due to the computational complexity of the EPLL deconvolution [26], as well as the deconvolution methods in Levin et al. [11] and Krishnan et al. [5], we generated reduced test datasets for these experiments. From our test dataset (see Section 3.3), we created two subsets to span length and angle. The first subset, subsequently referred to as Length 5 (L5), uses \(5\) randomly selected blurred images for each length, totaling \(500\) images. The second subset, subsequently referred to as Angle 3 (A3) uses \(3\) randomly selected blurred images for each angle, totalling \(540\) images. All images in these reduced test sets are noise free. #### 5.3.3 Error Ratio Comparisons We calculated SSD error ratios for our proposed blur kernel estimation as well as those from Levin et al. [11] and Krishnan et al. [5] as seen in Figure 7. Recall that an error ratio of one indicates that deblurring with the estimated kernel results in an identical image to that deblurred with the ground truth kernel. An error ratio of two or higher is considered unacceptable as it was shown in [24] that such SSD error ratios indicate the presence of significant perceptually noticeable distortions in the latent image estimated using the estimated kernel. An error ratio less than 1 indicates that the image deblurred with the estimated kernel achieves a better match to the true sharp image than deblurring with the true kernel. We note that we have the highest cumulative error ratio at one for both A3 and L5 datasets and that our method yields an error ratio of 1.25 or less for all images in the A3 and L5 test sets. This means that our model is able to predict more accurate kernels compared to the other methods. Since our method creates the kernel using linear parameters we are less prone to additive noise in the kernel. Levin et al.'s [11] kernel prediction has noise added in the kernel since many of the pixels that are supposed to be zero are instead small numbers close to zero. This noise can be seen to affect its results in kernel prediction. Krishnan et al. [19] thresholds the small elements of the kernel to zero which increases robustness to noise. ## 6 Conclusions In this paper, we have studied in detail the limitation in representation of linear blur kernels, particularly for smaller length blurs. We noticed an entanglement between length and angle when it comes to representation of the two parameters, meaning that developing a dataset that is balanced in both length and angle is difficult. Much of the research done in linear blur has implicitly assumed square, odd-sized kernels. Exploring different sized kernels gives a complete implementation of possible linear motion blur kernels that can be discovered in natural blurred images. The complete exploration of linear motion blur gives us an advantage of training a regressive deep learning model instead of a classification model as other deep learning methods implement. With regression we can estimate more accurate blur kernel parameters which are not limited by the model needing a prior predictive kernel size. Our robustness to noise has exceeded that of other methods, even testing to a higher level than most other methods. In particular, we see about a \(10\%\) drop in the \(R^{2}\) metric for a \(10\%\) Gaussian noise. We note, however, that the model trained on 10% Gaussian noise was robust to noise levels less than 10%, indicating that single model can serve across a wide range of noise scenarios. In future work, we will use this exploration of linear motion blur kernels as a baseline and foundation for spatially-varying blurs. We will expand this to a patch level to decompose a spatially-varying blur image into a superposition of locally uniform blur patches. This would give us a locally linear blur field to better model atmospheric turbulence in imagery. ## Acknowledgments The authors gratefully acknowledge Office of Naval Research grant N00014-21-1-2430 which supported this work.
2304.11247
Hybrid quantum physics-informed neural networks for simulating computational fluid dynamics in complex shapes
Finding the distribution of the velocities and pressures of a fluid by solving the Navier-Stokes equations is a principal task in the chemical, energy, and pharmaceutical industries, as well as in mechanical engineering and the design of pipeline systems. With existing solvers, such as OpenFOAM and Ansys, simulations of fluid dynamics in intricate geometries are computationally expensive and require re-simulation whenever the geometric parameters or the initial and boundary conditions are altered. Physics-informed neural networks are a promising tool for simulating fluid flows in complex geometries, as they can adapt to changes in the geometry and mesh definitions, allowing for generalization across fluid parameters and transfer learning across different shapes. We present a hybrid quantum physics-informed neural network that simulates laminar fluid flows in 3D Y-shaped mixers. Our approach combines the expressive power of a quantum model with the flexibility of a physics-informed neural network, resulting in a 21% higher accuracy compared to a purely classical neural network. Our findings highlight the potential of machine learning approaches, and in particular hybrid quantum physics-informed neural network, for complex shape optimization tasks in computational fluid dynamics. By improving the accuracy of fluid simulations in complex geometries, our research using hybrid quantum models contributes to the development of more efficient and reliable fluid dynamics solvers.
Alexandr Sedykh, Maninadh Podapaka, Asel Sagingalieva, Karan Pinto, Markus Pflitsch, Alexey Melnikov
2023-04-21T20:49:29Z
http://arxiv.org/abs/2304.11247v3
# Quantum physics-informed neural networks ###### Abstract Finding the distribution of the velocities and pressures of a fluid (by solving the Navier-Stokes equations) is a principal task in the chemical, energy, and pharmaceutical industries, as well as in mechanical engineering and the design of pipeline systems. With existing solvers, such as OpenFOAM and Ansys, simulations of fluid dynamics in intricate geometries are computationally expensive and require re-simulation whenever the geometric parameters or the initial and boundary conditions are altered. Physics-informed neural networks (PINNs) are a promising tool for simulating fluid flows in complex geometries, as they can adapt to changes in the geometry and mesh definitions, allowing for generalization across different shapes. We present a hybrid quantum physics-informed neural network that simulates laminar fluid flows in 3D Y-shaped mixers. Our approach combines the expressive power of a quantum model with the flexibility of a PINN, resulting in a 21% higher accuracy compared to a purely classical neural network. Our findings highlight the potential of machine learning approaches, and in particular quantum PINNs, for complex shape optimization tasks in computational fluid dynamics. By improving the accuracy of fluid simulations in complex geometries, our research using quantum PINNs contributes to the development of more efficient and reliable fluid dynamics solvers. ## I Introduction Computational fluid dynamics (CFD) solvers are primarily used to find the distribution of the velocity vector,, and pressure, \(p\), of a fluid (or several fluids) given the initial conditions (e.g. initial velocity profile) and the geometrical domain in which the fluid flows [1, 2]. To do this, it is necessary to solve a system of differential equations [3] called the Navier-Stokes (NS) equations that govern the fluid flow [4]. A well-established approach is to use numerical CFD solvers from several vendors, as well as publicly accessible alternatives, such as OpenFOAM [5] or Ansys [6]. These solvers discretize a given fluid volume into several small parts known as cells [7], where it is easier to get an approximate solution and then join the solutions of all the cells to get a complete distribution of the pressure and velocity over the entire geometrical domain. While this is a rather crude explanation of how CFD solvers actually work, the idea of discretizing a large domain into smaller pieces accurately captures one of their main working principles [8]. The runtime of the computation and the accuracy of the solution both sensitively depend on the fineness of discretization, with finer grids taking longer but giving more accurate solutions. Furthermore, any changes to the geometrical parameters necessitate the creation of a new mesh and a new simulation. This process consumes both time and resources since one has to remesh and rerun the simulation every time a geometrical parameter is altered [9]. We propose a workflow employing physics-informed neural networks (PINNs) [10] to escape the need to completely restart the simulations whenever a geometrical property is changed. A PINN is a new promising tool for solving all kinds of parameterized partial differential equations (PDEs) [9], as it does not require many prior assumptions, linearization or local time-stepping. One defines an architecture of the neural network (number of neurons, layers, etc.) and then embeds physical laws and boundary conditions into it via constructing an appropriate loss function, so the prior task immediately travels to the domain of optimization problems. For the classical solver, in the case of a parameterized geometric domain problem, getting accurate predictions for new modified shapes requires a complete restart of the program, even if the geometry has changed slightly. In the case of a PINN, to overcome this difficulty, one can use the transfer learning method [11] (Sec. III.1.2), which allows a model previously trained on some geometry to be trained on a slightly modified geometry without the need for a complete reset. Also, using a trained PINN, it is easy to obtain a solution for other parameters of the PDE equation (e.g. kinematic viscosity in the NS equation [4], thermal conductivity in the heat equation, etc.) with no additional training or restart of the neural network, but in the case of traditional solvers, restarts cannot be avoided. One of the features which makes PINNs appealing is that they suffer less from the curse of dimensionality. Finite discretization of a \(d\)-dimensional cube with \(N\) points along each axis would require \(N^{d}\) points for a traditional solver. In other words, the complexity of the problem grows exponentially as the sampling size \(d\) increases. Using a neural network, however, one can define a \(\mathbb{R}^{d}\rightarrow\mathbb{R}\) mapping (in case of just one target feature) with some weight parameters. Research on the topic suggests that the amount of weights/complexity of a problem in such neural networks grows polynomially with the input dimension \(d\)[12, 13]. This theoretical foundation alone allows PINNs to be a competitive alternative to solvers. It is worth noting that although a PINN does not require \(N^{d}\) points for inference, it does require many points for training. There exist a variety of sampling methods, such as latin hypercube sampling [14], Sobol sequences [15], etc., which can be used to improve a PINN's convergence on training [16]. However, a simple static grid of points is used in this work for the purpose of simplicity. Classical machine learning can benefit substantially from quantum technologies. In [17], quantum computing is used in a similar problem setting. The performance of the current classical models is constrained by the high computing requirements. Quantum computing models can improve the learning process of existing classical models [18; 19; 20; 21; 22; 23], allowing for better target function prediction accuracy with fewer iterations [24]. In many industries, including the pharmaceutical [25; 26], space [27], automotive [28], and financial [29; 30; 31; 32; 33] sector quantum technologies can provide unique advantages over classical computing. Many traditionally important machine learning domains are also getting potential benefits from utilizing quantum technologies, e.g., in image processing [34; 35; 36; 37] and natural language processing [38; 39; 40; 41]. Recent developments in automatic differentiation enable us to compute the exact derivatives of any order of a PINN, so there is no need to use finite differences or any other approximate differentiation techniques. It therefore seems that we do not require a discretized mesh over the computational domain. However, we still need a collection of points from the problem's domain to train and evaluate a PINN. For a PINN to provide an accurate solution for a fluid dynamics problem, it is important to have a high expressivity (ability to learn solutions for a large variety of, possibly complex, problems). Fortunately, expressivity is a known strength of quantum computers [42]. Furthermore, quantum circuits are differentiable, which means that their derivatives can be calculated analytically, which is essential on noisy intermediate-scale quantum devices. In this article, we propose a quantum PINN to solve the NS equations with a steady flow in 3D Y-shape mixer. The general principles and loss function of PINN workflow are described in Sec. II. The problem description, including the geometrical details, is presented in Sec. III while in Sec. III.1 and Sec. III.2, we describe classical and quantum PINNs in detail. Sec. III.1.1 explains the intricacies of PINN's training process and simulation results. A transfer learning approach, applied to PINNs, is presented in Sec. III.1.2. Conclusions and further plans are described in Sec. IV. ## II Physics-informed neural networks for solving partial differential equations Physics-informed neural networks (PINNs) were originally introduced in [10]. The main idea is to use a neural network - usually a feedforward neural network like a multilayer perceptron - as a trial function for a PDE's solution. Let us consider an abstract PDE: \[\mathcal{D}[f(r,t);\lambda]=0, \tag{1}\] where \(\Omega\subset\mathbb{R}^{d}\) is the computational domain, \(r\in\Omega\) is a coordinate vector, \(t\in\mathbb{R}\) is time, \(\mathcal{D}\) is a nonlinear differential operator with \(\lambda\) standing in for the physical parameters of the fluid and \(f(r,t)\) is a solution function. Let us consider a neural network \(u(r,t)\) that takes coordinates, \(r\), and time, \(t\), as input and yields some real value (e.g. the pressure of a liquid at this coordinate at this particular moment of time). We can evaluate \(u(r,t)\) at any point in the computational domain via a forward pass and compute its derivatives (of any order) \(\partial_{t}^{n}u(r,t)\), \(\partial_{r}^{n}u(r,t)\) through back-propagation [43]. Therefore, we could just substitute \(f(r,t)=u(r,t)\) and try to learn the correct solution for the PDE via common machine learning gradient optimization methods [44] (e.g., gradient descent). This approach is inspired firstly by the ability to calculate the _exact_ derivatives of a neural network via autodifferentiation [45] and secondly by neural networks being universal function approximators [46]. The loss, \(\mathcal{L}\), that the PINN tries to minimize is defined as \[\mathcal{L}=\mathcal{L}_{\text{PDE}}+\mathcal{L}_{\text{BC}}, \tag{2}\] where \(\mathcal{L}_{\text{BC}}\) is the boundary condition loss and \(\mathcal{L}_{\text{PDE}}\) is the partial differential equation loss. The boundary condition loss is responsible for satisfying the boundary conditions of the problem (e.g., a fixed pressure on the outlet of a pipe). For any field value, \(u\), let us consider a Dirichlet (fixed-type) boundary condition [47] \[u(r,t)|_{r\in B}=u_{0}(r,t), \tag{3}\] where \(u_{0}(r,t)\) is a boundary condition and \(B\subset\mathbb{R}^{d}\) is the region where a boundary condition is applied. If \(u(r,t)\) is a neural network function (see Sec. II), the boundary condition loss is calculated in a mean-squared error (MSE) manner: \[\mathcal{L}_{\text{BC}}=\langle(u(r,t)-u_{0}(r,t))^{2}\rangle_{B}, \tag{4}\] where \(\langle\cdot\rangle_{B}\) denotes averaging over all the data points \(r\in B\) that have this boundary condition. The PDE loss is responsible for solving the governing PDE. If we have an abstract PDE (1) and a neural network function \(u(r,t)\), substituting \(f(r,t)=u(r,t)\) and calculating the mean-squared error of the PDE gives: \[\mathcal{L}_{\text{PDE}}=\langle(\mathcal{D}[u(r,t);\lambda])^{2}\rangle_{ \Omega}, \tag{5}\] where \(\langle\cdot\rangle_{\Omega}\) means averaging over all the data points in the domain of the PDE. ## III Simulations In this work, we consider the _steady_ (i.e., time-independent) flow of an _incompressible_ fluid in 3D without any external forces. The NS equations (6) and the continuity equation (7) describe this scenario as follows: \[-(v\cdot\nabla)v+\nu\Delta v-\frac{1}{\rho}\nabla p=0, \tag{6}\] \[\nabla\cdot v=0, \tag{7}\] where \(v(r)\) is the velocity vector, \(p(r)\) is the pressure, \(\nu\) is the kinematic viscosity and \(\rho\) is the fluid density. The PDE parameters \(\nu\) and \(\rho\) were previously referred to as \(\lambda\). For each of the 4 PDEs (3 projections of vector equation 6 and 1 scalar equation 7), the \(\mathcal{L}_{\text{PDE}}\) is calculated separately and then summed up. Our task is to simulate the flow of liquid in a Y-shaped mixer consisting of three tubes (Fig. 2). The mixing fluids are identical and have parameters \(\rho=1.0\) kg/m\({}^{3}\) and \(\nu=1.0\) m\({}^{2}\)/s. The imposed boundary conditions are as follows: * no-slip BC on walls: \(v(r)|_{\text{walls}}=0\), * fixed velocity profile on inlets: \(v(r)|_{\text{inlets}}=v_{0}(r)\), * fixed pressure on outlets: \(p(r)|_{\text{outlets}}=p_{0}\), where, in this work, \(v_{0}(r)\) are parabolic velocity profiles on each inlet and \(p_{0}(r)=0\). ### Classical PINN In this section, we provide details on the PINN's architecture, training process, and simulation results. The PINN is a neural network whose architecture is a multi-layer perceptron with several fully connected layers. As shown in Fig. 1, the first layer consists of 3 neurons (since Figure 1: Scheme for the implementation of the hybrid PINN’s training process and its architecture. PINN takes the \((x,y,z)\) coordinates of the points, sampled in the geometrical domain, and yields \((v,p)\) as output, where \(v\) is the velocity vector and \(p\) is the pressure. The neural network itself begins with a classical part, which is a multilayer perceptron with \(l\) layers of \(n\) neurons. Then there is a quantum layer (a variational quantum circuit). “Filter” divides input points into 4 groups, where each group has its own constraint (a boundary condition or a PDE). The error of each constraint is calculated and added to the total loss, which is minimized via gradient descent. The training process is described in Sec. III.1.1. the problem is 3D), then there are \(l=5\) hidden layers with \(n=64\) neurons, and the penultimate layer has 16 neurons. For the classical PINN, the "quantum layer" box is replaced with one fully-connected layer \(16\to 4\). There is no quantum layer in the classical case, so the output goes straight into the filter. Between adjacent layers, there is a sigmoid linear unit (SiLU) activation function [48]. The PINN takes the \((x,y,z)\) coordinates as inputs and yields \((v,p)\) as its output, where \(v\) is the velocity vector with three components and \(p\) is the pressure. #### ii.2.1 Training The geometry is a collection of points organized in a.csv file. It is split into four groups: fluid domain, walls, inlets, and outlets. The fluid domain is the domain in which the NS equations are solved, i.e. where the fluid flows. The other three groups have boundary conditions described in Sec. II. While untrained, PINN produces some random distribution of velocities and pressures. These values and their gradients are substituted into the corresponding NS equations and boundary conditions. With every iteration, the weights of the neural network are updated to minimize the error in the governing equations, and our solution becomes more and more accurate. The PINN is trained via full-batch gradient descent with the Adam optimizer [49] for 1000 epochs, and then with L-BFGS optimizer [50] for 100 epochs. All points from the geometrical domain are processed at once, so one step of the optimizer equals one epoch. The training iteration is simple: the point cloud is passed through the PINN, the MSE loss is calculated (getting it requires taking gradients of \((v,p)\) at each point of the geometry), the gradient of the loss with respect to the weights is taken and the parameters are updated. Classical PINN training (1100 total epochs) took 5 minutes on single NVIDIA A100 GPU. To visualize the training outcomes of the neural network, we used ParaView [51] and the simulation results are shown in Fig. 2 (1) for loss and velocity distribution. After the training, the PINN manages to learn a non-trivial downward flow at the beginning of both pipes. On the edges of these pipes, the velocities become zero, as they should due to no-slip wall boundary conditions. However, further down the mixer, the solution degener Figure 2: 1) Classical model. (a) Loss curve. The classical PINN managed to learn solution near the entry point well. However, it vanishes to zero further down the mixer. 2) Transfer learned models. (a) Loss curve. The transfer-learned models trained better with each iteration, surpassing the original model. (b, c, d) Distributions of the fluid velocity for the last model with \(\alpha=35^{\circ}\). ates to zero, so it does not even reach the mixing point. This fact should at least violate the continuity equation because there is an inward flow without matching outward flow, but the model still treats this situation as an optimum and refuses to propagate the solution further. Possible reasons for this could be a mismatch between the scales of the different loss terms (continuity, NS and BC) in the total loss, the limited expressivity of the underlying neural network, the points sampling strategy or the choice of the optimizer. Still, we stick to our simple workflow and use this incomplete solution as a reference to further explore the properties of the PINN without overcomplicating the problem. #### iii.1.2 Transfer Learning Transfer learning is a powerful method of using the knowledge and experience of one model that has been pretrained on one problem to solve another problem [11]. It is extremely useful because it means that a second model does not have to be trained from scratch. This is especially helpful for fluid modeling where the crucial issue of selecting the most appropriate geometrical hyperparameters would otherwise lead to the simulations being rerun many times. For transfer learning, we used a model from the previous section as a base, which had \(\alpha_{0}=30^{\circ}\), where \(\alpha\) is the angle between the right pipe and the \(x\) axis (see Fig. 2). Then, for each \(\alpha=\{31^{\circ},32^{\circ},33^{\circ},34^{\circ},35^{\circ}\}\), we tried to obtain the solution, each time using the previously trained model as a initializer. For example, to transfer learn from \(31^{\circ}\) to \(32^{\circ}\), we used the \(31^{\circ}\) model as a base and so on. Each iteration is trained for 100 epochs with L-BFGS. Fig. 2 shows that the PINN adapts well to changes in the value of \(\alpha\). That is, our hypothesis was correct: with PINNs, one does not need to completely rerun the simulation on a parameter change, transfer learning from the base model will suffice. ### Hybrid Quantum PINN Quantum machine learning may help to improve the performance of the classical PINN. We propose a quantum PINN, which is a hybrid quantum-classical neural network. In the Noisy Intermediate-Scale Quantum (NISQ) era, when quantum computers do not have access to a quantum memory or a large number of qubits, the algorithms that are known to be superior to classical ones cannot be implemented. Heuristic quantum algorithms, however, have less stringent requirements for their implementation. Here, we use a variational quantum circuit (VQC) approach, which is one of the most promising NISQ algorithms today. It combines the best ideas of classical and quantum machine learning [52, 53, 54, 55]. At the moment, using only VQCs is not enough to solve large problems, especially for industrial tasks, so several more classical neural layers are used with a VQC (hence the name, "hybrid"). Also, the use of a large number of qubits and layer repetitions leads to the barren plateau problem [56, 57]. As an overview of the workflow, preliminary data processing takes place on a classical computer. This data is then encoded into the parameters of the quantum gates of an encoding layer of the VQC, followed by a variational layer. As the algorithm progresses, the gate parameters in the variational layer of the VQC are varied and finally, in the measurement layer of the VQC the qubits are measured, producing a set of classical bits as the output. A quantum algorithm can be represented as a kind of black box into which classical information enters, classical information comes out. The goal is to choose such variational parameters so that the measurement result is as accurate as possible in terms of the prediction function. In this way, finding the optimal gate parameters is like finding the optimal weights in a classical neural network. Hence, we refer to this as training the VQC. #### iii.2.1 Variational Quantum Circuit Quantum gates are the basic building blocks for any quantum circuit, including those used for machine learning. Quantum gates come in single-qubit (e.g. rotation gate \(R_{y}(\theta)\), gate that plays a central role in quantum machine learning) and multiple-qubit gates (e.g. CNOT) and modulate the state of qubits to perform computations. The \(R_{y}(\theta)\) gate rotates the qubit around the y-axis of the Bloch sphere by an angle \(\theta\), while the two-qubit CNOT gate changes the state of one qubit based on the current state of another qubit. Gates can be fixed, which means they perform fixed calculations, such as the Hadamard gate, or they can be variable, such as the rotation gate that depends on the rotation angle and may perform computations with tunable parameters. To get the results, the qubits are measured (i.e., projected onto some basis) and the expected value is calculated. If we use the \(\sigma_{z}\) Pauli matrix observable, the expected value of that measurement is expressed as: \(\left\langle\psi\right|\sigma_{z}\left|\psi\right\rangle\), where \(\psi\) is the wave function which describes the current state of our quantum system. An introduction to quantum circuits, including logic gates and measurements, can be found in standard quantum computing textbooks, such as [58]. #### iii.2.2 Training The hybrid PINN consists of the classical PINN with weights preinitialized from the previous stage (as described in Sec. III.1), a VQC and a fully-connected layer at the end. The VQC's design is inspired by [59]. The training process of the hybrid PINN does not differ from that of the classical PINN except in the following ways. Firstly, all calculations are done on the classical simulator of quantum hardware, the QMware server [60], which has recently been shown to be quite good for running hybrid algorithms [61]. Secondly, how does one backpropagate through the quantum circuit layer? The answer is to use the "adjoint differentiation" method, introduced in [62], which helps to efficiently compute derivatives of a VQC on a classical simulator. This time the model was trained for 100 epochs using mini-batch gradient descent with the Adam optimizer (Fig. 3). The mini-batch strategy was employed due to the very low speed of training of quantum circuits, as they train on a CPU. We will then compare this model with a purely classical one, with exactly the same architecture from Sec. III.1, but this time trained only with mini-batch Adam. All learning hyperparameters (learning rate, scheduler parameters, batch size) are shared between the quantum and classical model. Comparing the two, Fig. 4 shows that the quantum model outperforms the classical one in terms of the loss value by 21%. We tried to do inference of our model on real quantum processing units (QPUs) Lucy [63] and Rigetti's Aspen-M-3 [64]. That means, we have chosen some points from the geometrical domain and predicted velocity and pressure fields for them. On comparison, results from both QPUs greatly differ from the simulator ones. Most likely, these errors are caused by noise and decoherence, which are hard to mitigate. Also, particular QPUs work better with circuits that take into account their particular topology and gate implementations. We did not consider such limitations, as the primary tests of our quantum circuit were conducted on a simulator. ## IV Discussion In this work we examine a recently introduced [10] way of solving computational fluid simulation tasks, PINNs. This approach is based on substituting the solution function of the problem with a neural network of an arbitrary architecture (a multi-layer perceptron is used in this work) and optimizing trainable parameters via gradient descent (Adam, L-BFGS). In this problem setting, the loss function becomes a combination of the residual error of corresponding PDE and boundary conditions. We try to use this approach to solve a laminar mixing problem in a 3D Y-shaped geometrical domain and achieve plausible solution in the upper part of the mixer. The solution, Figure 4: Losses for the classical and hybrid quantum PINNs. Hybrid quantum PINN outperforms the classical PINN in terms of loss value due to higher expressivity. Figure 3: Hybrid quantum model. (a) Loss curve. (b, c, d) Distribution of the fluid velocities for the hybrid PINN at (\(\alpha=30^{\circ}\)). Similarly to the classical model, a non-trivial solution near the entry point is present. However, there is an asymmetry between the left and the right pipe, which should not be there. This could be an effect of the data encoding strategy. however, vanishes to zero as it goes lower through the mixer. The reason behind such behaviour could be insufficient expressivity of the model, static point sampling or even the choice of the optimizers. We then explore a transfer learning technique with application to a classical PINN, which shows that the PINN is actually capable of generalizing an existing solution to a weakly changed geometrical domain with little additional training. This enables PINNs to be very helpful in shape optimization tasks because traditional solvers lack this feature and demand a full restart on any parameter change. Also, with each step of the angle \(\alpha\), we see that the PINN achieves an even lower loss than before. It may be that this step-by-step learning helps the PINN to mitigate overfitting to a particular geometrical domain of the problem. Afterwards, we introduce a new PINN framework - a quantum PINN. We build it on top of a classical fully-connected PINN by adding a quantum circuit with trainable gates. We explore the potential of this model to solve the NS equations and show its superiority to purely classical network in terms of the loss value on 21%, which could mean that the chosen quantum circuit increases the PINN's expressiveness. The future plan includes exploring better architectures for the quantum PINN, investigating their impact on expressiveness, generalizability and optimization landscape, as well as trying out data-driven approaches. Entirely different networks, such as neural operators [65; 66] and graph neural networks [67; 68], could also be considered in a quantum setting and enhanced with quantum circuits.
2306.01639
Reduction of finite sampling noise in quantum neural networks
Quantum neural networks (QNNs) use parameterized quantum circuits with data-dependent inputs and generate outputs through the evaluation of expectation values. Calculating these expectation values necessitates repeated circuit evaluations, thus introducing fundamental finite-sampling noise even on error-free quantum computers. We reduce this noise by introducing the variance regularization, a technique for reducing the variance of the expectation value during the quantum model training. This technique requires no additional circuit evaluations if the QNN is properly constructed. Our empirical findings demonstrate the reduced variance speeds up the training and lowers the output noise as well as decreases the number of necessary evaluations of gradient circuits. This regularization method is benchmarked on the regression of multiple functions and the potential energy surface of water. We show that in our examples, it lowers the variance by an order of magnitude on average and leads to a significantly reduced noise level of the QNN. We finally demonstrate QNN training on a real quantum device and evaluate the impact of error mitigation. Here, the optimization is feasible only due to the reduced number of necessary shots in the gradient evaluation resulting from the reduced variance.
David A. Kreplin, Marco Roth
2023-06-02T15:59:47Z
http://arxiv.org/abs/2306.01639v3
# Reduction of finite sampling noise in quantum neural networks ###### Abstract Quantum neural networks (QNNs) use parameterized quantum circuits with data-dependent inputs and generate outputs through the evaluation of expectation values. Calculating these expectation values necessitates repeated circuit evaluations, thus introducing fundamental finite-sampling noise even on error-free quantum computers. We reduce this noise by introducing the variance regularization, a technique for reducing the variance of the expectation value during the quantum model training. This technique requires no additional circuit evaluations if the QNN is properly constructed. Our empirical findings demonstrate the reduced variance speeds up the training and lowers the output noise as well as decreases the number of necessary evaluations of gradient circuits. This regularization method is benchmarked on the regression of multiple functions. We show that in our examples, it lowers the variance by an order of magnitude on average and leads to a significantly reduced noise level of the QNN. We finally demonstrate QNN training on a real quantum device and evaluate the impact of error mitigation. Here, the optimization is feasible only due to the reduced number of necessary shots in the gradient evaluation resulting from the reduced variance. ## I Introduction The methods of quantum machine learning are among the most promising approaches to achieve a quantum advantage in today's era of noisy intermediary quantum (NISQ) computers.[1; 2; 3] Quantum machine learning (QML) offers significant flexibility in the design of quantum circuits, allowing for the use of short and hardware-efficient circuits. These circuits may operate more effectively on noisy hardware compared to problem-driven approaches as for example quantum optimization or quantum chemistry. In this young field, mainly two approaches are followed to develop machine learning algorithms on NISQ hardware. The first approach utilizes the exponentially large Hilbert space that is accessible by a quantum computer for the so called kernel trick.[4] Here, the input data is embedded into a high dimensional space enabling linear regression or classification within this space.[5] On a quantum computer, this is achieved by using a quantum feature map,[6; 7] a circuit in which data is encoded into a quantum state, for example by using rotation gates.[8] Optionally, the quantum feature map may contain additional trainable parameters that enable an adaption of the feature map for the given data.[9; 10; 11] The feature map is also utilized in the second QML approach, in which the output of the QML model are either probabilities of measuring qubits in a certain computational state or expectation values of manually chosen operators.[3; 12] This approach follows the principles of variational quantum algorithms,[2] and in this context, the feature map is more commonly referred to as a parameterized quantum circuit (PQC).[13] It is also possible to use quantum states directly as an input and manipulate the state by a trainable circuit before measuring it.[14; 15; 16; 17] In the following we denote the second QML approach as Quantum Neural Networks (QNNs) since it is the most established name today.[18] Parameters of QNNs are often optimized by minimizing a loss function similar to the training of a classical artificial neural network (ANN) by gradient descent.[12; 19; 20] Differentiation of the expectation value is possible for example by the parameter-shift rule, in which the analytic derivative is obtained through evaluations of the expectation value with shifted parameter values.[12; 21; 22] Recent research on QNNs has placed a strong emphasis on understanding their mathematical properties and investigating their advantages and disadvantages. Like ANNs, QNNs also offer universal function approximation,[23; 24] which can already be achieved on the single-qubit level.[25] Furthermore, QNNs can reach a high expressivity by the repeated encoding of the input data, also known as data re-uploading.[26; 24; 27] An open question is whether the high expressivity of QNNs is more of a problem than a feature, as it can also easily lead to overfitting of the data. On the other hand, research has also demonstrated that QNNs can achieve good generalization[28] with only few data points.[29] Another important topic in the study of QNNs is the phenomenon of barren plateaus, which refers to the observation that the variance of the gradient vanishes exponentially. The issue is a well-known challenge[30; 31] caused by various sources.[32; 33; 34; 35] While specially designed PQCs have shown promise in avoiding this issue,[36; 37] another source of barren plateaus arises from noise that can occur during evaluation on real hardware.[38; 39] Despite hardware-related noise potentially being reduced in the future, there will always be some level of noise resulting from the finite sampling of the quantum state. In this work, we address the challenge of handling finite sampling noise in QNNs within the constraints of the NISQ era, where a massive number of repeated evaluations of a quantum circuit is currently not feasible. Today, evaluating a circuit with a larger number of shots comes with long execution times and high financial costs, and therefore, the number of shots is often fixed to a maximum number.[40] As this is a technological issue that is not provider-specific and given the fact that the optimization of a QNN typically requires the evaluation of thousands of circuits, finite sampling noise can be a significant obstacle in training QNNs on real hardware. Additionally, access to quantum computers is often granted by a pay-per-shot plan,[41] which can result in considerable costs for the full training of a QNN. Therefore, reducing the number of shots is a practical and crucial goal in the current NISQ era of quantum computing. The standard deviation (STD) associated with the finite sampling noise of the expectation value \(E[\hat{H}]=\langle\Psi|\hat{H}|\Psi\rangle\) of some operator \(\hat{H}\) is calculated as: \[\text{std}(E[\hat{H}])=\sqrt{\frac{\text{var}(E[\hat{H}])}{N_{\text{shots}}}}, \tag{1}\] where \(\text{var}(E[\hat{H}])\) represents the variance of the expectation value. The formula shows that the finite sampling noise of the expectation value decreases with \(O(1/\sqrt{N_{\text{shots}}})\) as the number of shots \(N_{\text{shots}}\) increases. However, since the number of shots is practically limited in current NISQ devices, we propose an alternative approach that reduces \(\text{std}(E[\hat{H}])\) by lowering the variance of the expectation value. In QNNs, the PQC that generates the wavefunction \(|\Psi\rangle\) and the operator \(\hat{H}\) are free to choose, and they can be optimized to reduce the variance. We show that a significant reduction of the finite sampling noise can be achieved by adding the variance of the QNN as a regularization term in the loss function. This approach ensures that the training of the QNN not only optimizes the fitting loss but also significantly reduces the variance of the output. The paper is structured as follows: In Section II, we provide a technical introduction to QNNs and our concept of variance regularization. Section III presents an introductory example that demonstrates the impact of variance regularization on a selected problem. Next, in Section IV, we delve into the details of how variance regularization can be incorporated into the optimization procedure. We further discuss more deeply the optimization for a regression of the logarithm function and present results for two other functions. Section V focuses on evaluating the performance of QNNs on real quantum computing hardware, and we provide an overview of the optimization procedure conducted on the real hardware. Finally, we examine the combination of variance regularization and error mitigation techniques, specifically zero-noise extrapolation. ## II Variance regularization The QNN employed in this works utilizes a PQC, denoted as \(\hat{U}\), to encode the classical input data \(x\in\mathbb{R}\) into a quantum state \(\ket{\Psi}\) and manipulate the quantum state using additional parameters \(\varphi\): \[\ket{\Psi(x,\varphi)}=\hat{U}(x,\varphi)\ket{0}. \tag{2}\] Practically, the PQC \(\hat{U}(x,\varphi)\) is primarily constructed from one- and two-qubit gates, and often rotational gates are utilized for encoding data and manipulating the quantum state. Employing repeated input encoding techniques enhances the expressibility of the circuit.[27] An example of a PQC used in this study can be found in Figure 1. The output of the QNN, denoted as \(f(x)\), is obtained by evaluating the expectation value of a cost operator \(\hat{C}(\phi)\) as follows: \[f_{\varphi,\phi}(x)=\langle\Psi(x,\varphi)|\hat{C}(\phi)|\Psi(x,\varphi) \rangle\,. \tag{3}\] In scenarios where multiple outputs are desired from the QNN, an individual cost operators \(\hat{C}_{j}(\phi_{j})\) can be used for each output. In such cases, the QNN output \(f\) is considered as a vector containing the expectation values of each respective cost operator. When there is no need to distinguish between the parameters \(\varphi\) of the PQC and the parameters \(\phi\) of the cost operators, they can be combined into a single parameter vector \(\theta\). For convenience, the explicit dependency on the parameters is often neglected in the subsequent discussions. The parameters \(\theta\) of the QNN are determined through the minimization of a loss function \(L_{\text{fit}}(\theta)\). The choice of the loss function depends on the specific task at hand and plays a crucial role in the model's performance. It is common to adapt and utilize classical machine learning loss functions within the context of QNNs. In this work, we mainly focus on regression for which a possible loss function is given by the squared error (named in the following fitting loss): \[L_{\text{fit}}(\theta)=\sum_{i}||f_{\theta}(x_{i})-y_{i}||^{2}. \tag{4}\] Here, we consider a set of input data \(\{x_{i}\in\mathbb{R}^{d}\}\) and their corresponding labels \(\{y_{i}\in\mathbb{R}\}\) within a supervised learning scenario. In case of a classification task the cross-entropy loss function is often employed.[42] Moreover, alternative loss functions empower the QNN to tackle other problems such as differential equations.[43] The optimization of the parameters \(\theta\) involves minimizing the loss function which can be challenging because the loss function is typically non-convex. Therefore, gradient-based optimization methods are commonly employed to address this task.[20] To obtain derivatives with respect to the parameters \(\varphi\) of the PQC, one approach is the parameter-shift rule.[12; 21; 22] In this method, the parameter is shifted in each gate by a specific value and the analytic derivative is obtained by the difference of the resulting expectation values. Consequently it is necessary to evaluate two circuits for each gate containing the parameter. However, when dealing with PQCs that consist of numerous parameterized gates, the evaluation of the resulting amount of circuits can become a computational bottleneck, particularly when utilizing state-of-the-art quantum hardware. While alternative approaches, such as the linear combination of unitaries[44; 45] do exist, it is important to consider that these approaches may be more vulnerable to hardware noise when compared to the parameter-shift rule. The differentiation with respect to the cost operator parameters \(\phi\) is straightforward: \[\partial_{\phi_{m}}f_{\theta}(x)=\langle\Psi(x,\varphi)|\big{(} \partial_{\phi_{m}}\hat{C}(\phi)\big{)}|\Psi(x,\varphi)\rangle\,. \tag{5}\] The derivative \(\partial_{\phi_{m}}\hat{C}(\phi)\) of the cost operator can be often evaluated from the same measurement as the expectation value of the cost operator. In our routines, we reuse the results from the circuit evaluation of the cost operators to calculate these derivatives. Once the loss function is minimized to a satisfactory low value, the QNN is considered to be trained and the model can be used to obtain new predictions by inputting new data into Eq. (3). However, it is important to keep in mind that the output of the model is determined by the stochastic process of measuring the expectation value, and therefore, in contrast to classical ANNs, the output contains noise. The standard deviation of the expectation value, i.e. the model output, is obtained by (cf. Eq. (1)): \[\text{std}(f)=\sqrt{\frac{\sigma_{f}^{2}}{N_{\text{shots}}}}. \tag{6}\] The variance \(\sigma_{f}^{2}\) of the QNN can be computed by \[\sigma_{f}^{2}=\left\langle\Psi|\hat{C}^{2}|\Psi\right\rangle-\left\langle \Psi|\hat{C}|\Psi\right\rangle^{2}. \tag{7}\] In case of multiple outputs, the standard deviation is obtained for each output by evaluating the variance for each cost operator \(\hat{C}_{j}\) separately. In the following we utilize the variance as a regularization during the optimization of the QNN in order to reduce the noise of the model output. This is achieved by adding the following term to the loss function that minimizes the variance of the function at a set of points \(\{\tilde{x}_{k}\}\): \[L_{\text{var}}(\theta)=\sum_{k}||\sigma_{f}^{2}(\tilde{x}_{k})||, \tag{8}\] where \(||.||\) is a suitable vector norm. The total loss that is minimized during the training procedure is the sum \[L=L_{\text{fit}}+\alpha L_{\text{var}}. \tag{9}\] The hyper-parameter \(\alpha>0\) is used to adjust the balance between the fitting error and the variance reduction of the model. In our experience, a value between \(10^{-2}\) and \(10^{-4}\) yields the satisfying results. The choice of \(\{\tilde{x}_{k}\}\) is in principle arbitrary and should evenly capture the domain space of the input data. We assume that the training data is a good representation of the model domain, and therefore, we will set \(\{\tilde{x}_{k}\}=\{x_{i}\}\) in the following. This approach offers the advantage of reusing the circuits and function evaluations of \(f(x)\) from the fitting loss \(L_{\text{fit}}\). The computationally complexity of \(\left\langle\Psi|\hat{C}^{2}|\Psi\right\rangle\) strongly depends on the choice of the \(\hat{C}\). If the operator is idempotent, i.e. \(\hat{C}=\hat{C}^{2}\), the evaluation of this term comes with no additional costs. For example, this is the case for the probability \(p_{n}(0)\) (or \(p_{n}(1)\)) of a single qubit \(n\), since this is equivalent to a cost operator of \(\left|0\right\rangle\left\langle 0\right|_{n}\) (or \(\left|1\right\rangle\left\langle 1\right|_{n}\)) in which \(n\) labels the qubit. When the operator is diagonal in the computational basis, it becomes feasible to evaluate the expectation value of the squared operator using the same circuit measurements as those employed for function evaluation. This scenario occurs for example when the operator solely consists of Pauli operators \(\hat{I}\) and \(\hat{Z}\), as observed in Ising Hamiltonian with the following form: \[\hat{C}=\phi_{1}\hat{I}+\phi_{2}\sum_{p}\hat{Z}_{p}+\phi_{3}\sum_{p>q}\hat{Z} _{p}\hat{Z}_{q}\,. \tag{10}\] This is also true for the evaluation of the gradient of the variance: \[\nabla_{\theta}\sigma_{f}^{2}=\nabla_{\theta}\left\langle\Psi|\hat{C}^{2}| \Psi\right\rangle+2\left\langle\Psi|\hat{C}|\Psi\right\rangle\nabla_{\theta} \left\langle\Psi|\hat{C}|\Psi\right\rangle. \tag{11}\] The second term is computed from the intermediates that are also used in the gradient computation of the loss function \(L_{\text{fit}}\). The derivatives of the first term are obtained using the same circuits and measurements as those used for calculating the gradient of the function. However, extra work is introduced in the classical post-processing, to evaluate the additional expectation values from the measurements. For operators \(\hat{C}\) that are not necessarily diagonal in the computational basis, evaluating the squared cost operator may require additional evaluations of quantum circuits. This can make the application of variance regularization impractical in variational quantum eigensolvers, for example when dealing with molecules. However, the variance in variational quantum eigensolver results is already reduced because the wavefunction \(\Psi\) approximates an eigenstate of the operator. This is not necessarily the case for QNNs or other variational algorithms since the optimization process aims to minimize the loss function instead of the expectation value, making an additional reduction of the variance interesting. ## III Introductory example In this section, we present an illustrative example that demonstrates how variance regularization significantly enhances the robustness of a QNN against finite-sampling noise within a shot-based simulation. This example also highlights that a perfect fit, derived from a noise-free simulation, could inadvertently introduce a substantial variance of the expectation value. Consequently, this would necessitate a significantly large number of shots for an accurate evaluation. We want to point out that this effect should be taken into account when interpreting results from QNNs that are entirely sourced from noise-free simulators. Figure 1 displays the PQC that is utilized throughout this work. We use the Chebyshev input encoding in which the input data is first encoded by a \(\cos^{-1}(x)\) function.1 The use Figure 1: Parameterized quantum circuit of the QNN used in all examples in this work. The first layer of \(\hat{R}_{y}\) gates manipulates the initial state. The blueish highlighted layer includes the Chebychev input encoding in the \(\hat{R}_{x}\) gates as well as the parameterized control manipulation of the quantum state. The layer is repeated \(I\) times for a repeated input encoding. The last layer of \(\hat{R}_{y}\) gates serves as a change of the basis that is used for measurement. For a hardware efficient approach, the rightmost controlled gate in the blueish layer is removed to avoid swapping. of the inverse cosine implies a rescaling of the input data to \([-1,1]\). Using this non-linear input encoding as angles in rotation gates around the x-axis yields the following identity for integer \(n\):[43] \[\hat{R}_{x}(n\cos^{-1}(x))=T_{n}(x)\hat{I}-i\sqrt{1-x^{2}}U_{n-1}(x)\hat{X}\,, \tag{12}\] in which \(T_{n}(x)\) and \(U_{n}(x)\) are the first and second kind Chebyshev polynomials of degree \(n\).[46]\(\hat{X}\) denotes the Pauli-X operator. In contrast to previous works, we introduce a parameter \(\varphi\) instead of a fixed value for \(n\) which enables a flexible optimization of the degree of the Chebyshev polynomials during the training. An example of curves generated using Chebyshev polynomials with a non-integer value of \(n\) is presented in the Supplementary Section VII.1. These curves demonstrate a smooth transition between the individual Chebyshev polynomials. The initial values for the parameters in the encoding are chosen to be evenly distributed between \(\varphi_{l,1}=0.01\) and \(\varphi_{l,N_{q}}=\beta\) following the idea of the Chebyshev tower approach.[43] Here and in the subsequent sections, \(N_{q}\) denotes the number of qubits. The initial value \(0.01\) is chosen to avoid a redundancy in the parameter that occurs for \(\varphi=0.0\), and \(\beta\) is considered as a hyper-parameter of the model. The quantum state from the input encoding is manipulated by a hardware efficient approach of \(\hat{R}_{zz}(\varphi)=\exp(-i\frac{\varphi}{2}\hat{Z}\otimes\hat{Z})\) two-qubit interaction gates that are arranged in a nearest neighbor entangling set-up. The \(\hat{R}_{y}\) gates at the beginning and the end of the feature map enable a basis change of the initial state and the measuring basis. Both are also optimized during the training. In this introductory example, we choose the Ising Hamiltonian introduced in Eq. (10) as the cost operator. The parameters \(\phi_{1}\) to \(\phi_{3}\) of the Ising Hamiltonian are also optimized in the optimization. The first parameter \(\phi_{1}\) introduces a constant offset of the output of the QNN. The specific selection of this operator exemplifies a scenario where a large variance is observed after the training process. The PQC of the QNN is introduced in Figure 1, and \(N_{q}=4\) qubits and \(l=2\) layers are chosen. The optimization of the loss function, i.e. the training, is conducted using the noise-free simulator of Qiskit,[47] and it is performed with and without the variance regularization. Figure 2 displays the inference of the trained QNN with and without finite sampling noise. The top plot illustrates the QNN obtained without variance regularization, while the plot at the bottom demonstrates the outcomes with variance regularization. Note that the noise free output of the QNN, represented by the dotted black line, accurately reproduces the logarithm function in both plots. The results of the shot-based simulator, here the QASM simulator in Qiskit,[47] are computed utilizing \(10\,000\) shots. By incorporating the variance regularization, the averaged variance of the trained QNN is reduced significantly by a factor of \(85\). This reduction in variance impacts the model's precision, and it leads to an increase in the squared error from \(9.3\cdot 10^{-5}\) to \(8.3\cdot 10^{-3}\) in the noise-free optimization. However, there is no substantial visual difference observed in the noise-free outcome for these low fitting losses. This picture changes when considering the results of the shot-based simulations. Here, the difference between the evaluation of the QNN with the parameters obtained with and without variance regularization during the training is substantial. While the former results in a drastically noisy inference, the latter is difficult to visually distinguish from the noise-free result. Effectively, the \(85\)-fold reduction in variance implies that the same level of shot noise can be achieved with \(85\) times fewer shots. Alternatively, if the number of shots is kept constant (as depicted in Figure 2), the standard deviation (cf. Eq. (6)) is reduced by a factor of \(9.2\). The example without variance regularization further illustrates that the QNN obtained through training with a noise-free simulator may not be practical for evaluations on a shot-based backend. Despite its high accuracy, the solution without variance regularization would require approximately \(850\,000\) shots to achieve a similar result as the QNN trained with variance regularization. The cost operator presented in Eq. (10) exhibits limited flexibility due to its inclusion of only three free parameters. Additionally, the two-body interaction term is not well-suited for calculating the variance, as classical post-processing scales with \(O(N_{q}^{4})\). In the subsequent sections, we will utilize a different operator for our experiments, given by: \[\hat{C}(\phi)=\phi_{0}\hat{I}+\sum_{p}^{N_{q}}\phi_{p}\hat{Z}_{p}. \tag{13}\] Our experiments have shown this operator to be more versatile and less susceptible to shot noise in general. Therefore, all the results presented in the following sections are obtained using this cost operator. Figure 2: The output of the QNN is evaluated for two cases: trained with (lower figure) and without (upper figure) variance regularization. The training is conducted using a noise-free simulator, and the output is computed with and without shots. For the shot-based simulation, \(10\,000\) shots are utilized. ## IV Optimization with variance regularization In this section, we show numerical evidence for the benefits of using the variance regularization approach introduced in the previous section. In the following optimization we compare two approaches for choosing the parameter \(\alpha\) in the variance regularization (cf. Eq. (9)). In the first approach, the parameter remains constant throughout the optimization process. The second approach involves adjusting the parameter dynamically during optimization. The objective is to initially force the QNN to significantly reduce the variance and then gradually transition towards a regime where the squared error (cf. Eq. (4)) dominates the total loss. This approach results in a significantly lower final variance value. An additional benefit of reducing the variance at the beginning is the ability to use a lower number of shots in the initial iterations. The parameter \(\alpha\) is determined using a modified sigmoid function, given by: \[\alpha_{a,b,v}(i)=(1-v)\frac{b\exp(a(b-i))}{b\exp(a(b-i))+1}+v. \tag{14}\] Here, the parameter \(v\) represents the strength of the variance regularization at the end of the training, and \(b\) defines the width of the plateau in the initial phase when the optimization primarily focuses on reducing the variance of the function. The parameter \(a\) determines the slope of the decay in the regularization parameter. A plot illustrating the regularization parameter \(\alpha_{a,b,v}\) for various parameter values is presented in Figure 3. In addition, the number of shots for evaluating the gradient is adjusted during the optimization. It is readily apparent that a higher number of shots at the beginning of the optimization is not needed, since a precise evaluation is not beneficial in case of a large fitting error. In this section, we introduce a procedure that automatically adjusts the number of shots during the evaluation of the gradient circuits. It is based on the relative standard deviation (RSD) of the fitting loss \(L_{\text{fit}}\) (4). The number of shots are adjusted such that the RSD is lower than a predefined boundary. By using the approximation [48]\(\text{var}(f(X))\approx(f^{\prime}(E[X]))^{2}\text{var}(X)\) one obtains for the variance of the fitting loss \(L_{\text{fit}}\): \[\text{var}(L_{\text{fit}})=4\sum_{i}(f_{\theta}(x_{i})-y_{i})^{2}\frac{\sigma _{f}^{2}(x_{i})}{N_{\text{shots}}}. \tag{15}\] Empirically, we have observed that this approach also provides a good approximation of the variance of the total loss function \(L\), with the variance of \(\text{var}(L_{\text{var}})\) being notably lower. During the initial stages of optimization, the fitting error dominates the variance of the total loss. Furthermore, as the optimization progresses and the regularization parameter \(\alpha\) becomes smaller, the contribution of the variance loss to the total variance diminishes to a negligible extent. Using Eq. (15), the relative standard deviation of the fitting error can be expressed as follows: \[\text{rsd}(L_{\text{fit}})=\frac{\sqrt{4\sum_{i}(f_{\theta}(x_{i})-y_{i})^{2} \frac{\sigma_{f}^{2}(x_{i})}{N_{\text{shots}}}}}{\sum_{i}(f_{\theta}(x_{i})-y _{i})^{2}}<\beta. \tag{16}\] The number of shots for evaluating the circuits of the gradient computation is obtained by setting an upper limit of the RSD by a predefined hyper-parameter \(\beta\). Additionally, a minimum (100) and maximum number of shots is set. In our experience, a value of \(\beta=0.1\) is enough for a gradient evaluation that does not negatively impact the optimization compared to an optimization with the given maximum number of shots. The criterion for determining the number of shots was designed in such a way that no additional evaluations of quantities are required. The values of \(f_{\theta}(x_{i})\) and \(\sigma_{f}^{2}(x_{i})\) are already included in the loss function and are evaluated with the maximum number of shots. Subsequently, the number of shots in the evaluation of the circuits needed for the gradient computation is adjusted. The variance of the loss function, theoretically, does not provide any information about the variance of its gradient. We are not aware of any boundaries that can be derived for the gradient of the loss function without introducing additional circuit evaluations and expectation value calculations. As a result, there is no theoretical guarantee for determining the correct number of shots to ensure a predefined noise level for the gradient. However, empirically, we have found that this approach yields satisfactory results, and it achieves a similar optimization performance compared to working with the maximum number of shots. Figure 4 illustrates the optimization process for fitting the logarithmic function. Displayed from top to bottom are the variance loss, the fitting loss, and number of shots used in the gradient evaluation. The left panel of Figure 5 presents the training data used in the optimization, and the final fit. The figure showcases three different scenarios of variance regularization: (i) blue represents no variance regularization, (ii) green corresponds to a constant regularization parameter \(\alpha=0.005\), and (iii) orange represents the regularization parameter \(\alpha_{a,b,v}\) that changes during the iteration following the blue curve in Figure 3. The QNN employed is based on the PQC depicted in Figure 1. It utilizes \(N_{q}=10\) qubits, \(l=3\) layers, and the Figure 3: Different regularization parameter functions \(\alpha_{a,b,v}(i)\) for various combinations of \(a\), \(b\) and \(v\). The blue curve with \(a=0.08,b=20,v=0.005\) is used for the experiments throughout this paper. cost operator introduced in Eq. (13). The optimization is performed by ADAM [49] with a learning rate of 0.1 utilizing IBM's shot-based QASM simulator with a maximum of 5000 shots. The dashed lines in the plots represent statevector simulations without any noise. The shot-based optimization is repeated 10 times with the same initial parameters, and the individual results are displayed using thin lines. The solid lines represent the averaged result over the 10 runs. We first discuss the results without any variance regularization (blue curves). Without any finite measurement errors, the fit error of the noiseless optimization is the lowest of all optimization strategies. However, switching to the shot-based simulator yields a considerably different picture. The fit error reaches a considerably higher plateau compared to the state-vector simulation, primarily due to the finite sampling noise, and the final value is the highest compared to all other methods. Nonetheless, the variance slightly decreases as the optimization progresses. We conclude that the ADAM optimization indirectly addresses the variance in an attempt to further minimize the fitting error. However, this process occurs at a slow and inefficient pace. Adding the variance regularization with a constant parameter \(\alpha\) (green curves) strongly reduced the variance of the QNN, and the final variance is significantly lower. The fit error in the noise-free simulation is higher compared to the case without variance regularization, as the optimization is not solely focused on minimizing the fit error. However, this effect reverses when transitioning to the shot-based simulation, in which the reduced variance also improves the convergence to a lower fit error. Moving on to the iteration-based variance parameter, we observe a similar trend in the fit error. However, the variance is significantly decreased compared to the constant parameter \(\alpha\). The variance plot clearly demonstrates that this strategy primarily targets the variance reduction first, while prolonging the optimization of the fit. On the other hand, the lower variance results in fewer shots required for the time-consuming gradient evaluation, leading to a faster overall computation time until reaching the plateau after 300 iterations. The final variance is reduced from 52.09 (without variance regularization) to 4.16. In other words, the final QNN obtained with variance regularization requires over ten times fewer shots to achieve a similar level of finite sampling noise. Figure 5 presents the final results of regression on three different functions: the logarithm, the absolute value function, and an oscillating function. The figures also display the averaged values of the final fit error and variance over the last 10 optimization iterations. The optimization process follows the methodology described above. For the absolute value function, the fitting error of the individual training data Figure 4: Graphs representing the ADAM optimization of a QNN using the shot-based QASM simulator. The upper panel showcases the variance loss (excluding the prefactor \(\alpha\)), while the middle panel displays the fitting loss throughout the optimization process. The bottom panel illustrates the number of shots utilized in the gradient evaluation. All results are averaged values from 10 runs, and the individual results are depicted as thin lines. Results from the noise-free statevector simulator (SV) are represented by dashed lines. points is weighted, with higher weights assigned to the points in the center. These weights are determined by the function \(w(x)=2\exp(-x^{2})\). In all three examples, there is a noticeable reduction in both finite sampling noise and fit error. Particularly, the example of the absolute value function demonstrates a remarkable reduction in variance, exceeding a factor of 20. The reduction in fit error is evident in the plot for the oscillating function. The operator utilized in these examples (cf. Eq. (13)) has the capability to generate results without the same level of significant noise observed in the introductory example. However, despite this inherent capability, the application of variance regularization greatly enhances the results for all three examples, without imposing a notable computational overhead. ## V Results from the real hardware In this section we investigate the impact of the variance regularization on the performance of QNNs on real quantum computing hardware. All following computations are executed within the IBM Quantum ecosystem.[50] Training a QNN on real quantum computing platforms remains a challenging and time-consuming task today. In this section, we demonstrate that the reduced variance and the optimization procedure discussed in Section IV enable the optimization process on a real quantum computing backend, providing a notable performance boost due to the reduced number of shots. We train the QNN using the procedure described in Section IV, wherein the last two-qubit gate \(\hat{R}_{zz}\) of each layer is removed to achieve hardware-efficient linear entangling without introducing swapping gates. To reduce computational time, we decrease the number of training points for fitting the data compared to the previous examples. The training data used in this example is shown in Figure 7. Additionally, no error mitigation techniques are employed to expedite the process. The qubit assignment remains fixed throughout the entire optimization process, as well as during inference. However, evaluating the circuits resulting from the parameter-shift evaluation still consumes a significant amount of time. It takes approximately 27 minutes to evaluate the 2618 circuits needed in this example for the parameter-shift derivative on the real backend, even with the lowest setting of 100 shots. However, due to various reasons, such as pre- and post-processing of circuits and especially queuing, the training process for the QNN extends over a duration of several weeks. Frequent recalibration of the quantum hardware could potentially impact the optimization process, however, in our optimization this effect seems negligible. Figure 6 showcases the optimization performed on the IBM backend ibmq_montreal for the absolute value function. Additionally, we present the optimization with the exact same settings on the shot-based simulator. Notably, both optimizations exhibit very similar behavior, indicating the potential for further reduction in the fitting loss on the real backend. We anticipate that at some point, the additional noise introduced by the hardware will limit the further optimization process, resulting in a higher final loss compared to the shot-based sim Figure 5: Regression of various functions without (blue) and with (orange) variance regularization. The black lines show the reference function; the data points marked with an x are used for training the QNN. The training and the final inference are obtained from a shot-based QASM simulation using 5000 shots. The inference for the logarithm function is performed on a test set with an equidistant spacing of 0.002 while the spacing for the other functions is 0.004. ulation. Due to the variance regularization, which greatly reduces the output variance of the QNN, we can perform the gradient evaluation with a relatively low number of shots. This factor enables us to carry out the optimization of this example on the real backend in the first place. The full optimization curve of the shot-based QASM simulation is displayed in the Appendix in Section VII.2. Figure 7 displays the inference of the trained QNNs. The blue curve is evaluated with the shot-based simulator and with parameters that are obtained from the converged QASM optimization displayed in Figure 6. The orange curve is obtained from the IBM backend ibmq_montreal with parameters that result from the optimization on the same backend. At this stage of the optimziation, the output agrees well with the results from the shot-based simulator. We would like to emphasize that the optimization and inference on the real quantum computer were conducted without any error mitigation techniques. Despite this, the QNN demonstrated a remarkable capability to adapt to hardware imperfections during real hardware training, as evidenced by its good agreement with the simulation results. However, when evaluating the QNN on real backends using parameters obtained from the QASM optimization, we observed substantial deviations from the simulated outputs. These findings strongly indicate that QNNs intended for evaluation on a quantum computer should be trained on the same machine. Such an approach takes into account the specific hardware characteristics and imperfections, resulting in better performance and improved adaptability to the target quantum system. In our view, this emphasizes the necessity for techniques that enable training directly on the hardware, instead of solely concentrating on simulations. The final example is motivated by Reference [39], in which it is shown that the variance is increased by error mitigation. Furthermore, it is discussed that error mitigation protocols can worsen the trainability of QNNs because of the increased variance. To investigate how the variance regularization is influence by the error mitigation, we compute results on the real Figure 8: Histogram of the expectation value evaluated 300 times on the IBM backend ibmq_montreal. The darker colors are obtained with zero-noise extrapolation (ZNE). Gaussian distributions are fitted to the obtained expectation values, the resulting mean (\(\mu\)) and the standard deviation (\(\sigma\)) are displayed in the same color. The dashed lines show the reference values obtained from the same QNNs evaluated on a noise-free statevector (SV) simulator. Figure 6: Results from the optimization on the IBM backend ibmq_montreal and the corresponding shot-based QASM simulation, both utilizing 10 qubits. The optimization procedure is described in Section IV. Figure 7: The output of the QNNs from both shot-based simulators (QASM) and real backends is presented. The blue curve represents the result obtained from the converged QASM optimization. The orange curve depicts the output after 95 training steps on the ibmq_montreal backend. It is worth noting that the results from the real quantum computing (QC) backend are obtained without the utilization of error mitigation techniques. backend utilizing the zero-noise extrapolation protocol [51; 52] as error mitigation. Zero-noise extrapolation involves deliberately amplifying the noise in the output by replicating gate operators in the circuit without altering its functionality. This procedure allows the creation of a simple model based on the expectation value with controlled noise amplification, enabling extrapolation to the expectation value in the absence of any noise. The QNNs in this example are obtained by an optimization with the shot-based simulator, both with and without variance regularization. The training follows the protocol described above and in Section IV and fits the absolute value function. The expectation values of the different QNNs are evaluated 300 times at \(x=-0.5\) on the ibmq_montreal backend utilizing 5000 shots in each run. Figure 8 displays the histogram of the expectation values, both with and without zero-noise extrapolation. Gaussian distributions are fitted to the 300 expectation values to illustrate the width of the distribution, and the mean (\(\mu\)) and the standard deviation (\(\sigma\)) of these Gaussians are provided. It is evident that the variance of the expectation value is significantly improved by the variance regularization, regardless of the presence of zero-noise extrapolation. Furthermore, the center of the expectation value is shifted to the noise-free reference value of the QNN by the application of zero-noise extrapolation. The increased variance through the mitigation is visible for both QNNs, although it is not particularly significant in our example. Nonetheless, the variance reduction achieved through regularization remains strong even in the presence of zero-noise extrapolation. ## VI Conclusion In this work, we investigated the impact of finite sampling noise, an inevitable aspect of quantum computing, on QNNs. To mitigate this noise, we introduced a technique called variance regularization, which exploits the expressivity of QNNs to reduce the variance of the output. The method additionally includes the variance in the loss function that is minimized in the training. When the cost operator of the QNN is chosen to be diagonal in the computational basis (e.g. only using Pauli I and Z operators), the variance and its derivative can be computed from the same circuit evaluations as the function values and gradients. We presented an example illustrating that noise-free QNNs obtained from simulators can exhibit a good fit but may suffer from a high variance, requiring either a huge number of shots or introducing significant amount of finite sampling noise. We believe that this aspect is often underestimated in current research on QNNs. Our findings demonstrate that the variance regularization significantly reduces the finite sampling noise. Compared to results without regularization, the final QNN requires on average a magnitude fewer shots to achieve a similar level of noise. We introduced an optimization procedure in which the contribution of the variance loss is adjusted during the optimization, resulting in substantial variance reduction and improved regression of the QNNs. Empirically, we showed that the number of shots required during the gradient evaluation can be adjusted based on the variance of the fitting loss, leading to faster computation times. In the final part of our study, we examined the impact of variance regularization on IBM's real quantum computing backends. We demonstrated QNN optimization on a real backend, showcasing the adaptability of the QNN to hardware-specific characteristics during training. The results show similar improvements in the variance reduction compared to the simulation examples. Additionally, we observed that zero-noise extrapolation has no strong influence on the reduced variance of the output. We believe that variance regularization is a necessary step to make QNNs more practical for real-world applications, although the time-consuming training on real hardware remains a big challenge. Exploring the application of variance regularization in other variational quantum algorithms may also be worth investigating when reducing finite sampling noise is crucial. ###### Acknowledgements. This work was supported by the German Federal Ministry of Education and Research through the project H2Giga-DegradEL3 (grant no. 03HY110D). We further acknowledge the use of IBM Quantum services for this work. The views expressed are those of the authors, and do not reflect the official policy or position of IBM or the IBM Quantum team. ## VII Supplementary materials ### Chebyshev with non-integer parameters The first-kind Chebyshev polynomials \(T_{\varphi}(x)\) can be obtained from the following one qubit QNN: \[|\Psi(x,\varphi)\rangle=\hat{R}_{x}(\varphi\cos^{-1}(x))\qquad\text{and}\qquad \hat{C}=\hat{Z} \tag{17}\] The cost operator is the Pauli Z operator. Figure 9 shows the resulting curves for (non-integer) values of \(\varphi\in[2,3]\). The Figure 9: The first-kind Chebyshev polynomials \(T_{\varphi}(x)\) with non-integer parameter. original Chebyshev polynomials \(T_{2}(x)\) and \(T_{3}(x)\) are reproduced for \(\varphi=2,3\). ### Comparison between real quantum computing hardware and the fully converged simulated optimization Figure 10 shows the comparison of the optimization on the real quantum computing (QC) backend ibmq_montreal and the fully converged optimization carried out with the shot-based simulator. The optimization on the real backend was terminated at 95 iterations after running for several weeks. Although we were not able to run the optimization until convergence, the result shown in Fig 10 (and Fig 6, respectively) is the longest cohesive optimization instance that we were able to run on real hardware, given the current practical limitations discussed in the main text.
2304.06049
Exact and Cost-Effective Automated Transformation of Neural Network Controllers to Decision Tree Controllers
Over the past decade, neural network (NN)-based controllers have demonstrated remarkable efficacy in a variety of decision-making tasks. However, their black-box nature and the risk of unexpected behaviors and surprising results pose a challenge to their deployment in real-world systems with strong guarantees of correctness and safety. We address these limitations by investigating the transformation of NN-based controllers into equivalent soft decision tree (SDT)-based controllers and its impact on verifiability. Differently from previous approaches, we focus on discrete-output NN controllers including rectified linear unit (ReLU) activation functions as well as argmax operations. We then devise an exact but cost-effective transformation algorithm, in that it can automatically prune redundant branches. We evaluate our approach using two benchmarks from the OpenAI Gym environment. Our results indicate that the SDT transformation can benefit formal verification, showing runtime improvements of up to 21x and 2x for MountainCar-v0 and CartPole-v0, respectively.
Kevin Chang, Nathan Dahlin, Rahul Jain, Pierluigi Nuzzo
2023-04-11T19:52:30Z
http://arxiv.org/abs/2304.06049v2
Exact and Cost-Effective Automated Transformation of Neural Network Controllers to Decision Tree Controllers ###### Abstract Over the past decade, neural network (NN)-based controllers have demonstrated remarkable efficacy in a variety of decision-making tasks. However, their black-box nature and the risk of unexpected behaviors and surprising results pose a challenge to their deployment in real-world systems with strong guarantees of correctness and safety. We address these limitations by investigating the transformation of NN-based controllers into equivalent soft decision tree (SDT)-based controllers and its impact on verifiability. Differently from previous approaches, we focus on discrete-output NN controllers including rectified linear unit (ReLU) activation functions as well as argmax operations. We then devise an exact but cost-effective transformation algorithm, in that it can automatically prune redundant branches. We evaluate our approach using two benchmarks from the OpenAI Gym environment. Our results indicate that the SDT transformation can benefit formal verification, showing runtime improvements of up to \(21\times\) and \(2\times\) for MountainCar-v0 and CartPole-v0, respectively. ## I Introduction Over the last decade, neural network (NN)-based techniques [1] have exhibited outstanding efficacy in a variety of decision-making tasks, surpassing human-level performance in some of the most challenging control problems. They even lead the leaderboard in almost all benchmark problems in control and robotics. However, their deployment in safety-critical applications, such as autonomous driving and flight control, raises concerns [2, 3] due to the black-box nature of NNs and the risk of unexpected behaviors. To overcome the limitations of NN-based controllers, researchers have proposed distillation [4], which transfers the learned knowledge and behaviors of NN controllers to alternative models, such as decision trees, which are easier to interpret. In fact, the efficacy of NN controllers versus other models is not necessarily due to their richer representative capacity, but rather to the many regularization techniques available to facilitate training [5, 6]. By compressing NN controllers into simpler and more compact models, distillation can also facilitate formal verification. However, the distilled models typically fall short of the real-time performance of their full counterparts. In fact, identification of effective metrics to characterize the approximation quality of a distilled model versus the original NN is itself an open problem. In this paper, we focus instead on the _exact, systematic transformation_ of NN-based controllers into equivalent soft decision tree (SDT)-based controllers and the empirical evaluation of the impact of this transformation on the verifiability of the controllers. The equivalent SDT models can be used for verification, while the NN models are used at runtime. Moreover, unlike prior work, we consider discrete-output NN controllers with rectified linear unit (ReLU) activation functions and argmax operations. These discrete-action NNs are particularly challenging from a verification standpoint, in that they tend to amplify the approximation errors generated by reachability analysis of the closed-loop control system. Our contributions can be stated as follows: * We first prove that any discrete-output argmax-based NN controller has an _equivalent_ SDT. This is done by presenting a constructive procedure to transform any NN controller into an equivalent SDT controller that has the same properties. * We show that our constructive procedure for creating an equivalent SDT controller can also be computationally practical, in that the number of nodes in the SDT scales polynomially with the maximum width of the hidden layers in the NN. To the best of our knowledge, this is the first such computationally practical transformation algorithm. * We empirically validate the computational efficiency of formally verifying the SDT controller over the original NN controller on two benchmark OpenAI Gym environments [7], showing that verifying the SDT controller is 21 times as fast on the MountainCar-v0 environment and twice as fast on the CartPole-v0 environment. Our results suggest that SDT transformation can be used to accelerate the verification of NN controllers in feedback control loops, with potential impact on applications where performance guarantees are critical but deep learning methods are the primary choice for control design. Related Work. Distillation [4] has been used to transfer the knowledge and behavior of NN-based controllers to other models in an approximate, e.g., data-driven, or exact manner. _Approximate distillation_ can be performed by training shallow NNs to mimic the behavior of state-of-the-art NNs using a teacher-student paradigm [5]. Distilling SDTs from expert NNs was shown to lead to better performance than directly training SDTs [4]. Furthermore, distillation has demonstrated success in reinforcement learning (RL) problems, where the DAGGER algorithm is used to transfer knowledge from Q-value NN models via simulation episodes [8]. Finally, distilling to SDTs has also been suggested to interpret the internal workings of black-box NNs [9]. In contrast, _exact distillation_ has been proposed to transform feedforward NNs into simpler models while preserving equivalence [10, 11, 12]. Locally constant networks [10] and linear networks [11] have been introduced as intermediate representations to establish the equivalence between NNs and SDTs whose worst-case size scales exponentially in the maximum width of the NN hidden layers. Nguyen et al. [12] proposed transforming NNs with ReLUs into decision trees and then compressing the trees via a learning-based approach. As in previous approaches, our algorithm preserves equivalence with the SDTs. However, it also guarantees, without the need for compression, that the size of the tree scales polynomially in the width of the maximum hidden layer of the NN. Finally, we also provide quantitative evidence about the impact of the proposed transformations on the verifiability of the controllers. ## II Preliminaries We review key definitions for both neural networks (NN) and soft decision trees (SDT), using Fig. 1 as an illustrative example. Throughout the paper, we use \(A_{i,j}\) to denote the element in the \(i\)-th row and \(j\)-th column of matrix \(A\), and \(a_{i}\) or \((a)_{i}\) to denote the \(i\)-th element of vector \(a\). #### Ii-1 Neural Networks Let \(L\) denote the total number of layers in a NN, \(N^{l}\) denote the _width_, or number of neurons in the \(l\)-th layer, and define \(N:=(N_{1},\ldots,N_{L})\). In Fig. (a)a, we have \(L=3\), with a two-neuron input layer (\(N^{1}=2\)), a single-neuron hidden layer (\(N^{2}=1\)), and a three-neuron output layer (\(N^{3}=3\)), so that \(N=(2,1,3)\). The nodes in layer \(l\), with \(l>1\), are fully connected to the previous layer. Edges and nodes are associated with weights and biases, denoted by \(W^{l}\) and \(B^{l}\), respectively, for \(l\geq 2\). The output at each neuron is determined by its inputs using a _feedforward function_, defined below, and then passed through a rectified linear unit (ReLU) _activation function_. **Definition 1**: _(NN Layer Feedforward Function). Given input \(x\in\mathbb{R}^{N^{l-1}}\), the feedforward function \(f_{F}^{l}:\mathbb{R}^{N^{l-1}}\rightarrow\mathbb{R}^{N^{l}}\) maps \(x\) to the output of layer \(l\geq 2\), where the output of the \(i\)-th neuron in layer \(l\) is defined as_ \[(f_{F}^{l}(x))_{i}:=\sum_{i=1}^{N^{l-1}}W_{i,j}^{l}x_{j}+B_{i}^{l}.\] We also recall the definition of _characteristic function_. Let \(\alpha\) be the element-wise ReLU activation function, i.e., \(\alpha(x)_{i}=\max\{x_{i},0\}\). **Definition 2**: _(NN Layer-Characteristic Function). The characteristic function for layer \(l\) of NN \(\mathcal{N}\), \(f_{\mathcal{N}}^{l}:\mathbb{R}^{N^{1}}\rightarrow\mathbb{R}^{N^{l}}\), is defined as_ \[f_{\mathcal{N}}^{l}(x):=f_{F}^{l}\circ\alpha\circ f_{F}^{l-1}\circ\cdots\circ f _{F}^{3}\circ\alpha\circ f_{F}^{2}(x).\] **Definition 3**: _(NN Characteristic Function). The characteristic function of NN \(\mathcal{N}\), \(f_{\mathcal{N}}:\mathbb{R}^{N^{1}}\rightarrow\mathbb{N}\), is defined as_ \[f_{\mathcal{N}}(x):=\operatorname*{arg\,max}_{i\in\{1,\ldots,N^{L}\}}\{(f_{ \mathcal{N}}^{L})_{i}:i\in\{1,\ldots,N^{L}\}\}. \tag{1}\] In Definition 3, we assume that when \(\operatorname*{arg\,max}(.)\) is not a singleton, a deterministic tie-breaking procedure is used to select a single index. #### Ii-2 Soft Decision Trees We consider a binary SDT [9]. Let \(\mathcal{I}_{\mathcal{S}}\) and \(\mathcal{L}_{\mathcal{S}}\) denote the sets of inner and leaf nodes for an SDT \(\mathcal{S}\) with input dimension \(n\). Each inner node \(v\in\mathcal{I}\) is associated with weights \(w^{v}\in\mathbb{R}^{n}\) and a bias term \(b^{v}\in\mathbb{R}\). At node \(v\), \(w^{v}\) and \(b^{v}\) are applied to input \(x\). The resulting value is passed through an activation function \(\sigma\), producing a scalar, \(p_{v}(x)=\sigma(x^{\top}w^{v}+b^{v})\), which is compared to a threshold to determine whether to proceed to the left or right branch. In this paper, we consider SDTs using the sigmoid logistic activation function \(\sigma(y)=\frac{1}{1+e^{-y}}\) at all nodes. Each leaf node \(v\in\mathcal{L}\) is associated with a vector \(Q^{v}\). In general, \(Q^{v}\) is a distribution over possible output selections. In our SDTs, the elements of \(Q^{v}\) will take values in \(\{0,1\}\). Rather than learning the parameters \((w^{v},b^{v})\) or \(Q^{v}\) for each node \(v\) from data as in the literature [9], we derive these parameters via transformation of a reference NN. We denote the left and right child of an inner node \(v\) as \(l(v)\) and \(r(v)\), respectively, and the parent of \(v\) as \(\rho(v)\). The root node of the SDT is \(v_{0}\). We now define the SDT characteristic functions. **Definition 4**: _(SDT Node Characteristic Function). Let \(\mathcal{S}\) be an SDT with input dimension \(n\). Given input vectors \(x\in\mathbb{R}^{n}\), the characteristic function of node \(v\), \(f_{\mathcal{S}}^{v}:\mathbb{R}^{n}\rightarrow\mathbb{N}\), is defined recursively as_ \[f_{\mathcal{S}}^{v}(x)=\left\{\begin{array}{cl}\operatorname*{arg\,max}_{k }\{Q_{k}^{v}\},&\text{if }v\in\mathcal{L}_{\mathcal{S}},\\ f_{\mathcal{S}}^{l(v)}(x),&\text{if }v\in\mathcal{I}_{\mathcal{S}}\wedge p_{v}(x) \leq 0.5,\\ f_{\mathcal{S}}^{r(v)}(x),&\text{if }v\in\mathcal{I}_{\mathcal{S}}\wedge p_{v}(x) >0.5.\end{array}\right.\] **Definition 5**: _(SDT Characteristic Function). The characteristic function of SDT \(\mathcal{S}\) with input dimension \(n\), \(f_{\mathcal{S}}:\mathbb{R}^{n}\rightarrow\mathbb{N}\), is defined as \(f_{\mathcal{S}}(x):=f_{\mathcal{S}}^{v_{0}}(x)\)._ Throughout this work, we assume that NNs and SDTs use the same deterministic argmax-based tie-breaking procedure. We further introduce the notation \(\mathcal{D}(v)\) to represent the effective _domain_ of an SDT node \(v\), i.e., the set of all possible inputs arriving at \(v\). The set \(\mathcal{D}(v)\) is computed recursively in a top-down manner from the root node as follows \[\mathcal{D}(v)=\left\{\begin{array}{ll}\mathbb{R}^{n},&\text{if }v=v_{0},\\ \mathcal{D}(\rho(v))\cap&\text{if }v\neq v_{0}\wedge\\ \{x|p_{\rho(v)}(x)\leq 0.5\},&\text{ }l(\rho(v))=v,\\ \mathcal{D}(\rho(v))\cap&\text{if }v\neq v_{0}\wedge\\ \{x|p_{\rho(v)}(x)>0.5\},&\text{ }r(\rho(v))=v,\end{array}\right. \tag{2}\] where \(n\) is the input dimension of the SDT. For example, for the SDT in Fig. (b)b, the inputs \(x=(x_{0},x_{1})^{\top}\in\mathbb{R}^{2}\) are processed starting from the root node Fig. 1: Example NN to SDT Transformation. \(v_{0}\), where \(\mathcal{D}(v_{0})=\mathbb{R}^{2}\). The input range related to node \(v_{1}\) is \(\mathcal{D}(v_{1})=\{x\in\mathbb{R}^{2}|x_{1}\leq 0\}\) and \(v_{1}\) is reached only if \(x_{1}\leq 0\). Similarly, node \(v_{2}\) is reached when \(x_{1}\geq 0\), i.e., \(\mathcal{D}(v_{2})=\{x\in\mathbb{R}^{2}|x_{1}\geq 0\}\). In the remainder of the paper, we omit the reference to the underlying state-space in the expressions for the node input domains, when it is clear from the context, and simply write, e.g., \(\mathcal{D}(v_{1})=\{x_{1}\leq 0\}\) and \(\mathcal{D}(v_{2})=\{x_{1}>0\}\). ## III Transformation from Neural Network to Decision Tree We present an algorithm for constructing an SDT \(\mathcal{S}_{\mathcal{N}}\) which is equivalent to a reference NN \(\mathcal{N}\) in the sense that \(f_{\mathcal{N}}(x)=f_{\mathcal{S}_{\mathcal{N}}}(x)\) for all inputs \(x\in\mathbb{R}^{n}\). We outline the relation between fully connected NNs with ReLU activation and argmax output and SDTs based on our transformation in Fig. 1. In the NN of Fig. (a)a, the output of the single neuron in layer 2 following the ReLU activation is \[\alpha(f_{\mathcal{N}}^{2}(x))=\alpha\left(W^{2}x+B^{2}\right)=\alpha(x_{1})= \begin{cases}0,&\text{if }x_{1}\leq 0,\\ x_{1},&\text{if }x_{1}>0.\end{cases} \tag{3}\] Carrying these two cases forward through the output layer \(L=3\), we have \[f_{\mathcal{N}}^{L}(x)=\begin{cases}B^{L}&=(0.001,\,0,\,0)^{\top},\quad\text{ if }x_{1}\leq 0,\\ W^{L}x_{1}+B^{L}&=(0.001,\,0,\,x_{1})^{\top},\quad\text{if }x_{1}>0.\end{cases} \tag{4}\] Thus, when \(x_{1}\leq 0\), we have \[f_{\mathcal{N}}(x)=\operatorname*{arg\,max}_{i\in\{1,\ldots,N^{L}\}}\{(f_{ \mathcal{N}}^{L}(x))_{i}\}=1,\] while when \(x_{1}>0\), we have \[f_{\mathcal{N}}(x)=\begin{cases}1,&\text{if }x_{1}\leq 0.001,\\ 3,&\text{if }x_{1}>0.001,\end{cases} \tag{5}\] assuming we take the lowest index to break ties. Turning to the SDT in Fig. (b)b, we observe that (3) partitions the input space into two subsets based on the inner node's ReLU activation. This is precisely the split that occurs at the root node \(v_{0}\) of the SDT toward nodes \(v_{1}\) and \(v_{2}\). Then, (5) further splits one of these subsets based on the output layer values. This split occurs at \(v_{2}\) to provide nodes \(v_{3}\) and \(v_{4}\). Finally, we have three regions where \(f_{\mathcal{N}}(x)\) is constant, corresponding to leaf nodes \(v_{1}\), \(v_{3}\), and \(v_{4}\) in Fig. (b)b. As shown in (3)-(5) for subsets of the NN input space, based on the sequence of ReLU activations, \(f_{\mathcal{N}}^{L}(x)\) is an affine function. Such subsets may be further partitioned based on the argmax operation. Therefore, the operation of fully connected NNs with ReLU activations and argmax output can be understood in terms of successive assignment of inputs to increasingly refined partitions of the state space, which can be shown to consist of convex polyhedra [10]. Identification of SDT splits and leaf node assignments based upon NN neuron activations and output layer outputs forms the core of our transformation technique, which we explain further in the remainder of this section. See Appendix A for an application of the transformation to the example in Fig. 1. ### _Pre and Post-Activation Formulas_ We establish the relationship between \(\mathcal{N}\) and \(\mathcal{S}_{\mathcal{N}}\) by first introducing, for each node \(v\), a _pre-activation function_\(\mathcal{F}_{i}^{l}\llbracket v\rrbracket:\,\mathcal{D}(v)\to\mathbb{R}\) and a _post-activation function_\(\overline{\mathcal{F}_{i}^{l}\llbracket v\rrbracket}:\mathcal{D}(v)\to \mathbb{R}\). The pre-activation function provides the output of the \(i\)-th neuron in the \(l\)-th layer of \(\mathcal{N}\) as a function of the input in \(\mathcal{D}(v)\) prior to the ReLU. The _post-activation function_ gives the neuron output after the ReLU. The pre-activation functions for node \(v\) are defined for \(l=2,\ldots,L\) and \(i=1,\ldots,N^{l}\) as \[\mathcal{F}_{i}^{l}\llbracket v\rrbracket(x)=\\ \begin{cases}\sum_{j=1}^{N^{l}_{1}}W_{i,j}^{l}x_{j}+B_{i}^{l},&\text{if }l=2,\\ \sum_{j=1}^{N^{l-1}_{1}}W_{i,j}^{l}\overline{\mathcal{F}_{j}^{l-1}\llbracket v \rrbracket}(x)+B_{i}^{l},&\text{if }l>2\wedge\overline{\mathcal{F}_{j}^{l-1} \llbracket v\rrbracket}(x)\neq\bot\\ &\text{for }j=1,2,\ldots,N^{l-1},\\ \bot,&\text{otherwise}.\end{cases} \tag{6}\] Here, \(\bot\) denotes an undefined value. The post-activation functions for node \(v\) are defined for \(l=2,\ldots,L-1\) and \(i=1,\ldots,N^{l}\) as \[\overline{\mathcal{F}_{i}^{l}\llbracket v\rrbracket}(x)=\begin{cases}\mathcal{F} _{i}^{l}\llbracket v\rrbracket(x),&\text{if }\mathcal{F}_{i}^{l}\llbracket v\rrbracket\neq\bot\wedge\\ &\mathcal{D}(v)\cap\{\mathcal{F}_{i}^{l}\llbracket v\rrbracket(x)\leq 0\}=\emptyset,\\ 0,&\text{if }\mathcal{F}_{i}^{l}\llbracket v\rrbracket\neq\bot\wedge\\ &\mathcal{D}(v)\cap\{\mathcal{F}_{i}^{l}\llbracket v\rrbracket(x)>0\}=\emptyset,\\ \bot,&\text{otherwise}.\end{cases} \tag{7}\] We define \(\mathcal{F}^{l}\llbracket v\rrbracket:=(\mathcal{F}_{1}^{l}\llbracket v \rrbracket,\ldots,\mathcal{F}_{N^{l}}^{l}\llbracket v\rrbracket)^{\top}\) and \(\overline{\mathcal{F}^{l}\llbracket v\rrbracket}\) similarly for all \(l=2,\ldots,L\). The pre-activation formulas play a crucial role in determining the pre-threshold branching functions \(p_{v}\) at each inner node \(v\) of \(\mathcal{S}\). ### _SDT Split and Leaf Formation Rules_ We construct the branches of \(\mathcal{S}_{\mathcal{N}}\) based on the rules in Table I. By starting with the root node \(v_{0}\), for each node \begin{table} \begin{tabular}{c|c|c} **Rules** & **Conditions** & **Computation of \(p_{v}(x)\) or \(Q^{v}\)** \\ \hline 1. Split based on ReLU & \(\exists\;i,l<L\) s.t. \(\mathcal{D}(v)\cap\{\mathcal{F}_{i}^{l}\llbracket v\rrbracket(x)\leq 0\}\neq\emptyset\wedge\) & \(p_{v}(x)=\left\{\begin{array}{ll}\sigma(\mathcal{F}_{i}^{l}\llbracket v \rrbracket(x))\\ \text{for }\min\;i,l\text{ such that Rule 1 conditions hold }\\ \end{array}\right.\) \\ \hline 2. Split based on output layer & \(\begin{array}{l}\mathcal{D}(v)\cap\bigcap_{v^{\prime}\neq i_{1}}\{F_{i_{1}}^{L} \llbracket v\rrbracket(x)\geq\mathcal{F}_{i_{1}}^{L}\llbracket v\rrbracket(x)\} \neq\emptyset\wedge\\ \mathcal{D}(v)\cap\bigcap_{v^{\prime}\neq i_{2}}\{F_{i_{2}}^{L}\llbracket v \rrbracket(x)\geq\mathcal{F}_{i_{1}^{L}}^{L}\llbracket v\rrbracket(x)\} \neq\emptyset\end{array}\) & \(p_{v}(x)=\sigma(\mathcal{F}_{i_{1}}^{L}\llbracket v\rrbracket(x)-\mathcal{F}_{i_{2} }^{L}\llbracket v\rrbracket(x))\) \\ \hline 3. Form leaf node & Neither Rule 1 nor Rule 2 satisfied & \(Q_{i}^{v}=\left\{\begin{array}{ll}1&\text{if }i=\operatorname*{arg\,max}_{k}\{\mathcal{F}_{k}^{L} \llbracket v\rrbracket(x)\}\;\forall x\in\mathcal{D}(v)\\ 0&\text{otherwise}\end{array}\right.\) \\ \end{tabular} \end{table} TABLE I: Rules for constructing an SDT node \(v\). in \(\mathcal{S}_{\mathcal{N}}\), we use Table I to obtain \(p_{v}(x)\) or \(Q^{v}\) in a top-down fashion from the root to leaves, as further explained below. **Rule 1.** If there exists a neuron \(i\) in layer \(l\) of \(\mathcal{N}\) such that \(D_{0}:=\mathcal{D}(v)\cap\{\alpha(\mathcal{F}_{i}^{l}[\![v]\!](x))=0\}\neq\emptyset\) and \(D_{1}:=\mathcal{D}(v)\cap\{\alpha(\mathcal{F}_{i}^{l}[\![v]\!](x))>0\}\neq\emptyset\) hold, we form a split at node \(v\) in \(\mathcal{S}_{\mathcal{N}}\). \(\mathcal{D}(v)\) is then partitioned along the hyperplane \(\mathcal{F}_{i}^{l}[\![v]\!](x)=0\), with \(\mathcal{D}(l(v))=D_{0}\) and \(\mathcal{D}(r(v))=D_{1}\). For example, for node \(v_{0}\) in Fig. 0(b), we create a split at \(v_{0}\) with \(p_{v_{0}}(x)=\sigma(\mathcal{F}_{1}^{l}[\![v_{0}]\!](x))\). **Rule 2.** Suppose no partitions can be found for \(\mathcal{D}(v)\) based on the ReLUs according to Rule 1. Then, \(\mathcal{D}(v)\) may be further partitioned based on the output layer values. If there exist \(i_{1}\) and \(i_{2}\) and sets \(D_{i_{1}}:=\{x\in\mathcal{D}(v)\big{|}\arg\max_{i}\{\big{(}\mathcal{F}^{L}[\! [v]\!](x)\big{)}_{i}=i_{1}\}\neq\emptyset\) and \(D_{i_{2}}:=\{x\in\mathcal{D}(v)\big{|}\arg\max_{i}\{\big{(}\mathcal{F}^{L}[\! [v]\!](x)\big{)}_{i}\}=i_{2}\}\neq\emptyset\), we form a split at node \(v\). \(\mathcal{D}(v)\) is then partitioned along the hyperplane \(\mathcal{F}_{i_{2}}^{L}[\![v]\!](x)-\mathcal{F}_{i_{1}}^{L}[\![v]\!](x)=0\), giving \(D_{i_{1}}\subseteq\mathcal{D}(l(v))\) and \(D_{i_{2}}\subseteq\mathcal{D}(r(v))\). For example, for node \(v_{2}\) in Fig. 0(b), we create a split at \(v_{2}\) and set \(p_{v_{2}}(x)\) as \(\sigma(\mathcal{F}_{1}^{l}[\![v_{2}]\!](x)-\mathcal{F}_{3}^{l}[\![v_{2}]\!](x))\). **Rule 3.** If neither Rule 1 nor Rule 2 can be applied to further partition \(\mathcal{D}(v)\), then the index of the neuron with the maximum output at layer \(L\), i.e., the outcome of the \(\arg\max\) operator remains constant over the entire set \(\mathcal{D}(v)\). We then declare \(v\) as a leaf node, setting \(Q_{i}^{v}=1\) for the neuron index corresponding to the largest output, and \(0\) otherwise. For example, for node \(v_{1}\) in Fig. 0(b) we set \(Q_{1}^{v_{1}}(x)=1\) and \(Q_{2}^{v_{1}}(x)=Q_{3}^{v_{1}}(x)=0\). The conditions above, such as non-emptiness of \(\mathcal{D}(v)\cap\{\alpha(\mathcal{F}_{i}^{l}[\![v]\!](x))=0\}\) in Rule 1, can be formulated and efficiently solved in terms of feasibility problems for LPs. ### _Transformation Procedure_ We construct \(\mathcal{S}_{\mathcal{N}}\) by starting with the root node \(v_{0}\) and building the binary tree downwards. We first construct the left-hand branches until a leaf node is discovered, from which we backtrack the tree to define the unexplored right branches. A recursive method implementing this procedure is presented in Algorithm 1. The transformation procedure effectively identifies a partition of the input space according to the domains associated with the leaf nodes of the SDT. Within these sets, the neural network characteristic function \(f_{\mathcal{N}}\) is constant, and due to our choice of \(Q^{v}\) at each leaf node \(v\), we have that \(f_{\mathcal{N}}(x)=f_{\mathcal{S}_{\mathcal{N}}}(x)\) over \(\mathcal{D}(v)\). Taking a union over the SDT partitions, we establish the equivalence of \(\mathcal{N}\) and \(\mathcal{S}_{\mathcal{N}}\) in Theorem 1. As detailed in Appendix B, Theorem 1 can be proved by induction on layer \(l\) to show that \(\mathcal{F}^{L}[\![v]\!](x)=f_{\mathcal{N}}^{L}(x)\) for leaf nodes nodes \(v\in\mathcal{L}_{\mathcal{S}_{\mathcal{N}}}\). **Theorem 1**: _For a given NN \(\mathcal{N}\) and its SDT transformation \(\mathcal{S}_{\mathcal{N}}\) using Algorithm 1 with input space \(\mathbb{R}^{n}\), the corresponding characteristic functions are pointwise equal, i.e., \(f_{\mathcal{N}}(x)=f_{\mathcal{S}_{\mathcal{N}}}(x)\) for all \(x\in\mathbb{R}^{n}\)._ Differently from previous algorithms in the literature [10, 11, 12], our algorithm only generates essential branches during the creation of the SDT. Given the NN input and output layer sizes and the number of hidden layers, the SDT size scales polynomially in the maximum hidden layer width. The size complexity of \(\mathcal{S}_{\mathcal{N}}\) in terms of the number of nodes is stated in Theorem 2, whose proof is provided in Appendix C. **Theorem 2**: _Let \(\mathcal{N}\) be a NN and \(\mathcal{S}_{\mathcal{N}}\) the SDT resulting from the application of Algorithm 1 to \(\mathcal{N}\). Denote the number of nodes in \(\mathcal{S}_{\mathcal{N}}\) by \(|\mathcal{S}_{\mathcal{N}}|\). Then, we obtain_ \[|\mathcal{S}_{\mathcal{N}}|=O\left(\prod_{l=2}^{L-1}\frac{(N^{l})^{(N^{1})}}{(N ^{1})!}2^{N^{L}}\right)=O\left(\frac{2^{N^{L}}}{(N^{1}!)}\mathcal{I}^{N^{1}L }\right),\] _where \(\mathcal{I}:=\max_{l\in\{2,\dots,L-1\}}N^{l}\)._ ## IV Verification Formulation We describe the verification problems that we solve to evaluate the impact of the proposed transformation. We consider closed-loop controlled dynamical systems with state and action spaces \(\mathcal{X}\) and \(\mathcal{U}\), respectively, and dynamics \(h:\mathcal{X}\times\mathcal{U}\rightarrow\mathcal{X}\). Let \(\pi:\mathcal{X}\rightarrow\mathcal{U}\) denote a time-invariant Markovian policy (controller) mapping states to actions. Given a system dynamics \(h\), an initial set \(\mathcal{X}_{i}\), and goal set \(\mathcal{X}_{g}\), we wish to determine whether \(\mathcal{X}_{g}\) is reachable in finite horizon \(T\) for all initial states \(x_{0}\in\mathcal{X}_{i}\), under \(h\) and policy \(\pi\). If so, we say that the specification \((\mathcal{X}_{i},\mathcal{X}_{g},T)\) is verified for \(\pi\). In this context, we consider two verification approaches. **Problem 1**: _(One-Shot Verification)._ We "unroll" the system dynamics at time instant \(t\in\{0,\dots,T\}\) and encode the verification problem to a satisfiability modulo theory (SMT) problem [13] using the bounded model checking approach [14]. Verification of \((\mathcal{X}_{i},\mathcal{X}_{g},T)\) for a policy \(\pi\) is then equivalent to showing that the following formula is _not_ satisfiable: \[\phi_{1}(\pi):=(\mathcal{X}_{i})\wedge(\overline{\mathcal{X}_{g}})\bigwedge_{t=0} ^{T-1}(x_{t+1}=h(x_{t},u_{t}))\wedge(u_{t}=\pi(x_{t})). \tag{8}\] If \(\phi_{1}(\pi)\) is false, then \(\pi\) is guaranteed to drive the system from any \(x_{0}\in\mathcal{X}_{i}\) to \(\mathcal{X}_{g}\) within the finite horizon \(T\). We observe that (8) requires encoding \(T\) replicas of the NN (policy \(\pi\)) in the control loop, which can make the SMT problem intractable due to its computational complexity. Therefore, we also consider an alternative verification approach via reachability analysis. In particular, we adopt a _recursive reachability analysis_[15], where we use the \(s\)-step unrolled dynamics, with \(s\ll T\), to compute an over-approximation of the \(s\)-step reachable set in terms of a rectangle. **Problem 2**: _(Recursive Reachability Analysis (RRA)._ We fix a step parameter \(s\) and recursively compute reachable sets \(\mathcal{R}_{t}\), where \(t=ms\) for \(m\in\mathbb{N}\). Given a system dynamics \(h\), policy \(\pi\) and step parameter \(s\), we encode the reachable set at time \(t\) as the SMT formula \[\begin{split}\mathcal{R}_{t}(\pi)&=\bigg{\{}x \bigg{|}x=x_{t}\wedge(\mathcal{R}_{t-s})\wedge\\ &\qquad\bigwedge_{k=t-s}^{t-1}(x_{k+1}=h(x_{k},u_{k}))\wedge(u_{k }=\pi(x_{k}))\bigg{\}}.\end{split} \tag{9}\] By setting \(\mathcal{R}_{0}=\mathcal{X}_{i}\), we can verify the specification \((\mathcal{X}_{i},\mathcal{X}_{g},T)\) by checking satisfaction of the following SMT formula \[\phi_{\text{RRA}}(\pi):=(\mathcal{X}_{i})\wedge(\overline{\mathcal{X}_{g}}) \wedge\bigcup_{m=1}^{[T/s]}\mathcal{R}_{ms}(\pi). \tag{10}\] While RRA may yield overly conservative reachable sets due to error propagation, it is often more tractable than direct one-shot verification [15], since it decomposes the overall reachability problem into a set of smaller sub-problems, each having a finite horizon of \(s\) and encoding the NN policy only \(s\) times, with \(s\ll T\). ## V Case Studies ### _The Environments_ #### V-A1 MountainCar-v0 In the MountainCar control task [16], an underpowered car needs to reach the top of a hill starting from a valley within a fixed time horizon \(T\). The state vector \(x_{t}\in\mathbb{R}^{2}\) comprises the car's position \(x_{t,0}\) and horizontal velocity \(x_{t,1}\) at time step \(t\), while the input \(u_{t}\in\{-1,0,1\}\) represent the car's acceleration action, either left (L), idle (I), or right (R), respectively. The system dynamics are given in Appendix D. While the reference NNs are trained to reach the top of the hill \((x\geq\mathfrak{g})\) in the minimum number of steps, we seek to verify whether a given controller will reach the goal state within \(T\) steps, starting from any point in an initial interval. Our specification \((\mathcal{X}_{i},\mathcal{X}_{g},T)\) is given by \[\mathcal{X}_{i}=\{x_{0}\in[\text{i},\text{i}_{u}],x_{1}=0\},\ \mathcal{X}_{g}=\bigcup_{t=0}^{T}\{x_{t,0}\geq\mathfrak{g}\},\] where \(\text{i}_{l}\), \(\text{i}_{u}\), and \(\mathfrak{g}\) are parameters. #### V-A2 CartPole-v0 In the CartPole control task [17], a pole is attached to a cart moving along a frictionless track, to be balanced upright for as long as possible within a fixed horizon \(T\). The state vector \(x_{t}\in\mathbb{R}^{4}\) consists of the cart position \(x_{t,0}\), the cart velocity \(x_{t,1}\), the pole angle \(x_{t,2}=\theta_{t}\), and the pole angular velocity \(x_{t,3}\) at time step \(t\). The input \(u_{t}\in\{0,1\}\) denotes the acceleration of the cart to the left or right. The system dynamics are given in Appendix E. We seek to verify that the pole is balanced upright within tolerance \(\mathfrak{g}\) at the end of horizon \(T\), starting from a range of initial cart positions and pole angles. With \(\text{i}_{l}\), \(\mathfrak{g}\) as parameters, our specification \((\mathcal{X}_{i},\mathcal{X}_{g},T)\) is given by \[\begin{split}\mathcal{X}_{i}&=\{x_{0,0}\in[\text {i}_{l},0],x_{0,2}\in[\text{i}_{l},0],x_{0,1}=x_{0,3}=0\}\\ \mathcal{X}_{g}&=\{|x_{T,2}|\geq\mathfrak{g}\}. \end{split} \tag{11}\] ### _Evaluation Results_ We adopt the problem setups available in the open-source package OpenAI Gym [7] and the parameters in Table II. We start by training NN controllers for \(1e7\) steps and then apply our transformation to construct equivalent SDTs. Figure 2 illustrates the average score, transformation time, and number of leaves of the SDT for each NN controller. We also display the estimated number of leaves under a naive transformation method that generates a split at every node for every neuron in every layer, denoted by "w/o branch removal". This value signifies the percentage reduction in size achieved by our transformation. As shown in Fig. 2, the percentage of size reduction for the SDT increases with the number of NN layers. Furthermore, the size of the transformed SDT for the CartPole problem increases faster than for the MountainCar problem, which can be attributed to the difference in \(N^{1}=|x_{t}|\). Nevertheless, we were able to transform all NN controllers in less than \(60\) seconds. \begin{table} \begin{tabular}{|c|c|c|c|} \hline Environment & \(\text{i}_{l}\) & \(\text{i}_{u}\) & \(\mathfrak{g}\) \\ \hline MountainCar & \(-0.11\) & \(-0.1\) & \(0.5\) \\ \hline CartPole & \(-0.1\) & N/A & \(\pi/15\) \\ \hline \end{tabular} \end{table} TABLE II: Hyperparameters in OpenAI Gym. Fig. 4: Comparison of MountainCar NN and SDT controller one-shot verification runtimes. Fig. 3: MountainCar NN policies, L (), I (), R (). Fig. 2: Transformation time and size of the transformed SDT. An advantage of SDT controllers is that the policy can be inferred from the tree structure. Fig. 3 plots the policies and SDT leaf node partitions for example MountainCar controllers. Note that constant action state-space regions become more complex as the depth of the NN increases. All SMT problems in our experiments are solved using an in-house implementation of a satisfiability modulo convex programming (SMC) solver [18], which integrates the Z3 satisfiability (SAT) solver [19] with Gurobi [20]. For the one-shot verification approach, Fig. 4 shows a comparison of the verification times for \(\mathcal{N}\) with \(N=(2,1,3)\) and \(\mathcal{S}_{\mathcal{N}}\) with three leaf nodes in the MountainCar problem. The NN verification time increases significantly compared to the equivalent SDT. However, verification takes more than 60000 seconds for \(\mathcal{N}\) when \(T>38\) and for \(\mathcal{S}_{\mathcal{N}}\) when \(T>64\). For the CartPole problem, all controllers fail to solve the verification problem (8) within 60000 seconds for \(T>10\). To assess the efficiency of RRA for NN and SDT controllers, we measured runtimes both for individual reachability set determination as well as overall verification time. Figure 4(a) plots reachable sets, along with overall verification and reachable set generation runtimes for an example MountainCar controller with \(s\in\{1,2\}\) in (9). Figure 4(b) plots verification and reachable set generation runtimes for a collection of CartPole controllers with \(s=1\) in (9). As shown, RRA verification becomes more efficient using the equivalent SDT controllers, rather than the reference NNs. Figure 6 compares the average inference and overall RRA verification times for a collection of NN and equivalent SDT controllers. We set \(T=200\) for the MountainCar problem and \(T=25\) for the CartPole problem. While the inference time for the SDT increases with the number of layers in NN, our results show that the transformed SDT controller accelerates verification for the MountainCar problem by up to \(21\times\) and for the CartPole problem by up to \(2\times\). Moreover, the larger the number of layers in the NN, the larger the difference between runtime for NN verification and runtime for SDT verification. ## VI Conclusion We proposed a cost-effective algorithm to construct equivalent SDT controllers from any discrete-output argmax-based NN controller. Empirical evaluation of formal verification tasks performed on two benchmark OpenAI Gym environments shows a significant reduction in verification times for SDT controllers. Future work includes experimenting with more sophisticated RL environments and investigating an inverse algorithm to transform soft decision tree controllers into neural network controllers.
2307.09602
A max-affine spline approximation of neural networks using the Legendre transform of a convex-concave representation
This work presents a novel algorithm for transforming a neural network into a spline representation. Unlike previous work that required convex and piecewise-affine network operators to create a max-affine spline alternate form, this work relaxes this constraint. The only constraint is that the function be bounded and possess a well-define second derivative, although this was shown experimentally to not be strictly necessary. It can also be performed over the whole network rather than on each layer independently. As in previous work, this bridges the gap between neural networks and approximation theory but also enables the visualisation of network feature maps. Mathematical proof and experimental investigation of the technique is performed with approximation error and feature maps being extracted from a range of architectures, including convolutional neural networks.
Adam Perrett, Danny Wood, Gavin Brown
2023-07-16T17:01:20Z
http://arxiv.org/abs/2307.09602v1
A max-affine spline approximation of neural networks using the Legendre transform of a convex-concave representation ###### Abstract This work presents a novel algorithm for transforming a neural network into a spline representation. Unlike previous work that required convex and piecewise-affine network operators to create a max-affine spline alternate form, this work relaxes this constraint. The only constraint is that the function be bounded and possess a well-define second derivative, although this was shown experimentally to not be strictly necessary. It can also be performed over the whole network rather than on each layer independently. As in previous work, this bridges the gap between neural networks and approximation theory but also enables the visualisation of network feature maps. Mathematical proof and experimental investigation of the technique is performed with approximation error and feature maps being extracted from a range of architectures, including convolutional neural networks. Machine Learning, Neural Networks, Neural Networks, Neural Networks, Neural Networks ## 1 Introduction ### Interpreting networks Interpretability of neural networks is of increasing importance as they become embedded in more facets of everyday life. Applications such as medical diagnoses or self-driving cars would greatly benefit from easily applied inspection techniques. This would enable extracted network features to be validated and possibly used to make inferences about the data, such as knowing what features are indicative of certain diseases and responses. Being able to shine light into the black boxes that are neural networks facilitates verification beyond validation with hidden test data. A common technique for understanding what input features correspond to particular outputs is to apply gradient ascent on the inputs whilst aiming to maximise a particular output's probability, also termed input optimisation (Erhan et al., 2009; Simonyan et al., 2013). As it relies on gradient techniques it can fall into common issues such as gradient saturation, initialisation sensitivity and local optima. There is also little guarantee about the extracted saliency map's relation to the trained features of the network. An alternative approach is the use of a complimentary deconvolutional network (Zeiler and Fergus, 2014; Linardatos et al., 2021). In effect the same filters of a convolutional layer are applied in reverse to extract the input saliency map. They have shown good performance in network interpretability but lack spatial precision because of the reverse convolution operation. They are also architecture dependant and therefore not a general purpose tool. Techniques are also available to understand what features were selected as pertinent in an image using gradient information (Zhou et al., 2016; Selvaraju et al., 2017), although this is on an image-by-image basis and does not extract general properties of the trained network. ### Network transformation It was previously shown by Balestriero et al. that neural networks could be represented as a combination of Max-Affine Spline Operators (MASO) (Balestriero et al., 2018; Balestriero and Baraniuk, 2021). Splines are a way of approximating a continuous function with a combination of straight lines, or planes in high dimensions. This work provided a link between deep neural networks and approximation theory and was used to generate a regularisation technique which aided training. The contribution of Balestriero et al. was to show that neural network layers using convex operators, including convolution and pooling, can be represented as max-affine splines if they are piecewise-affine, such as ReLU, and approximated arbitrarily close if they are not piecewise. There is also discussion of how non-convex operators could be modelled as a combination of MASOs, although this is not explored experimentally. This technique is limited to creating a MASO of each layer individually and cannot be used to extract feature maps of the whole network. The work of this paper presents a novel method for network transformation that converts all layers simultaneously into a pair of complementary Convex and Concave Splines (CCS). This alternate form allows feature maps to be extracted from the trained network to aid interpretability. There are no requirements of convexity, it only needs to be a bounded function with a well-defined second derivative, although it will be show experimentally how this constraint can be relaxed. ### Contributions 1. A novel method of splitting a neural network into complementary convex and concave components 2. The application and subsequent sampling of a Legendre transform of the convex and concave components to create a max-affine spline approximation of the original neural network that is embarrassingly parallel in operation 3. A novel method for feature visualisation and interpretation is proposed 4. The investigation of the CCS approximate form to evaluate network complexity ## 2 Background Inspection of neural network behaviour is of increasing importance as they become crucial components of safety critical functions. There have been probing techniques which inspect the network (Zeiler and Fergus, 2014; Linardatos et al., 2021). Common techniques involve performing gradient ascent on the inputs to create representation that maximises the activation of hidden neurons or outputs. There have also been investigations into the theoretical bounds of neural network capacity, although these fall short of explaining a trained neural network's behaviour (Tishby and Zaslavsky, 2015; Achille and Soatto, 2018). An alternative neural network spline representation was presented by Balestriero et al. (Balestriero et al., 2018; Balestriero and Baraniuk, 2021) which showed that, by converting a network, properties can be inspected and understood using established mathematical techniques from approximation theory. Other authors have made the link between neural networks and splines but often only for single layers and in combination with piecewise linear (PWL) activations, such as ReLU (Parhi and Nowak, 2022; DeVore et al., 2021; Bunel et al., 2017, 2020; Misener and Floudas, 2010; Chu et al., 2018). Theoretical extensions are suggested for non-piecewise activation functions but to the authors knowledge there are no experimental examples as of writing. ### Affine (Linear) splines Splines make an attractive alternative form for neural networks with PWL activations as it becomes possible to exactly match the original function with a finite set of splines and they also map \(\mathbb{R}^{D}\rightarrow\mathbb{R}\). In the domain \(\mathbb{R}^{D}\) the functional combination of \(N\) splines are a set of hyperplanes with slope parameters \(\alpha\in\mathbb{R}^{DxN}\) and offsets \(\beta\in\mathbb{R}^{N}\). As only one hyperplane is selected for any particular point in the domain this is equivalent to partitioning the domain into N regions. This problem requires the creation of complex polyhedra where each hyperplane meets another (Chu et al., 2018; Misener and Floudas, 2010; Bunel et al., 2020), termed knots in 1-D. If the function is convex then this step can be skipped and the maximum the hyperplanes can taken, avoiding the need for knots. This was exploited by Balestriero et al. (Balestriero et al., 2018; Balestriero and Baraniuk, 2021) to create a Max-Affine Spline (MAS) representation of a neural network layer. However, this relies on the use of PWL activation functions and some guarantees need to be made about convexity of the network function. Theoretical explanation is given to how non-convex and non-piecewise function could be approximated with a combination of MASs but no method for generating that was given. ### A convex-concave representation It has been proven than any (PWL) function can be expressed as the difference between two convex PWL linear functions, alternatively the addition of a convex and concave function (Wang, 2004). As any continuous function can be approximated arbitrarily closely by a PWL function as the number of linear elements tends to infinity, by extension this means any continuous function can be approximated by the difference between two convex PWL functions. As was discussed in the MaxOut paper (Goodfellow et al., 2013) and by Balestriero et al. (Balestriero et al., 2018; Balestriero and Baraniuk, 2021) this means the difference between two MASs can approximate any continuous function. When applied to neural network approximation the difficulty then becomes finding the appropriate convex and concave function. The Concave-Convex Procedure (Yuille and Rangarajan, 2003) was developed to find a suitable combination by minimising an energy function. In this method the Legendre transform is used to move to a suitable domain in which a cost function can be constructed to minimise over. The work of this paper aims to skip the need for optimisation by creating a creating a convex and concave representation by exploiting knowledge of the second derivative of the function that is being approximated. ## 3 Methodology ### Max-Affine Splines Approximation theory aims to approximate a complex function with a simpler one. A spline function is an example of how a complex function can be approximated by the combination of linear segments. A max-affine spline (MAS) is a multivariate function (De Boor & De Boor, 1978) mapping \(\mathbb{R}^{D}\rightarrow\mathbb{R}\) which combines splines using the maximum function, taking the form below \[\mathrm{mas}(x)=\max_{i=1,\ldots,N}\alpha_{i}\cdot x+\beta_{i}, \tag{1}\] where \(\alpha_{i}\in\mathbb{R}^{D}\) is one of the \(N\) slope parameters, \(\beta_{i}\in\mathbb{R}\) is its corresponding offset and \(x\in\mathbb{R}^{D}\) are the input values. As \(N\rightarrow\infty\) this can approximate any convex function. Swapping the maximum function to a minimum allows to approximate any concave function. ### The Legendre transform The Legendre transform is a powerful tool used to transform a function of one quantity into a conjugate quantity. This can be used to convert from a function of points \(x\) to a function of gradients \(m\). The Legendre transform of a function \(f(x)\) to a gradient formulation is shown in Eq. 2, where \(\sup\) is the supremum. \[f^{*}(m)=\sup_{x\in\mathbb{R}}mx-f(x) \tag{2}\] By sampling from \(f^{*}(m)\) a collection of gradients can be used to describe the original function. They take the form of a linear function \(y=mx+c\) where \(m\) is the gradient and \(c=f(x)\). The maximum operation can be used in place of the supremum and then this takes the form a MAS. The problem with taking a Legendre transform of a neural network, as is the aim of this work, is that it only works for convex functions. ### A convex-concave representation of any function **Theorem 1:** Any function with a well-defined second derivative can be expressed as the sum of a convex function and a concave function (Klee, 1976). **Theorem 2**: Any continuous PWL function can be expressed as the combination of a convex and concave PWL function (Wang, 2004). For a function to be convex the second derivative must be greater than or equal to zero, \(f^{\prime\prime}(x)\geq 0\). This means if the second derivative of a function is know a convex representation can be constructed by adding a term to the second derivative to ensure it is always above zero. Using the sigmoid function as an example \[f(x)=\frac{1}{1+e^{x}}=\sigma(x), \tag{3}\] the second derivative is \[f^{\prime\prime}(x)=\sigma(x)(1-\sigma(x))(1-2\sigma(x)), \tag{4}\] which is minimum at \(x=\frac{1}{2}+\frac{1}{2\sqrt{3}}\) with \(f^{\prime\prime}(x)=\frac{-1}{6\sqrt{3}}\approx-0.96\). By adding \(0.96\) to the second derivative and twice integrating back a convex function is created. Any constant from integration can be set to zero as it does not effect the second derivative. \[f_{\text{convex}}(x)=\frac{1}{1+e^{x}}+0.96x^{2}, \tag{5}\] however, the original function is lost because of the additional \(x^{2}\) term. We can follow a similar method to create a concave representation of the function which can cancel out the \(x^{2}\) term, \[f_{\text{concave}}(x)=\frac{1}{1+e^{x}}-0.96x^{2}, \tag{6}\] which leads to \[f(x)=0.5(f_{\text{convex}}+f_{\text{concave}}). \tag{7}\] Due to the symmetry of the sigmoid function the minimum of the second derivative is the opposite sign of the maximum of the second derivative. In other more complicated functions the maximum magnitude of the maximum and minimum of the second derivative must be added to create complementary convex and concave parts. This leads to the general form \[f(x)=0.5(f(x)+cx^{2}+f(x)-cx^{2}), \tag{8}\] where \[c=\max(|\max(f^{\prime\prime}(x))|,|\min(f^{\prime\prime}(x))|). \tag{9}\] By splitting the function into a convex and concave part the Legendre transform can now be applied to create two complementary MAS approximations of the original function. In the implementation throughout this work \(f(x)\) and \(cx^{2}\) are kept separate to avoid any washing out of values of \(f(x)\) in floating point due to large values of \(cx^{2}\). It requires no more parameters than keeping a separate convex and concave function as \(c\) is common across both. ### A convex-concave neural network A neural network with appropriate neuron activation is a bounded function with a well-defined second derivative. As \(\mathbf{x}\) is now a vector the first step requires taking the Hessian of the overall network. This creates a Hessian matrix of partial derivatives \(H=\nabla^{2}f(\mathbf{x})\). The original function is convex if and only if \(H\) is positive semi-definite (PSD) for all \(\mathbf{x}\). The Hessian is symmetric since \[\frac{\delta}{\delta x_{i}\delta x_{j}}f(\mathbf{x})=\frac{\delta}{\delta x_{ j}\delta x_{i}}f(\mathbf{x}), \tag{10}\] and a symmetric matrix is PSD if and only if the eigenvalues are positive. **Proposition 1:** If \(\nabla^{2}f(\mathbf{x})\) entries are bounded, there exists \(c>0\) such that \(H+cI\) is PSD for all \(\mathbf{x}\). If all eigenvalues are positive it is already convex and \(c=0\). Assuming the minimum eigenvalue, \(\varepsilon\), is less than zero \(c\) is non-zero. To calculate \(c\) let \(\lambda\) be an eigenvalue of \(H\) with eigenvector \(\mathbf{v}\) then \[\lambda\mathbf{v} =H\mathbf{v}, \tag{11}\] \[\lambda\mathbf{v}+c\mathbf{v} =H\mathbf{v}+c\mathbf{v},\] (12) \[(\lambda+c)\mathbf{v} =(H+c)\mathbf{v}, \tag{13}\] so \(\lambda+c\) is an eigenvalue of \(H+c\). Then set \(c=-\varepsilon\) and the Hessian is now PSD. But what is the convex function of \(\nabla^{2}f(\mathbf{x})+cI\)? Consider \[g(\mathbf{x})=\mathbf{x}^{T}\mathbf{x}=\sum_{i}\mathbf{x}^{2}, \tag{14}\] \[\frac{\delta}{\delta x_{i}\delta x_{j}}g(\mathbf{x})=\begin{cases}1&\text{if }i=j \\ 0&\text{otherwise,}\end{cases} \tag{15}\] so the Hessian of \(g(\mathbf{x})=I\). Therefore \(\nabla^{2}f(\mathbf{x})+cI\) is the Hessian of \(f(\mathbf{x})+c\mathbf{x}^{T}\mathbf{x}\). Similar to the method described in Section 3.3 the minimum value of the eigenvalue is used for the convex and maximum for the concave function. The maximum absolute value is used to generate a common value of \(c\) which guarantees that both partitions of the neural network are complementary and respectively convex and concave. This procedure is carried out for each output of the network individually, creating a value of \(c\) for each. Practically, when performing this step, as calculating the exact form of the Hessian at all points is computationally complex, the Hessian is evaluated at each input data point using the PyTorch Hessian function. The minimum and maximum value across all points is used to generate the value of \(c\) for each output. #### 3.4.1 A convex-concave PWL neural network Functions, such as ReLU, are twice differentiable but because of their piecewise nature their second derivative is not well-defined which is a requirement when generating the Hessian. Experimentally it was found that using the value of \(c\) calculated by a neural network using non PWL functions trained on the same task was sufficient. It will also be shown later that relatively arbitrary values of \(c\) can be used to create approximate convex and concave forms of PWL neural networks. ### Approximating MNIST The MNIST dataset with the standard 60,000/10,000 train/test split is used for benchmarking neural network approximation (LeCun, 1998). 0.5 is subtracted from input values to centre them around zero. All networks in the following section were trained in PyTorch with stochastic gradient descent with momentum. Across all examples a learning rate of 0.05 used with a momentum value 0.9 and 50% dropout trains the network for 300 epochs with cross-entropy loss. Sigmoid activation is used unless otherwise stated. The CNN used uses two convolutional layers followed by a hidden layer of size 200. The first had 1 input channel, 16 output channels, a kernel size of 5x5, stride 1, and padding 2. Sigmoid activation and max pooling (kernel size 2x2) followed. The second convolution layer had 16 input channels, 32 output channels, and the same kernel size, stride, padding, activation, and max pooling. The justification for using clustering to explore network complexity comes from each spline capturing elements of the original function. Therefore, the fewer planes required the simpler the function. When clustering the gradients and offsets of splines are concatenated into a single vector and clustered using the fast PyTorch K-means package. The clustering is run 10 times at each value of K to attain a mean and standard deviation. All experiments are run using a single NVIDIA a100 80GB GPU. Code for the experiments can be found at [https://github.com/adamgoodtime/Legendre_Net.git](https://github.com/adamgoodtime/Legendre_Net.git). ## 4 Experiments and Results ### Transforms in 1D The first example displays the capability to create a Convex-Concave-Spline (CCS) representation of non-convex functions. Figure 1(a) shows the convex and concave pair which are constructed to approximate a Gaussian function. The faintly coloured lines show the uniformly sampled planes with the maximum of the green lines being used to create the convex component and the minimum of the blue lines used to create the concave component. These are then averaged to create the CCS approximation of the Gaussian function. Figure 1(b) shows the same procedure to approximate a sigmoid function. Figure 1(c) applies the same technique to a combination of 400 Gaussian functions with mean, standard deviation and weight drawn uniformly from \([-3,3]\), \([0,0.2]\) and \([-1,1]\) respectively. 300 planes are uniformly sampled across the 1D domain, for both the convex and concave function, which corresponds to the same number of parameters as is used by the Gaussian combination. The error visible at various points is a result of the sampling frequency. The planes are sampled uniformly across the input space and, therefore, if the original function changes rapidly between sample locations the change in gradient is not precisely captured. This can be remedied by increasing the number of planes but this \begin{table} \begin{tabular}{|c|c|c|c|} \hline Architecture & Test acc. \% & CCS acc. \% & Approx. loss \% \\ \hline \hline 200x5 & 98.47 & 97.69 & -0.78 \\ \hline 200x4 & 98.53 & 97.94 & -0.59 \\ \hline 200x3 & 97.9 & 97.35 & -0.55 \\ \hline 200x2 & 98.11 & 97.44 & -0.67 \\ \hline 1600x1 & 98.27 & 97.62 & -0.65 \\ \hline 800x1 & 98.18 & 97.64 & -0.54 \\ \hline 400x1 & 98.24 & 97.52 & -0.72 \\ \hline 200x1 & 98.1 & 97.74 & -0.36 \\ \hline CNN & 99.04 & 97.81 & -1.23 \\ \hline ReLU-200x2 & 98.5 & 97.64 & -0.86 \\ \hline ReLU-200x1 & 98.12 & 97.18 & -0.94 \\ \hline ReLU-200x1 c=5 & 98.12 & 97.11 & -1.01 \\ \hline \end{tabular} \end{table} Table 1: The MNIST test accuracy of the final models and the test accuracy of the CCS approximation using all planes. The final column shows the loss in accuracy following approximation. The architecture denotes the hidden layer width and depth using sigmoid activation unless otherwise stated. c=5 is a middling value of \(c\) for the ReLU network, although there is little variance around the chosen value of \(c\). Figure 1: (a) A reconstruction of a Gaussian function with CCS. The faint lines show the planes of which the maximum (minimum) is taken to produce the convex (concave) function. (b) The same as (a) for a sigmoid activation function. (c) The CCS of 400 Gaussian functions combined. The inset shows the largest approximation error coming from limited sampling around a period of rapid change. would require more computation resource. There is also the opportunity to non-uniformly sample planes and increase sampling around periods with large second derivatives, however, this is non-trivial. ### Approximating a network trained on MNIST Table 4.1 shows the final test accuracy and approximation accuracy across a range of architectures. The approximation accuracy is relatively consistent across architecture settings. The most significant inaccuracy is from the single layer ReLU networks. Although, little difference is observed when using a uniform value of \(c\) or when using the calculated \(c\) from the 200x1 sigmoid network. The main difference in approximation loss is a result of the test accuracy of the network rather than the approximation accuracy as that is relatively consistent. ### Exploring network complexity with clustering The CCS approximation generates a plane for every data point in the training set. This leads to a perfect correspondence in training accuracy between the original network and the approximate form but effects the testing accuracy. It can also lead to many planes, 60,000 for MNIST. To examine the redundancy of the CCS procedure planes are clustered using K-means. A range of K values is chosen to see how varying the number of planes changes the faithfulness of the approximation. Across the plots of Figure 2 the CNN approximation is consistently lower, requiring around a magnitude more clusters to reach similar levels of approximation accuracy compared to other architectures. This can be understood as a measure of the complexity of the network. More planes are required match to function of the network meaning there is less redundancy. This also means the the network varies more across the input space and therefore is more computationally complex. This idea will be further explored in Section 4.4. It can be seen in Figure 2(a) that layer size has little effect on the ability to approximate the network. This is likely a result of the expressivity of the network being fairly consistent across various layer sizes with added neurons not significantly effecting the test accuracy. This means the CCS is capturing a similarly shaped function and therefore achieves similar performance across different hidden layer sizes. When comparing the approximation accuracy across different sizes of depth in Figure 2(b) a less clear picture emerges with the shallowest and deepest networks being the best approximated and layer depths of two and three containing the highest approximation errors. A possible explanation for this is that a shallow network has the lowest complexity and therefore can be approximated relatively well. As the number of layers increases the the complexity grows and with it the the algorithm struggles to approximate the complex function. However, once the depth goes beyond a certain point a degree of smoothing happens over the input space as a result of more information dispersal across the layers and regularisation via dropout. This will be explored in the Sec 4.4 where features will be extracted from various architectures and contrasted. Examining the ReLU network approximation error shows that the choice of \(c\) does not need to be precise with a uniform and calculated value of \(c\) achieving similar approximation error. The value of \(c=5\) was chosen as the uniform value, although there was little sensitivity to the value between the range of 2 and 10. Less than 2 and the convex and concave components were not curved enough to capture the function of the network and beyond 10 there was diminishing returns from increased curvature due to floating point limitations. A surprising result from Figure 2(c) is that the best approximation came from ReLU network of depth 2 and the worst from a sigmoid network of depth 2. A possible explanation for this is the increased classification of the 2-layer ReLU network. Also, there is no significant increase in classification accuracy between the 2-layer sigmoid network and the 1-layer networks but there will be an increased complexity over the input space which will be harder for the approximation to capture. ### Examining features Following the clustering of planes random clusters are selected to inspect the features of the network. A small value of \(K=10\) is used to increase the disparity between clusters. As was discussed in Section 3.3, the gradient and offset of \(f(x)\) and \(cx^{2}\) are kept separate, allowing the extraction of the gradient component of the plane that relates to the original function, \(f^{\prime}(x)\). This corresponds to the network's feature map for a particular output as the gradient shows what input would create the highest variability in response of the network. Figure 3 compares the extracted features of four randomly selected clusters for the output zero. The features of shallow networks are consistent, with little variation across clusters. The deeper networks contain noticeable variation across clusters suggesting a higher information content captured by the network function. The 3-layer network has a significantly noisier feature map, which corresponds to the worse test accuracy. Although the 5-layer network has varied feature maps, the approximation is still good due to the quality of the features, which can be seen by their relative smoothness and lack of noise. The CNN has by far the smoothest and most varied feature maps. The features also look the least like the number zero. This suggests a high Figure 2: K-means was run until convergence across all examples and then the classification accuracy on the test set was calculated using the selected planes. Clustering was performed 10 times with the line showing the mean and the shaded region the standard deviation. The effect of clustering the CNN planes is shown across all plots as a benchmark. (a) shows the effect of layer width in a neural network with one hidden layer. (b) keeps the layer width the same but alters the depth of the network. (c) displayed how using approximate forms of \(c\) for ReLU networks effects approximation and contrasts it with sigmoid networks of the same network size. degree of variability in the CNN response across the range of possible inputs. This explains the need for more planes to approximate the CNN function as there are fewer redundant planes and a diverse set of responses. The smoothness of the response also displays a low sensitivity to noise. ## 5 Discussion and Limitations It has been shown in this work that an alternate convex and concave representation of any bounded function with a well-defined second derivative can used to construct an approximate form using Max-Affine Splines (MAS), creating a Convex-Concave Spline (CCS) representation. This was displayed for complex non-convex functions and also applied to neural network approximation. This alternate form creates further bridges to approximation theory. It was also shown experimentally that approximate forms can be created for piecewise linear (PWL) functions which possess undefined second derivatives at their points of inflection. The CCS representation allowed inspection of feature maps. This enabled the inspection and comparison of network function and an approximation of functional complexity. The construction of the MAS also lends itself to highly parallel computation as each spline can be computed independently. Networks with multiple layers and convolutional filers can be flattened into a combination of linear operators. In theory, the same method can be used for individual neurons, although this is left for future work. Although CCS can model any continuous bounded function with a well-defined second derivative it is still a PWL approximation and the approximation error only tends to zero as the number of planes tends to infinity. In this method a sample is taken at each training data point, which lead to an exact correspondence between the network and the CCS in training data accuracy but lead to test accuracy dropping by around 0.5-1%. In the future, optimisation could be performed to create a more condensed CCS form. Also the Hessian is only evaluated around the training data values which means it may not capture the full potential dynamic range of the network. An exact form was created for the the 1D examples, however, this is left to future work for neural network approximation. The addition to the second derivative to guarantee convexity is not an optimal choice as \(x^{2}\) can become very large in comparison to the original function. When integrating back the constant was set to zero, choosing a different value could alleviate this problem. In the work of Yuille and Rangarajan (Yuille & Rangarajan, 2003) an energy function is minimised to generate complementary convex and concave functions, although this has not been extended to neural network approximation. Comparison across architectures enabled the interrogation of network complexity. As is often the problem with features map generation the interpretation is qualitative and left to subjective explanation. Future work would benefit from quantitative descriptions of the extracted feature maps to Figure 3: The feature maps of different architectures for the MNIST class zero extracted from the CCS representation. A lighter shade corresponds to a positive weight and darker negative. make precise and objective claims about the networks being investigated. A measure of variability across feature maps would be straightforward to implement. Designing a metric to measure noise present in a feature map would be more complicated when extending beyond image classification.
2306.13215
OVLA: Neural Network Ownership Verification using Latent Watermarks
Ownership verification for neural networks is important for protecting these models from illegal copying, free-riding, re-distribution and other intellectual property misuse. We present a novel methodology for neural network ownership verification based on the notion of latent watermarks. Existing ownership verification methods either modify or introduce constraints to the neural network parameters, which are accessible to an attacker in a white-box attack and can be harmful to the network's normal operation, or train the network to respond to specific watermarks in the inputs similar to data poisoning-based backdoor attacks, which are susceptible to backdoor removal techniques. In this paper, we address these problems by decoupling a network's normal operation from its responses to watermarked inputs during ownership verification. The key idea is to train the network such that the watermarks remain dormant unless the owner's secret key is applied to activate it. The secret key is realized as a specific perturbation only known to the owner to the network's parameters. We show that our approach offers strong defense against backdoor detection, backdoor removal and surrogate model attacks.In addition, our method provides protection against ambiguity attacks where the attacker either tries to guess the secret weight key or uses fine-tuning to embed their own watermarks with a different key into a pre-trained neural network. Experimental results demonstrate the advantages and effectiveness of our proposed approach.
Feisi Fu, Wenchao Li
2023-06-15T17:45:03Z
http://arxiv.org/abs/2306.13215v2
# OVLA: Neural Network Ownership Verification using Latent Watermarks ###### Abstract Ownership verification for neural networks is important for protecting these models from illegal copying, free-riding, re-distribution and other intellectual property misuse. We present a novel methodology for neural network ownership verification based on the notion of _latent watermarks_. Existing ownership verification methods either modify or introduce constraints to the neural network parameters, which are accessible to an attacker in a white-box attack and can be harmful to the network's normal operation, or train the network to respond to specific watermarks in the inputs similar to data poisoning-based backdoor attacks, which are susceptible to backdoor removal techniques. In this paper, we address these problems by _decoupling_ a network's normal operation from its responses to watermarked inputs during ownership verification. The key idea is to train the network such that the watermarks remain dormant unless the owner's secret key is applied to activate it. The secret key is realized as a specific perturbation only known to the owner to the network's parameters. We show that our approach offers strong defense against backdoor detection, backdoor removal and surrogate model attacks.In addition, our method provides protection against ambiguity attacks where the attacker either tries to guess the secret weight key or uses fine-tuning to embed their own watermarks with a different key into a pre-trained neural network. Experimental results demonstrate the advantages and effectiveness of our proposed approach. ## 1 Introduction Deep neural networks (DNNs) have demonstrated impressive performances on a wide variety of applications ranging from image recognition Krizhevsky et al. (2012) to protein folding Jo et al. (2015). Obtaining these levels of performance often requires constructing large models with many parameters. For example, the well-known VGG-16 network Simonyan and Zisserman (2014) has about 138 million parameters, not to mention that the more recent large-scale language models like GPT-3 Floridi and Chiriatti (2020) which has 175 billion parameters. Training these models are expensive - requires a large amount of good-quality training data Krizhevsky et al. (2012), dedicated GPU clusters Patterson et al. (2021), days if not weeks to train Patterson et al. (2021), and specialized tuning Sada (2021). Given the high cost of developing and training these models and the massive profits that they may help generate, these models are valuable intellectual properties (IPs) to their owners and it is important to protect them from misuse such as illegal copying, re-distribution, and free-riding. In this paper, we refer to the type of schemes that aim that ascertaining the ownership of a neural network _ownership verification (OV)_. Most approaches for neural network ownership verification employ some form of _digital watermarks_. In the context of DNNs, the watermark information is embedded into a hosting DNN Uchida et al. (2017); Nagai et al. (2018); Adi et al. (2018); Zhang et al. (2018); Ma et al. (2021); Wang et al. (2021). A DNN model can then be queried to extract the watermark or verify the presence of a watermark. Existing methods of DNN watermarking roughly fall into the following two categories. 1. **Static Watermarking**. The idea is to embed watermark information into the weights of a DNN. Representative techniques include adding a parameter regularization term to the DNN loss function and then verifying the ownership of the DNN by parameter projection Uchida et al. (2017), Nagai et al. (2018), and generating a matrix as a fingerprint of the DNN and inserting the fingerprint by adding a penalty term to force the user-selected parameters to be close to the fingerprint matrix Chen et al. (2019). One problem of such approaches is that the additional parameter constraints can degrade the DNN's performance for normal operation. In addition, it has been shown that most static watermark schemes are vulnerable to watermark removal attacks such as model compression Cheng et al. (2017), fine-tuning Wang and Kerschbaum (2019), and watermark overwrites Wang and Kerschbaum (2019). A recent paper leverages this insight to embed a parameter mask as the watermark such that the network would still have high accuracy when it is pruned using this mask Chen et al. (2021). However, one potential issue with this approach is that a user-designed mask limits the structure of pruned model and can hinder training. Finally, it is also worth noting that an OV scheme that uses static watermarks requires a judge or the owner to have _white-box access_ to the DNN in question. 2. **Dynamic Watermarking**. The idea is to train the DNN to produce specific outputs when a pre-determined watermark is present in the input Adi et al. (2018), Zhang et al. (2018), Yang et al. (2021). Given the connection to backdoor attacks on neural networks Gu et al. (2017), this approach is sometimes referred to _backdoor-based watermarks_. In a similar vein, authors of Le Merrer et al. (2020) propose to use adversarial perturbations of certain training examples as watermarks. When separate training instances are used as watermarked inputs, these inputs are also called a trigger set in the literature Fan et al. (2019). An advantage of dynamic watermarking is that it allows the owner to probe the DNN in question by supplying watermarked inputs and observing the DNN's outputs without white-box access to the network. However, similar to static watermarking schemes, dynamic watermarking is also susceptible to watermark removal attacks via fine-tuning, model pruning or watermark overwriting Boenisch (2020). In addition, dynamic watermarking schemes is vulnerable to surrogate model attacks Dong et al. (2021), i.e. an attacker can create a surrogate DNN by querying the victim model and then extract the watermark information through trigger reverse-engineering Wang et al. (2019). In addition to watermark removal and surrogate model attacks, ambiguity attacks Craver et al. (1998), Fan et al. (2019) post significant challenges to DNN ownership verification. These attacks aim at casting doubt on the ownership of a DNN by forging additional watermarks on top of the original ones. An effort aimed at failing this type of attacks adds a so-called passport layer after each convolutional layer to modulate the performance of the network depending on the correctness of the user-supplied passport Fan et al. (2019). However, due to the coupling of passport learning and model learning, there is a substantial drop in normal-operation performance. On the other hand, distributing the passports along with the models for normal operation cannot prevent illegal copying or re-distribution. A subsequent work extended this idea by removing the need to change the network's architecture and training a passport-aware branch that is only added during ownership verification Zhang et al. (2020). However, it still suffers from performance degradation compared to a normally trained model. Another work applies the passport idea which was originally developed for convolutional neural networks to watermarking generative adversarial networks Ong et al. (2021). In this paper, we propose OVLA (**o**w**nership **v**erification using **I**a**tent **w**atermarks), a novel DNN ownership verification methodology with strong performance guarantee, defense against backdoor detection, backdoor removal, surrogate model attacks and ambiguity attacks. The key idea of OVLA is to _decouple the network's normal operation from its responses to watermarked inputs during ownership verification_. Instead of limiting the passport to the normalization layers of the DNN such as in Fan et al. (2019), Zhang et al. (2020), we show that it is possible to realize the passport (called _secret weight key_ in this paper) as a perturbation to the weights of almost any layer in the network. Compared with existing approaches, OVLA provides provably guarantee on the network's performance during normal operation. We show that OVLA-watermarked DNNs can effectively evade backdoor detection techniques, are immune to surrogate model attacks, and are resistant to watermark removal methods such as fine-tuning and model pruning. In addition, OVLA offers strong defense against ambiguity attacks where the attacker either tries to guess the secret weight key or uses fine-tuning to embed their own watermarks with a different key into a pre-trained neural network. The latter type of ambiguity attacks is unexplored in current literature. Figure 1 illustrates the high-level ownership verification flow of OVLA, where the user registration mechanism is designed specifically for guarding against the second type of ambiguity attacks (details in Section 2.7). We summarize our contributions below. 1. We present OVLA, a novel DNN ownership verification methodology that effectively decouples ownership verification from the DNN's normal operation. 2. We provide theoretical analysis to show that OVLA is the first DNN ownership verification method with provable performance guarantees and strong defenses against surrogate model attacks and fine-tuning-based ambiguity attacks. The latter is not explored in current literature. 3. Across a set of benchmarks, OVLA- watermarked DNNs show strong empirical resistance against backdoor detection, backdoor removal, key guessing-based ambiguity attacks. ## 2 Background ### Deep Neural Networks An \(R\)-layer feed-forward DNN \(f=\kappa_{R}\circ\sigma\circ\kappa_{R-1}\circ...\circ\sigma\circ\kappa_{1}:X\to Y\) is a composition of linear functions \(\kappa_{r},r=1,2,...,R\) and activation function \(\sigma\), where \(X\subseteq\mathbb{R}^{m}\) is the input domain and \(Y\subseteq\mathbb{R}^{n}\) is the output domain. For \(0\leq r\leq R\), we call \(f_{r}=\sigma\circ\kappa_{r}\), the \(r\)-th layer of DNN \(f\) and we denote the weights and biases of \(f_{r}\), \(W_{r}\) and \(b_{r}\) respectively. We use \(\theta=\{W_{r},b_{r}\}_{r=1}^{r=R}\) to denote the set of parameters in \(f\), and we write \(f(x)\) as \(f(x;\theta)\). ### Digital Watermarking In general, digital watermarking refers to a technique that embeds a message, called watermark information, into a hosting multimedia content. In this paper, we consider zero-bit watermark which is also known as ownership verification. In general, a watermarking technique includes two parts: embedding and extraction (verification). (1) For embedding, an embedding function \(E\) takes some watermark information \(W\) and a carrier model \(M\) and output a watermarked model \(M^{\prime}=E(\bar{M},W)\). (2a) For extraction, the goal is to extract the watermark information \(W^{\prime}\) (potentially different from \(W\) due to imperfect extraction) from a watermarked model \(M^{\prime}\). We use \(D\) to denote the extraction function such that \(W^{\prime}=D(M^{\prime})\). (2b) During ownership verification, the verification function \(D\) takes \(W\) and \(M^{\prime}\) as inputs and outputs \(D(W,M^{\prime})=\{\texttt{True},\texttt{False}\}\). ### Backdoor Attacks We consider data poisoning-based backdoor attacks that train a DNN with a portion of the training data modified to include pre-determined trigger pattern(s) and their target label(s). An example trigger pattern is a small yellow square pasted on a specific location of an image. The training process will force the DNN to associate any image with the trigger pattern to the target label. We call \(f\) a backdoored DNN if it has a high accuracy on clean data and classifies trigger data to its target label. ### Zero-bit Backdoor-based Watermarking We consider zero-bit backdoor-based watermark which applies backdoor attacks as the watermark embedding function and then verifies the presence of the watermark by checking the network's accuracy on a set of inputs with the trigger added (henceforth called a _trigger set_ for convenience)1. Figure 1: Flow chart of OVLA. The embedding process is to train a DNN \(f=E(D,D_{T},T_{L})\) with additional trigger data \(D_{T}\) and trigger labels \(T_{L}\), where \(D\) is the original training data. Watermark verification is to verify the watermarked DNN's accuracy on trigger data, \(T^{\prime}_{L}=D(f,D_{T})\), where \(T^{\prime}_{L}\) is the DNN's prediction on trigger data. If \(T^{\prime}_{L}\) is close to \(T_{L}\), then the verification is considered successful. Formally, the verification process is to check if \[Pr_{x\in D_{T}}[\arg\max f(x)\neq T_{L}(x)]\leq\epsilon \tag{1}\] where \(\epsilon\) is a user-defined threshold and \(\arg\max\) is to take the label with the maximal probability as predicted by \(f\). ### Adversarial Weight Perturbation Adversarial weight perturbation (AWP) has been introduced for improving the robustness of a neural network Wu et al. (2020). Several existing works Rakin et al. (2020); Chen et al. (2021); Garg et al. (2020); Ning et al. (2022) show that adversarial weight perturbation can be used in place of data poisoning to introduce a backdoor to a DNN. For a DNN \(f(x;\theta)\), we call \(\delta\) an AWP if by adding \(\delta\) to the weight parameters \(\theta\), the resulting DNN \(f(x;\theta+\delta)\) is is a backdoored DNN for some trigger set known to the attacker. ### Surrogate Model Attacks In a surrogate model attack, the attacker treats the victim watermarked DNN as a black-box and tries to replicate its functionality by constructing a surrogate model that is trained from repeated input-output queries on the victim DNN. The attacker then reverse-engineers the watermark information from the surrogate model Li et al. (2021); Gou et al. (2021). ### Ambiguity Attacks Ambiguity attacks aim to cast doubt on the ownership of the model Craver et al. (1998). The ambiguity arises when two separate parties can both claim ownership of the model by demonstrating successful ownership verification on their chosen watermarks. In this paper, we consider two kinds of ambiguity attacks: 1. **Free-rider Attacks**. The attackers, known as free riders, benefit from the system without contributing their fair share Lin et al. (2019). In DNN OV, a free-rider is an attacker who embeds their own watermark into a DNN which was not trained by them. In particular, we consider the setting where the attacker fine-tunes a pre-trained DNN to embed their own watermark. 2. **Key Guessing Attacks**. The goal of these attacks is to guess the secret weight key or find a substituted key (and the associated trigger set) to claim ownership of the target DNN. ### Free-rider Attacks vs. Key Guessing Attacks. With a slight abuse of the terminology, we use free-rider attacks to refer to attacks that require modifying a pre-trained DNN in a relatively inexpensive way to claim ownership (i.e. they are _almost_ free-riders), and key guessing attacks to refer to attacks that try to "guess" the watermark information and do not require modifying the DNN. ## 3 Overview of Ovla In this section, we introduce the OVLA scheme, which includes: (1) User Registration, (2) Latent Watermark Embedding, and (3) Latent Watermark Verification (Figure 2). The key idea of OVLA is to train the network such that the watermarks remain dormant unless the owner's secret key is applied to activate it. This highlights a fundamental difference between OVLA and existing dynamic watermarking schemes: instead of directly verifying the trigger-set accuracy of the trained DNN \(f(x;\theta)\), _OVLA verifies the trigger-set accuracy of DNN \(\hat{f}=f(x;\theta+\delta)\)_ where \(\delta\) is the owner's secret weight key and we call \(f(x;\theta+\delta)\) the unlocked DNN. In addition, \(f\) is trained in such a way that it does not respond to the trigger. ### User Registration We propose to include a trusted authority (TA) which applies a registration function \(R\) to any user who wishes to register under the OVLA system. The trusted authority plays a similar role as the certificate authority in public-key infrastructure and can double as a judge in ownership disputes. \(R\) takes a user-defined string as input and outputs a secret weight key which is issued to the user. The reason of having a trusted authority is to prevent users from registering a self-designed secret weight key. A non-centralized registration could be built if all the users agree to use the same public one-way function Goldreich as the registration function. The property of a one-way function would make it extremely costly to register a self-designed secret weight key. ### Latent Watermark Embedding The watermark is latent in the sense that the network does not respond to it unless the secret weight key is applied. Latent watermarks are embedded during training using a specially crafted loss function. We use \(L_{1}(\theta)\) to denote the loss for DNN's normal operation on a clean dataset \(D\) (with a label function \(C_{L}\)). To embed a latent watermark, we use a latent watermark dataset \(D_{T}\), which is a subset of clean data injected with the watermark (with a label function \(T_{L}\)) and a pre-determined secret weight key \(\delta\). To separate the DNN's normal operation from latent watermark verification, we define the latent watermark loss \(L_{2}\) as the sum of following three terms: \[L_{2}(\theta)=\sum_{x\in D_{T}}L(f(x;\theta),C_{L}(x))+\lambda_{1}\sum_{x\in D }L(f(x;\theta+\delta),C_{L}(x))+\lambda_{2}\sum_{x\in D_{T}}L(f(x;\theta+ \delta),T_{L}(x))\] where \(\lambda_{1}\), \(\lambda_{2}\) are hyperparameters that control the importance of each term. The first term is used to force the DNN not to respond to latent watermarks without the secret weight key, thereby avoiding leaking any watermark information. The last two terms are designed for latent watermark verification which we will explain in more detail in Section 3.3. Finally, the loss function for the DNN training process is a weighted sum of \(L_{1}\) and \(L_{2}\). ### Latent Watermark Verification To claim the ownership of a DNN \(f\), one should have a registered secret weight key \(\delta\), a latent watermark set \(D_{T}\) and a trigger label function \(T_{L}\). Formally, the verification process is to check if \[Pr_{x\in D}[\arg\max f(x;\theta+\delta)\neq C_{L}(x)]\leq\epsilon_{1}\quad Pr_ {x\in D_{T}}[\arg\max f(x;\theta+\delta)\neq T_{L}(x)]\leq\epsilon_{2} \tag{2}\] where \(\theta\) is the parameter of \(f\) and \(\epsilon_{1},\epsilon_{2}\) are user-defined thresholds. For a latent watermarked DNN \(f\), minimizing the last two terms in loss function 2 force the perturbed DNN \(\hat{f}\) to map any clean data \(x\) to its label \(C_{L}(x)\) and any latent watermark data to its trigger label \(T_{L}(x)\). Therefore, the ownership of a DNN trained with loss function 2 can be verified the owner with the corresponding secret weight key. Figure 2: Left: Watermarked DNN, which behaves like a clean DNN, and does not respond to the watermarked input. Right: Unlocked DNN, which is used for ownership verification and correctly maps a watermarked input to its target class (class 0). ## 4 Analysis of \(\mathtt{O\VLA}\) ### Performance Guarantee In this section, we provide theoretical support on how \(\mathtt{OVLA}\)'s scheme of decoupling the DNN's normal operation and the backdoor-based ownership verification can preserve the performance of the target DNN. First, we show that any continuous function can be approximated by \(f(x;\theta)\) where \(f(x;\theta+\delta)\) is a backdoored DNN. To this end, we consider a stronger version which requires showing that any \(C(\mathbf{R}^{m+k},\mathbf{R}^{n})\) function can be approximated by \(f(x;\theta+\delta)\), where we take \((x,\delta)\in\mathbf{R}^{m+k}\) as variables and \(\theta\) as the parameter of this function. **Theorem 1** (Universal Approximation Theorem for Parameter Space).: _Suppose \(f(x;\theta)\) is a fully connected feedforward neural network with more than four hidden layers. \(\delta\) is a perturbation for the weights of a single layer which is between the 2nd hidden layer and the last 2nd layer inclusive. We claim that the resulting neural network \(f(x;\theta+\delta)\) is a universal approximation for any \(C(\mathbf{R}^{m+k},\mathbf{R}^{n})\), where \(k\) is the dimension of \(\delta\). That is, for any \(g:\mathbf{R}^{m+k}\rightarrow\mathbf{R}^{n}\), there exists a \(\theta\) such that \(\sup||f(x;\theta+\delta)-g(x,\delta)||<\epsilon\)._ **Corollary 1** (Performance Guarantee).: _Suppose \(f(x;\theta)\) is a feed-forward neural network with more than four hidden layers. For any non-zero weight perturbation \(\delta\) which has the same size as the weight of a single layer between the 2nd hidden layer and the last 2nd layer inclusive. Then by the Universal Approximation Theorem for Parameter Space, there exists a secret weight key \(\delta\) such that \(f(x;\theta)\) can approximate any continuous function where \(f(x;\theta+\delta)\) is a backdoored DNN._ Corollary 1 also ensures that \(\mathtt{OVLA}\) can work for any secret weight key issued by the trusted authority. ### Defense against Backdoor Detection We consider backdoor detection techniques based on reverse-engineering the trigger and its target class. Neural Cleanse Wang et al. (2019) is a good representative of these techniques. It assumes a white-box model where the attacker has access to the DNN parameters and uses a gradient-based optimization method to reverse-engineer the trigger and its target class. Such backdoor detection methods can be used by an attacker to extract the watermark information for a backdoor-based watermarked DNN. For \(\mathtt{OVLA}\), without the secret weight key \(\delta\), the watermarked DNN does not respond to the latent watermark. Therefore, for attackers who do not have knowledge of \(\delta\), such backdoor detection methods will not identify the latent watermarks. An experiment in Section 5 shows that the latent watermarked DNNs are indeed closer to clean DNNs than to backdoored DNNs. ### Immunity to Surrogate Model Attacks Surrogate model attacks target both static and dynamic watermarking schemes, since the watermark information (i.e. DNN's weights for static watermarking and the trigger and its target class for dynamic watermarking) could be leaked by performing input-output queries on the target model. On the contrary, a latent watermarked DNN does not respond to the watermarks unless the secret weight key is applied and thus the watermark information would not be leaked through input-output queries. In the following theorem, we claim that \(\mathtt{OVLA}\) is immune to surrogate model attacks due to the arbitrariness of the unlocked DNN, i.e. it is not possible to recover \(f(x;\theta+\delta)\) given only input-output queries of \(f(x;\theta)\). **Theorem 2** (Immunity to Surrogate Model Attacks).: _Suppose \(f(x;\theta)\) is a latent watermarked DNN with non-zero secret weight key \(\delta\), \(D\) is the clean dataset and \(D_{T}\) is the trigger set. For any \(\epsilon>0\), there exists another DNN \(f(x;\theta^{\prime})\):_ 1. \(Pr_{x\in D}[\arg\max f(x;\theta)\neq\arg\max f(x;\theta^{\prime})]\leq\epsilon\)_;_ 2. \(Pr_{x\in D_{T}}[\arg\max f(x;\theta+\delta)=\arg\max f(x;\theta^{\prime}+\delta )]\leq\frac{1}{c}+\epsilon\)_._ ### Immunity to Free-Rider Attacks To the best of our knowledge, existing DNN OV techniques do not offer protection against free-rider attacks. Specifically, a (almost) free-rider can fine-tune (which is much less expensive than training) a pre-trained DNN which does not belong to them to embed their own watermarks and then claim ownership of the resulting DNN. For \(\mathtt{OVLA}\), while we do not directly prohibit embedding watermarks through fine-tuning, the following theorem shows that using fine-tuning to embed a _latent_ watermark is as expensive as (re)training from scratch. Thus, there is no incentive for an attacker to forge their own latent watermarks on a pre-trained model this way. **Theorem 3** (Immunity to Free-Rider Attacks).: _If the secret weight key \(\delta\) is non-sparse and \(||\delta||_{2}\) is large enough, then \(\theta+\delta\) is close to a normal distribution on the whole parameter space, where \(\theta\) is the parameter of a pre-trained DNN \(f(x,\theta)\). Therefore, embedding \(\delta\) into \(f(x,\theta)\) via fine-tuning is as difficult as retraining from scratch._ ## 5 Experiments In this section, we implement OVLA on a set of DNN models and evaluate their performances under backdoor detection, key guessing attacks, and watermark removal via model pruning and fine-tuning. The experiments are designed to answer the following questions: 1. How do the OVLA-watermarked DNNs perform relatively to normally trained DNNs on clean data? 2. How well does OVLA protect the watermarked models against key guessing attacks? 3. Can the OVLA-watermarked DNNs evade backdoor detection methods such as Neural Cleanse? 4. How well does the OVLA-watermarked DNNs resist watermark removal techniques such as model pruning and fine-tuning? We use the following **evaluation metrics**: 1. **AC**: the accuracy of a watermarked DNN on clean test data; 2. **AW**: the accuracy of a watermarked DNN on latent watermark data (the trigger set); 3. **ACU**: the accuracy of a unlocked DNN (after the secret weight key is applied) on clean test data; 4. **AWU**: the accuracy of a unlocked DNN on latent watermark data. ### OVLA on MNIST/CIFAR10/GTSRB We train a OVLA-watermarked DNN on MNIST LeCun (1998)/CIFAR10 Krizhevsky et al. (2009)/GTSRB Stallkamp et al. (2012) separately. For MNIST, we use a three-layer multilayer perceptron; for CIFAR10, we use vgg16_comp Simonyan and Zisserman (2014); for GTSRB, we use a six-layer convolutional neural network O'Shea and Nash (2015). More details about the DNN structure and the training hyperparameters can be found in the Supplemental Material. We then verify each OVLA-watermarked DNN on both clean data and latent watermark data. The results are presented in Table 1. The performance of the OVLA-watermarked DNNs on clean data is very close to (and sometimes even better than) the performance of non-watermarked DNNs. For the watermark data, the unlocked DNNs \(f(x,\theta+\delta)\) achieve \(>\)\(99.93\%\) AWU for all cases. ### Defense against Key Guessing Attacks We train a OVLA-watermarked DNN for each of the datasets MNIST/CIFAR10/GTSRB. We then sample 100 randomly generated weight key from a high dimensional uniform distribution (every entry is drawn from a uniform distribution between 0 and 1) and then perform ownership verification for the OVLA-watermarked DNN unlocked using a random weight key. From Figure 3, we can observe that all the randomly sampled keys fail the ownership verification. ### Defense against Backdoor Detection We use the implementation of Neural Cleanse Wang et al. (2019) in TrojanZoo Pang et al. (2022) to evaluate how well OVLA-watermarked DNNs can evade backdoor detection. The GTSRB dataset is omitted because it is not supported by \begin{table} \begin{tabular}{c c c c c c c c c c c c} \hline \hline & \multicolumn{4}{c}{MNIST} & \multicolumn{4}{c}{CIFAR10} & \multicolumn{4}{c}{GTSRB} \\ \#L & AC & AW & ACU & AWU & AC & AW & ACU & AWU & AC & AW & ACU & AWU \\ \hline 0 & \(98.03\%\) & \(9.82\%\) & - & - & \(78.67\%\) & \(10.88\%\) & - & - & \(91.79\%\) & \(0.25\%\) & - & - \\ 1 & \(97.96\%\) & \(9.85\%\) & \(97.0\%\) & **100.0\%** & \(80.85\%\) & \(10.48\%\) & \(67.63\%\) & \(99.99\%\) & \(90.36\%\) & \(0.43\%\) & \(88.8\%\) & \(99.97\%\) \\ 2 & \(97.87\%\) & \(9.8\%\) & \(97.88\%\) & **100.0\%** & \(89.99\%\) & \(8.95\%\) & \(70.7\%\) & **100.0\%** & \(90.56\%\) & \(6.03\%\) & \(88.15\%\) & \(99.93\%\) \\ 3 & **98.07\%** & \(9.83\%\) & \(97.94\%\) & **100.0\%** & \(78.43\%\) & \(10.06\%\) & \(74.22\%\) & **99.99\%** & \(92.06\%\) & \(0.4\%\) & \(92.16\%\) & \(99.98\%\) \\ 4 & - & - & - & - & **81.63\%** & \(9.97\%\) & \(80.51\%\) & **100.0\%** & **92.67\%** & \(0.54\%\) & \(92.46\%\) & \(99.99\%\) \\ \hline \hline \end{tabular} \end{table} Table 1: The performance of OVLA generated watermark on MNIST/CIFAR10/GTSRB. All models are train with 100 epochs. #L: The layer that secret weight key lies on (L=0 is the performance of a non-watermarked DNN). TrojanZoo. Table 2 shows that the detection results of Neural Cleanse. We can observe that Neural Cleanse is not able to find any trigger with a small \(L_{1}\) norm2 for both OVLA and Clean DNN (DNNs trained normally on only clean data). Thus, OVLA-watermarked DNNs would be treated as Clean DNNs when inspected by backdoor detection methods like Neural Cleanse. Footnote 2: Note that empirically speaking, for any DNN, there almost always exists a universal adversarial perturbation Moosavi-Dezfooli et al. (2017) with a large enough \(L_{1}\) norm. ### Resistance to Model Pruning We train a OVLA-watermarked DNN on MNIST/CIFAR10 and then apply model pruning Cheng et al. (2017) to the OVLA-watermarked DNN. Pruning is applied to the last convolutional layer. We again use TrojanZoo for this evaluation Pang et al. (2022) and omit GTSRB since it is not yet supported by the tool. We report how the performances on clean data and watermarked data change as the ratio of pruning increases. Results for MNIST are included in Supplemental Material. In Figure 4, we can observe that OVLA's performance is similar to that of clean DNN as the network is pruned - almost no accuracy (AC) drop even when 95% of neurons are pruned. On the contrary, for backdoor-based watermarks Adi et al. (2018), accuracy drops to 55% when 95% neurons are pruned. In fact, the OVLA-watermarked DNNs can still pass ownership verification when 97% neurons are pruned. ### Resistance to Fine-Tuning We train a OVLA-watermarked DNN on MNIST/MNIST/CIFAR10 and then fine-tune the trained DNN with \(20\%\) clean data from the training dataset. We then perform ownership verification on the fine-tuned DNN and record how its performance changes during fine-tuning. Results for using secret weight key on the first layer are reported in Table 3. \begin{table} \begin{tabular}{c|c c c c} \hline & \multicolumn{2}{c}{OVLA} & Clean DNN & BadNet Adi et al. (2018) \\ \hline \multirow{3}{*}{MNIST} & ACC & 99.920\% & 99.910\% & **100.000\%** \\ & Norm & 47.635 & 77.725 & **2.177** \\ & NormMD & 1.868 & 0.034 & **-3.438** \\ \hline \multirow{3}{*}{CIFAR10} & ACC & 0.080\% & 0.010\% & **99.710\%** \\ & NormMD & 31.854 & 71.780 & **7.490** \\ \cline{1-1} & NormMD & 0.186 & 1.924 & **-1.357** \\ \hline \end{tabular} \end{table} Table 2: Neural Cleanse Wang et al. (2019) results for OVLA/Clean DNN/BadNet on MNIST/CIFAR10. Clean DNN is a DNN trained using only clean data; BadNet Adi et al. (2018) is used as a backdoor-based dynamic watermarking scheme. ACC: backdoor accuracy on the reverse-engineered trigger. Norm: \(L_{1}\) norm of the reverse-engineered trigger. NormMD: norm deviation of the reverse-engineered trigger (negative NormMD means the norm is less than the median and positive NormMD means the norm is greater than the median). A DNN is considered as a backdoored DNN if the backdoor accuracy is higher than some accuracy threshold (usually set to 90%) and the NormMD is less than some NormMD threshold (usually set to -1). Figure 3: Defense against Key Guessing Attacks on MNIST/CIFAR10/GTSRB. The red dot corresponds to result of using the secret weight key \(\delta\). The blue dots correspond to results produced from using randomly guessed keys. We use \(\epsilon_{1}=\epsilon_{2}=0.05\) as the thresholds for latent watermark verification, i.e. any dot inside the red shaded area would be considered as verified. More result can be found in the Supplemental Material. Same as Section 5.2, we set \(\epsilon=5\%\) as the threshold of watermark verification. Only one fine-tuned DNN (at the 91st epoch for MNIST) failed the watermark verification. ## 6 Conclusion In this paper, we propose OVLA, a novel DNN ownership verification methodology that decouples ownership verification from the DNN's normal operation. Our methodology has strong theoretical guarantees on normal operation performance, and defense against surrogate model attacks and free-rider attacks. In addition, OVLA-watermarked DNNs show strong empirical resistance to backdoor detection, backdoor removal, key guessing-based ambiguity attacks.
2304.08058
One-Class SVM on siamese neural network latent space for Unsupervised Anomaly Detection on brain MRI White Matter Hyperintensities
Anomaly detection remains a challenging task in neuroimaging when little to no supervision is available and when lesions can be very small or with subtle contrast. Patch-based representation learning has shown powerful representation capacities when applied to industrial or medical imaging and outlier detection methods have been applied successfully to these images. In this work, we propose an unsupervised anomaly detection (UAD) method based on a latent space constructed by a siamese patch-based auto-encoder and perform the outlier detection with a One-Class SVM training paradigm tailored to the lesion detection task in multi-modality neuroimaging. We evaluate performances of this model on a public database, the White Matter Hyperintensities (WMH) challenge and show in par performance with the two best performing state-of-the-art methods reported so far.
Nicolas Pinon, Robin Trombetta, Carole Lartizien
2023-04-17T08:19:23Z
http://arxiv.org/abs/2304.08058v1
One-Class SVM on siamese neural network latent space for Unsupervised Anomaly Detection on brain MRI White Matter Hyperintensities ###### Abstract Anomaly detection remains a challenging task in neuroimaging when little to no supervision is available and when lesions can be very small or with subtle contrast. Patch-based representation learning has shown powerful representation capacities when applied to industrial or medical imaging and outlier detection methods have been applied successfully to these images. In this work, we propose an unsupervised anomaly detection (UAD) method based on a latent space constructed by a siamese patch-based auto-encoder and perform the outlier detection with a One-Class SVM training paradigm tailored to the lesion detection task in multi-modality neuroimaging. We evaluate performances of this model on a public database, the White Matter Hyperintensities (WMH) challenge and show in par performance with the two best performing state-of-the-art methods reported so far. A 2023 A 2171-15, 2023 Full Paper - MIDL 2023 A 2023 CC-BY 4.0, N. Pinon, R. Trombetta & C. Lartizien ## 1 Introduction _Unsupervised Anomaly Detection_ (UAD), also referred to as _outlier detection_, has been proposed as an alternative to deep supervised learning for medical image analysis when the studied pathology is either rare or with heterogeneous patterns as well as when getting labels from radiologists is very challenging. This formalism relies on the estimation of the distribution of normal (i.e. non-pathological) data in some representation space associated to some distance metric allowing to quantify the deviation of test samples from this normal model at inference time. Samples highly deviating from the normal distribution are referred to as _outliers_. Different categories of UAD methods have been recently applied to medical image segmentation or detection tasks. The most popular formalism is based on auto-encoders (AE) architectures that are trained on normal images only to perform a "pretext" task consisting in the reconstruction of the input image. During inference, voxel-wise anomaly scores are computed in the image space as the reconstruction errors, _i.e._ the differences between the input test image and the pseudo-normal reconstructed one, assuming that the AE has initially well captured the normal subjects main features and will thus generate large errors for anomalous voxels contained in the test image. Such models have successfully been applied to the _segmentation_ of visible brain anomalies in MRI medical image analysis (Baur et al., 2021). Recent observations, however, outline the limitations of the reconstruction error scores for the detection of very subtle abnormalities (Meissen et al., 2022). Different attempts have been proposed to overcome the reported limitations of these approaches. Pinaya et al proposed an advanced architecture combining a vector quantized auto-encoder (VQ-VAE) with autoregressive transformers acting in the latent representation space to explicitly model the likelihood function of the discrete elements (Pinaya et al., 2022). This was shown to perform well in different neuroimaging applications including the MICCAI WMH challenge that tackles the detection of white matter hyperintensity (WMH) lesions in T1 and FLAIR MRI. However, the sequential nature of auto-regressive models introduces bias, which can be handled with an ensemble of models but at the cost of a much higher computation time at inference. Alaverdyan _et al._ proposed to perform the detection step in a latent space by coupling the representation power of patch-based AE networks to extract relevant and subtle features with the efficiency of a multivariate non parametric discriminative one class support vector machine (OC-SVM) (Alaverdyan et al., 2020). This model was shown to achieve promising results for the detection of subtle (MRI negative) epilepsy lesions in T1 and FLAIR MRI. In this work, we build on the formalism proposed in (Alaverdyan et al., 2020) and propose an original discriminative model that is compared to the state-of-the art generative architecture proposed by (Pinaya et al., 2022) and (Baur et al., 2021). Performance of these models, trained on the same database of normal control exams (Merida et al., 2020), are evaluated on the WMH challenge T1 and FLAIR MRI data to guarantee a fair comparison. ## 2 Proposed UAD method The proposed UAD pipeline is depicted on figure 1. It consists of two main steps, the **representation learning** step which constructs a latent space of the distribution of normal samples based on an auto-encoder trained on patches extracted from a control population. The **outlier detection** step which estimates the support of the normality distribution for each patient based on a one-class support vector machine (OC-SVM) trained on a subset of patches extracted from the patient under consideration. ### Representation learning With the goal of facilitating outlier detection, we first construct a representation space of latent variable \(\mathbf{z}\) that is suitable for this task. Leveraging the architecture proposed in (Alaverdyan et al., 2020), we train a siamese auto-encoder (SAE) to reconstruct 2D patches of the input image, where the patch-based approach is aimed at enriching the latent space with local information at the voxel level. The siamese auto-encoder is composed of two auto-encoders with shared weights, each taking a couple of input patches \((\mathbf{x_{1}},\mathbf{x_{2}})\) from different subjects, but located at the same location in the brain. The patches are drawn from a set of normal (i.e. healthy) images \(\mathcal{X}=\mathcal{X}_{1\leq h\leq N_{\mathrm{hc}}}^{h}=(\mathbf{x}_{i}^{h} )_{1\leq i\leq m,1\leq h\leq N_{\mathrm{hc}}}\) with \(m\) the number of locations and \(N_{\mathrm{hc}}\) the number of healthy controls. The network first encodes the patches \((\mathbf{x_{1}},\mathbf{x_{2}})\) into latent representations \((\mathbf{z_{1}},\mathbf{z_{2}})\) and decodes them into reconstructions \((\mathbf{\hat{x_{1}}},\mathbf{\hat{x_{2}}})\). While training this network has to balance two terms for the loss 1) a cosine similarity term, ensuring that the couple of patches located in the same location in the brain are close when projected in the latent space, thus constructing a meaningful representation space 2) a reconstruction error term between the original couple of patches and their reconstructions ensuring that the encoder does not collapse to a single representation. \[L_{SAE}(\mathbf{x_{1}},\mathbf{x_{2}})=\sum_{t=1}^{2}||\mathbf{x_{t}}-\mathbf{ \hat{x}_{t}}||_{2}^{2}-\alpha\cdot cos(\mathbf{z_{1}},\mathbf{z_{2}})\] The training is done on patches of the input images, with the goal of constructing an encoder that captures fine and subtle information. Patches are extracted from healthy controls only with the assumption that the latent variable \(\mathbf{z}\) extracted from pathological area will appear as out of distribution in the inference stage. At the end of the training, the encoder's weights are frozen and used to extract latent representation \(\mathbf{z}\) from any image patch \(\mathbf{x}\). ### Outlier detection We propose to perform the outlier detection step in the latent space of the auto-encoder by estimating the support of the normal (i.e. healthy) probability distribution. To this end, we Figure 1: Proposed UAD pipeline consisting of 3 steps : 1) representation learning on the whole control database 2) OC-SVM tuning on each patient using a subset of latent representations \(\mathbf{z}\) 3) inference on the whole brain using previously tuned OC-SVM. use a one-class support vector machine (OC-SVM) algorithm (Scholkopf and Smola, 2002) whose goal is to construct a decision function \(f\) that is positive on the estimated normal distribution support and negative outside. Samples \(\mathbf{z}_{i}\) are projected to a high dimensional space with a mapping \(\boldsymbol{\phi(\cdot)}\) associated with a kernel \(k\) such that \(k(\mathbf{z}_{i},\mathbf{z}_{j})=\boldsymbol{\phi}(\mathbf{z}_{i})\cdot \boldsymbol{\phi}(\mathbf{z}_{j})\). The kernel is chosen to be the radial basis function kernel, i.e. \(k(\mathbf{z}_{i},\mathbf{z}_{j})=\exp(-\gamma||\mathbf{z}_{i}-\mathbf{z}_{j}|| _{2}^{2})\). This guarantees that the problem is linear in this redescription space so that the decision function is a hyperplane of equation \(\boldsymbol{w}\cdot\boldsymbol{\phi}(\mathbf{z})-\rho=0\). An additional parameter \(\nu\) adjusts the upper bound on the fraction of permitted training errors, allowing to account for the presence of "non-normal" samples in the training samples. Based on this \(\nu\)-property and assuming that the lesion area represents a negligible fraction of patient images, we propose to build one normality model per patient \(p\), by randomly sampling \(n\) voxel locations throughout the \(m\) brain voxel locations with \(n\ll m\). Patches centered on these \(n\) locations are fed through the SAE network to constitute a subset \(\mathcal{Z}^{p}=(\mathbf{z}_{i}^{p})_{1\leq i\leq n}\) that serves to estimate the decision function \(f_{p}\) of parameters \(\mathbf{w}_{p}\) and \(\rho_{p}\) for patient \(p\). Once the decision function is computed, we can infer an outlier score for each of the \(m\) voxels of the patient image, by extracting the patch centered on this voxel, feeding it then to the SAE to derive its latent representation \(\mathbf{z}\), which is in turn inputted to the decision function \(f_{p}\) to estimate its distance to the normal distribution support. This allows deriving an anomaly score map for the whole brain of patient \(p\). Note that, unlike in (Alaverdyan et al., 2020), this whole outlier detection step is done only at inference stage on each individual patient image and does not need any training on the normal training set \(\mathcal{X}\). We hypothesize that computing the normal distribution at patient level will enable detection performance gain as it allows to be independent of the registration quality in this step and also can capture some of the particularity of the patient normal distribution (e.g. large occipital lobe volume, brain shrinkage, etc.). ### Post-processing of the anomaly score maps We found in early experiments that the method was generating a high number of false positives in the cerebrospinal fluid (CSF), whether near the border of the cortex or in the ventricles, as we believe these regions are highly affected by the quality of the registration. To mitigate this effect we use the FMRIB's Automated Segmentation Tool (FAST) by (Zhang et al., 2001) to segment the grey and white matter, allowing us to exclude the CSF from the anomaly maps. Details of this post-processing can be found in appendix E. ## 3 Experiments ### Database and splitting Two different databases are used in this study. **The control dataset** consists of a series of 75 paired T1 weighted and FLAIR MRI scans acquired on healthy volunteers on a 1.5T Siemens Sonata scanner and mCT PET scanner (Siemens Healthcare, Erlangen, Germany). This database was approved by our institutional review board with approval numbers X and X (blinded for review). It serves to learn the normality distribution of the UAD models. **The WMH Segmentation Challenge training1 dataset** contains 60 paired T1 weighted and FLAIR images each associated to the corresponding 3D lesion mask image. These data were acquired on 3 scanners of different vendors in 3 different hospitals in the Netherlands and Singapore, namely 20 exams acquired on a 3 T Philips Achieva of UMC Utrecht, 20 exams exams acquired on a 3 T Siemens TrioTim of NUHS Singapore and 20 exams acquired on a 3 T GE Signa HDxt of VU Amsterdam. All 3D images of the 2 databases were co-registered to the MNI space based on SPM12 processing tools, thus leading to 3D volumes of size 157x189x136 with 1mm\({}^{3}\) isotropic voxel size. ### Hyper-parameters of the UAD method The encoder was composed of 4 convolutionnal blocks with the following characteristics : kernel size of \((5,5)\), \((3,3)\), \((3,3)\) and \((3,3)\), strides, respectively, of \((1,1)\), \((1,1)\), \((3,3)\) and \((1,1)\), number of filters, respectively, of 3, 4, 12 and 16, no padding and GeLu activation. Each block was followed by a batch normalization block. The decoder was the symmetric counterpart of the encoder, except the last block which did not use batch normalization and used sigmoid activation function. The input of the encoder consisted of patches of each of the 2 modalities combined as channels. The siamese network was trained with 18 750 000 patches of size 15\(\times\)15\(\times\)2 (250 000 patches per subject). We used Adam optimizer (Kingma and Ba, 2015) for 30 epochs, with default hyperparameters, best model selection based on validation loss and training batch size of 1000. For the OC-SVM, \(n\) was set to 500 (sampling ratio \(\frac{n}{m}\simeq 0.02\%\)). We used \(\nu=0.03\) and the hyperparameter \(\gamma\) was set such that \(\frac{1}{\gamma}\) was equal to the product of variance and dimension of the \(\mathbf{z}_{i}\). ### Comparison to other detection methods We compare our UAD pipeline to what is, to our knowledge, the best performing unsupervised models for anomaly detection and segmentation on the WMH challenge dataset (Baur et al., 2021; Pinaya et al., 2022). **VQVAE and Transformer** Pinaya et al proposed to combine the discrete latent representation of a Vector Quantized Variational Auto-Encoder (VQ-VAE) with a Transformer (Vaswani et al., 2017) to perform anomaly detection by restoration of lesions on MRI images. The VQ-VAE (van den Oord et al., 2017) is trained to reconstruct whole 2D transverse slices and learn a meaningful discrete latent representation vector of the data. In a second step, the Transformer serves as an autoregressive model to learn the sequences of indices of the quantized latent vectors on the "normal" images only. For each element of the sequence, if the probability of the encoding vector predicted by the autoregressive model is lower than an arbitrary value, this vector is resampled. The new restored sequence then feeds the decoder of the VQ-VAE to get the final image where it is assumed that the anomalies have been "healed". The error map between this output image and the original one is interpreted as an anomaly score to segment the lesions in the brain. An additional step upsamples the mask of the elements that have been resampled by the Transformer and uses it as a mask to filter the residuals maps. We adapt this approach to our context of experimentation, using the control dataset \(\mathcal{X}\) to train the models. The slices were padded to a size of 192x192 and we used the same architectures for the VQ-VAE, resulting in a latent space of size 24x24x256. The same data augmentation and learning parameters are used and the model was trained for 500 epochs with a batch size of 128. During our experimentations, we found that using Performer (Choromanski et al., 2020) was less efficient and accurate than the regular Transformer, so we chose the latter. It is composed of 8 layers, embedding size of 256 and was train trained for 200 epochs with a batch size of 32, learning rate of 1e-4. The threshold for resampling encoding vectors was set to 0.005. For computational limitations, the improvement induced by the multiplication of pathways in latent space for the Transformer was not evaluated, we only report performance achieved when using the basic raster order. Auto-encoderThe performances are also compared to the auto-encoder of (Baur et al., 2021), which has the particularity to include two skip connections in the middle of the network. Anomaly maps are obtained after applying a 5x5x5 median filter on the error maps between the input and the associated reconstruction. The same data augmentation - small random translation, contrast and intensity shifts - is applied on the padded slices and the model is trained during 500 epochs with Adam optimizer with default hyperparameters and a batch size of 128. Multiple OC-SVMTo assess the benefits of our patient-specific OC-SVM approach, we use the latent representation obtained with a SAE on the control dataset to tune one OC-SVM per voxel as in (Alaverdyan et al., 2020). ### Evaluation methodology For each method presented, we obtain an anomaly score map, whether it is the score of the decision function of OC-SVM, the restoration error for the VQ-VAE + transformer or the reconstruction error for the AE. We evaluate classical pixel-level metrics : the area under the ROC curve (**AU ROC**), as well as the area under the precision recall curve (**AU PRC**), which intrinsically takes into account large class imbalance and does not use the false positive rate. We also compute the AU ROC corresponding to false positives rates lower than 30% (**AUC ROC 30**) as in (Bergmann et al., 2021). Anomaly maps outlining 30% or more of FP voxels are indeed degenerated and of no use in the medical imaging context where the anomalies take only a small portion of the total volume (0.35% in the WMH database). The small lesional fraction also justifies the use of the \(\nu\)-property used in section 2.2. As in (Bergmann et al., 2021), we also investigate the area under the Per Region Overlap curve (**AU PRO**), which reports variations of the average PRO as a function of the FP rate, where the PRO is defined as the sensitivity of each individual lesion, and the average PRO is the average values over all lesions in the patient. The PRO acts as a true positive rate (sensitivity) normalized per lesion size, meaning a correctly detected small lesion will count as much as a large one. This metric is particularly relevant in the context of anomaly detection in medical imaging, where we want to detect every lesions regardless of the size, unlike AU ROC which is biased towards detecting large lesions. Finally, as a mean of comparison to (Pinaya et al., 2022), we also investigate the best achievable **Dice**, which is simply the maximum value of the Dice metric obtained with the optimal threshold applied on the score maps. Non parametric Kruskal-Wallis analysis of variance followed by Dunn's tests for multiple comparisons were performed to compare the different metrics. ## 4 Results Visual assessment of the anomaly maps achieved by the UAD models is showcased on Figure 2 and Appendix C. Table 1 reports performance achieved by our proposed SAE+OC-SVM method with and without accounting for detections in the CSF (see section 2.3) compared to the methods presented in 3.3. Reported metrics correspond to the mean values and standard deviations computed over the pooled 60 exams of the WMH training database. On overall, performance of the SAE+ OC-SVM are better than all three other methods for all the metrics. As explained in section 2.3, we emphasize that the PRO metric, widely used in the computer vision domain, is well-suited for the evaluation of outlier detection tasks. The good PRO performance achieved with our model is thus a positive indicator of its capacity to detect subtle brain anomalies. Results of Table 1 show the benefits of tuning one OC-SVM per patient instead of one per voxel, as it significantly improves the performances compared to (Alaverdyan et al., 2020). They also indicate that both our method and the VQ-VAE+Transformer model outperform the simple AE model proposed by (Baur et al., 2021). The two last columns of \begin{table} \begin{tabular}{|c|c|c|c|c|c|} \hline \multirow{2}{*}{3 hospitals} & \multicolumn{2}{c|}{VQ-VAE} & \multicolumn{2}{c|}{SAE} & \multicolumn{1}{c|}{SAE} & \multicolumn{1}{c|}{SAE} \\ & \multicolumn{1}{c|}{\(+\) Transformer} & \multicolumn{1}{c|}{AE} & \multicolumn{1}{c|}{\(+\) multiple} & \multicolumn{1}{c|}{\(+\) OC-SVM} & \multicolumn{1}{c|}{\(+\) OC-SVM} \\ & \multicolumn{1}{c|}{(Pinaya)} & \multicolumn{1}{c|}{(Baur)} & \multicolumn{1}{c|}{OC-SVM} & \multicolumn{1}{c|}{(Ours)} & \multicolumn{1}{c|}{+ CSF seg} \\ & \multicolumn{1}{c|}{(Pinaya)} & \multicolumn{1}{c|}{(Baur)} & \multicolumn{1}{c|}{(Alaverdyan)} & \multicolumn{1}{c|}{(Ours)} & \multicolumn{1}{c|}{(Ours)} \\ \hline AU ROC & 0.69 \(\pm\) 0.13 & 0.53 \(\pm\) 0.09 & 0.52 \(\pm\) 0.19 & **0.80**\(\pm\) 0.09 & **0.81**\(\pm\) 0.10 \\ \hline AU ROC 30 & 0.40 \(\pm\) 0.20 & 0.20 \(\pm\) 0.12 & 0.19 \(\pm\) 0.16 & **0.48**\(\pm\) 0.20 & **0.59**\(\pm\) 0.17 \\ \hline AU PRC & 0.065 \(\pm\) 0.079 & 0.028 \(\pm\) 0.030 & 0.023 \(\pm\) 0.031 & **0.084**\(\pm\) 0.099 & **0.165**\(\pm\) 0.168 \\ \hline AU PRO & 0.55 \(\pm\) 0.10 & 0.50 \(\pm\) 0.08 & 0.43 \(\pm\) 0.17 & 0.71 \(\pm\) 0.11 & **0.80**\(\pm\) 0.07 \\ \hline AU PRO 30 & 0.19 \(\pm\) 0.13 & 0.15 \(\pm\) 0.07 & 0.09 \(\pm\) 0.13 & 0.33 \(\pm\) 0.18 & **0.48**\(\pm\) 0.13 \\ \hline \(\lceil\) Dice \(\rceil\) & 0.11 \(\pm\) 0.10 & 0.06 \(\pm\) 0.05 & 0.05 \(\pm\) 0.05 & **0.14**\(\pm\) 0.13 & **0.22**\(\pm\) 0.17 \\ \hline \end{tabular} \end{table} Table 1: Mean metric on every patient from the 3 different hospitals for each method. In bold are shown the best model and those for which the statistical difference with the best model for Dunn’s test is not significative (p-value \(\geq\) 0.01). Figure 2: Showcase of the different methods studied on 3 examples from the 3 hospitals Table 1 underline the impact of the proposed post-processing on the SAE+OC-SVM model (on Figure 2, 5th column, we see that our method is likely to generate false detections in the CSF, especially in the ventricles). Reported performance are on overall higher when applying the CSF mask, this is mainly due to a significant reduction of the false positive rate that is not counterbalanced by the paired slight decrease in sensitivity due to the imperfect segmentation of the ventricles encompassing some true lesions located on its border. However, most of the statistical tests did not conclude that the observed differences were significant. To further investigate the comparative performance of the 3 UAD models, we report results achieved by each of the 3 hospitals (Amsterdam, Singapore and Utrecht) in Tables 2, 3, 4, of Appendix A. This study is, as far as we know, the first to report such a detailed analysis by institution. It shows that all the models see their performance decrease on the Utrecht dataset. This could be due to a greater difference between the images in this dataset and those of the control dataset, especially for FLAIR images, highlighting the need to have more heterogeneous controls during the representation learning step to build more robust models. Computation of the global mean lesional volume of each center, however, indicates a dataset shift with mean values of 13495, 26123 and 29296 mm\({}^{3}\) for the Amsterdam, Singapore and Utrecht centers, respectively. One possible explanation might thus be that our method does not perform well when data are characterized by a low lesional load. This requires further investigation. ## 5 Discussion and Conclusion The reported DICE-score and AUPRC in (Pinaya et al., 2022) (Dice = 0.269, AUPRC = 0.158) and (Baur et al., 2021) (Dice=0.45 and AUPRC = 0.37) are much higher than the values reported in this study. However, they do not compare since they were achieved based on UAD models trained on FLAIR data only while we accounted for both T1 and FLAIR (concatenated as 2 input channels) in this study. The significant performance gap is also likely to be explained by methodological differences among the studies. As an example, training of the VQ-VAE + transformer models in (Pinaya et al., 2022) is based on a selection of more than 15 000 FLAIR "normal" volumes from the UK Biobank database, some of them containing WMH lesions. This training dataset, constituted of the 4 central slices of each volume, is thus highly different from ours based on 75 3D volumes of healthy controls (including all transverse slices) who do not contain any WMH lesion. Training of the Pinaya and Baur UAD models in this study included data augmentation focused on intensity scaling and contrast adjustment, unlike ours. Such a strategy may help accounting for the distribution shifts observed among images acquired on the 4 different scanners as reported in Figure 3. As stated in the Introduction, our main purpose was to provide a fair comparison between the different UAD models by training and testing these models on the same datasets as well as using the same evaluation metrics and strategy. This study demonstrated very promising performance of the proposed SAE+OC-SVM model in par with state-of-the art UAD models. Further work will focus on implementing domain adaptation strategies to account for data distribution shift among the different clinical centers, as well as evaluating performance achieved with the FLAIR data only. ## Acknowledgments This work was granted access to the HPC resources of IDRIS under the allocation 2022-AD011012813R1 made by GENCI. It was partially funded by French program "Investissement d'Avenir" run by the Agence Nationale pour la Recherche (ANR-11-INBS-0006).
2303.01965
A Lifted Bregman Formulation for the Inversion of Deep Neural Networks
We propose a novel framework for the regularised inversion of deep neural networks. The framework is based on the authors' recent work on training feed-forward neural networks without the differentiation of activation functions. The framework lifts the parameter space into a higher dimensional space by introducing auxiliary variables, and penalises these variables with tailored Bregman distances. We propose a family of variational regularisations based on these Bregman distances, present theoretical results and support their practical application with numerical examples. In particular, we present the first convergence result (to the best of our knowledge) for the regularised inversion of a single-layer perceptron that only assumes that the solution of the inverse problem is in the range of the regularisation operator, and that shows that the regularised inverse provably converges to the true inverse if measurement errors converge to zero.
Xiaoyu Wang, Martin Benning
2023-03-01T20:30:22Z
http://arxiv.org/abs/2303.01965v1
# A Lifted Bregman Formulation for the Inversion of Deep Neural Networks ###### Abstract We propose a novel framework for the regularised inversion of deep neural networks. The framework is based on the authors' recent work on training feed-forward neural networks without the differentiation of activation functions. The framework lifts the parameter space into a higher dimensional space by introducing auxiliary variables, and penalises these variables with tailored Bregman distances. We propose a family of variational regularisations based on these Bregman distances, present theoretical results and support their practical application with numerical examples. In particular, we present the first convergence result (to the best of our knowledge) for the regularised inversion of a single-layer perceptron that only assumes that the solution of the inverse problem is in the range of the regularisation operator, and that shows that the regularised inverse provably converges to the true inverse if measurement errors converge to zero. Inverse problems, regularisation theory, lifted network training, Bregman distance, perceptron, multi-layer perceptron, variational regularisation, total variation regularisation Article Xiaoyu Wang, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning, Martin Benning modelling that include (but are not limited to) (variational) Autoencoders (Kingma and Welling, 2013), Normalising Flows (Rezende and Mohamed, 2015; Dinh et al., 2015), Cycle-Consistent Generative Adversarial Networks (Zhu et al., 2017), and Probabilistic Diffusion Models (Sohl-Dickstein et al., 2015; Ho et al., 2020). While several approaches for the inversion of neural networks have been proposed especially in the context of generative modelling (see for example (Behrmann et al., 2019, 2021) in the context of normalising flows, (Xia et al., 2022) in the context of generative adversarial networks and (Gal et al., 2022) in the context of probabilistic diffusion models), an important aspect, which is often overlooked, is that invertible operations alone are not automatically stable with respect to small variations in the data. For example, computing the solution of the heat equation after a fixed termination time is stable with respect to variations in the initial condition, but estimating the initial condition from the terminal condition of the heat equation is not stable with respect to perturbations in the terminal condition. This issue cannot be resolved without approximation of the inverse with a family of continuous operators, also known as _regularisation_. The research field of _Inverse and Ill-posed Problems_ and its branch _Regularisation Theory_ focus strongly on the stable approximation of ill-posed and ill-conditioned inverses via _regularisations_(Engl et al., 1996) and so-called _variational regularisations_(Scherzer et al., 2009; Benning and Burger, 2018) that are a special class of (nonlinear) regularisations. The optimisation model proposed in (Mahendran and Vedaldi, 2015) can be considered as a variational regularisation method with total variation regularisation; however, the work in (Mahendran and Vedaldi, 2015) is purely empirical, and to the best of our knowledge no works exist that rigorously prove that the proposed approach is a variational regularisation. In this work, we propose a novel regularisation framework based on lifting with tailored Bregman distances and prove that the proposed framework is a convergent variational regularisation for the inverse problem of estimating the inputs from single-layer perceptrons or the inverse problem of estimating hidden variables in a multi-layer perceptron sequentially. While there has been substantial work in previous years that focuses on utilising neural networks as nonlinear operators in variational regularisation methods (Lunz et al., 2018; Arridge et al., 2019; Schwab et al., 2019; Li et al., 2020; Mukherjee et al., 2021), this is the first work that provides theoretical guarantees for the stable, model-based inversion of neural networks to the best of our knowledge. Our contributions are three-fold. 1) We propose a novel framework for the regularised inversion of multi-layer perceptrons, respectively feed-forward neural networks, that is based on the lifted Bregman framework recently proposed by the authors in Wang and Benning (2022). 2) We show that for the single-layer perceptron case, the proposed variational regularisation approach is a provably convergent regularisation under very mild assumptions. To our knowledge, this is the first time that an inversion method has been proposed that does not just allow to perform inversion empirically, but for which we can prove that the proposed method is a convergent regularisation method without overly restrictive assumptions such as differentiability of the activation function and the presence of a tangential cone condition. 3) We propose a proximal first-order optimisation strategy to solve the proposed variational regularisation method and present several numerical examples that support the effectiveness of the proposed model-based regularisation approach. The paper is structured as follows. In Section 2 we introduce the lifted Bregman formulation for the model-based inversion of feed-forward neural networks. In Section 3 we prove that for the single-layer perceptron case the proposed model is a convergent variational regularisation method and provide general error estimates as well as error estimates for a concrete example of a perceptron with ReLU activation function. In Section 4 we discuss how to implement the proposed variational regularisation computationally for both the single-layer and multi-layer perceptron setting with a generalisation of the primal-dual hybrid gradient method and coordinate descent. Subsequently, we present numerical results that demonstrate empirically that the proposed approach is a model-based regularisation in Section 5, before we conclude this work with a brief section on conclusions and outlook in Section 6. ## 2 Model-based inversion of Feed-forward Networks Suppose we are given an \(L\)-layer feed-forward neural network \(\mathcal{N}:\mathbb{R}^{n}\times\mathcal{P}\rightarrow\mathbb{R}^{m}\) of the form \[\mathcal{N}(x,\mathbf{\Theta})=\sigma_{L}(f(\sigma_{L-1}(f(\ldots\sigma_{1}(f(x, \Theta_{1}))\ldots)),\Theta_{L})), \tag{1}\] for input data \(x\in\mathbb{R}^{n}\) and **pre-trained** parameters \(\mathbf{\Theta}\in\mathcal{P}\). Here, \(\{\sigma_{l}\}_{l=1}^{L}\) denotes the collection of nonlinear activation functions and \(f\) denotes a generic function parametrised by parameters \(\{\Theta_{l}\}_{l=1}^{L}\). For ease of notation, we use \(\mathbf{\Theta}\) to refer to all parameters \(\{\Theta_{l}\}_{l=1}^{L}\). For a given network output \(y\in\mathbb{R}^{m}\), our goal is to solve the inverse problem \[\mathcal{N}(x,\mathbf{\Theta})=y\] for the unknown input \(x\in\mathbb{R}^{n}\). We propose to approximate the inverse of this nonlinear, potentially ill-posed inverse problem via the minimisation of a lifted Bregman formulation of the form \[\begin{pmatrix}x^{\alpha}\\ x_{1}^{\alpha}\\ \vdots\\ x_{L-1}^{\alpha}\end{pmatrix}\in\operatorname*{arg\,min}_{x,x_{1},\ldots,x_{L -1}}\left\{\sum_{l=1}^{L}B_{\Psi_{l}}(x_{l},f(x_{l-1},\Theta_{l}))+\alpha R(x )\right\}\,, \tag{2}\] where we assume \(x_{0}=x\) and \(x_{L}=y^{\delta}\) for simplicity of notation. The data \(y^{\delta}\) is a perturbed version of \(y\), for which we assume \(B_{\Psi_{L}}(y^{\delta},f(x_{L-1}^{\dagger},\Theta_{L}))\leq\delta^{2}\), for some constant \(\delta\geq 0\) and \(y=\sigma_{L}(f(x_{L-1}^{\dagger},\Theta_{L}))\). The functions \(B_{\Psi_{l}}\) for \(l=1,\ldots,L\) are defined as \[B_{\Psi_{l}}(x,z)=\frac{1}{2}\|x\|^{2}+\Psi_{l}(x)+\left(\frac{1}{2}\|\cdot\| ^{2}+\Psi_{l}\right)^{*}(z)-\left\langle x,z\right\rangle, \tag{3}\] for a proper, convex and lower semi-continuous function \(\Psi_{l}\colon\mathbb{R}^{n_{l}}\rightarrow\mathbb{R}\cup\{\infty\}\). The notation \(\left(\frac{1}{2}\|\cdot\|^{2}+\Psi_{l}\right)^{*}\) refers to the convex or Fenchel conjugate of \(\frac{1}{2}\|\cdot\|^{2}+\Psi_{l}\), i.e. \(\left(\frac{1}{2}\|\cdot\|^{2}+\Psi_{l}\right)^{*}(z)=\sup_{y}\langle z,y \rangle-\frac{1}{2}\|y\|^{2}-\Psi_{l}(y)\). Last but not least, the function \(R:\mathbb{R}^{n}\rightarrow\mathbb{R}\cup\{\infty\}\) is a proper, convex, and lower semi-continuous function that enables us to incorporate a-priori information into the inversion process. The impact of this is controlled by the parameter \(\alpha>0\). Please note that the functions \(B_{\Psi_{l}}\) have some useful properties and are directly connected to the chosen activation functions \(\{\sigma_{l}\}_{l=1}^{L}\). Following (Wang and Benning, 2022), we observe \[B_{\Psi_{l}}(x,z)\geq\frac{1}{2}\|\sigma_{l}(z)-x\|^{2}\,,\] where \(\sigma_{l}:\mathbb{R}^{n_{l}}\to\mathbb{R}^{n_{l}}\) is the proximal map with respect to \(\Psi_{l}\), i.e. \[\sigma_{l}(z)=\operatorname*{arg\,min}_{y\in\mathbb{R}^{n_{l}}}\left\{\frac{1}{ 2}\|y-z\|^{2}+\Psi_{l}(y)\right\}\,,\] for all \(l\in\{1,\ldots,L\}\). This means that we will solely focus on feed-forward neural networks with **nonlinear activation functions that are proximal maps**. Another useful property is that the functions \(B_{\Psi_{l}}\) are continuously differentiable with respect to their second argument. If we define \(F_{x}^{l}(z):=B_{\Psi_{l}}(x,z)\), we observe \[\nabla F_{x}^{l}(z)=\sigma_{l}(z)-x\,. \tag{4}\] Please note that the family of objective functions \(B_{\Psi_{l}}\) satisfies several other interesting properties; we refer the interested reader to (Wang and Benning, 2022, Theorem 10). For the remainder of this work, we assume that the parametrised functions \(f\) are affine-linear in the first argument, with parameters \(\Theta_{l}\). A concrete example is the affine-linear transformation \(f(x,\Theta_{l})=W_{l}x+b_{l}\), for a (weight) matrix \(W_{l}\in\mathbb{R}^{n_{l}\times n_{l-1}}\), a (bias) vector \(b_{l}\in\mathbb{R}^{n_{l}}\) and the collection of parameters \(\Theta_{l}=(W_{l},b_{l})\). In the next section we show that (2) is a variational regularisation method for \(L=1\) and prove a convergence rate with which the solution of (2) converges towards the true input of a perceptron when \(\delta\) converges to zero. ## 3 Convergence analysis and error estimates In this section we show that the proposed model (2) is a convergent variational regularisation for the specific choice \(L=1\) and the assumption \(f(x,\Theta)=Wx+b\) for \(\Theta=(W,b)\), which reduces (2) to a variational regularisation model for the perceptron case studied in Wang and Benning (2020). In contrast to Wang and Benning (2020) we are not interested in estimating the perceptron parameters \(W\) and \(b\) but assume that these are fixed, and that we study the regularisation operator \[\mathcal{R}_{\alpha}\colon\,\text{dom}(\Psi)\rightrightarrows\mathbb{R}^{n} \,,\qquad\mathcal{R}_{\alpha}\colon\,y^{\delta}\rightrightarrows x_{\alpha} \in\operatorname*{arg\,min}_{x\in\mathbb{R}^{n}}\left\{B_{\Psi}\left(y^{ \delta},Wx+b\right)+\alpha R(x)\right\}\,, \tag{5}\] where \(\text{dom}(\Psi)\) is defined as \(\text{dom}(\Psi):=\{y\in\mathbb{R}^{m}\,|\,\Psi(y)<\infty\}\). We first want to establish under which assumptions (5) is well-defined for all \(y^{\delta}\). ### Well-definedness For simplicity, we focus on the finite-dimensional setting with network inputs in \(\mathbb{R}^{n}\) and outputs in \(\text{dom}(\Psi)\). However, the following analysis also extends to more general Banach space settings with additional assumptions on the operator \(W\), see for instance (Benning and Burger, 2018, Section 5.1). Following (Benning and Burger, 2018), we assume that \(R\) is non-negative and the polar of a proper function, i.e. \(R=H^{*}\) for a proper function \(H:\mathbb{R}^{n}\to\mathbb{R}\cup\{\infty\}\). Note that this automatically implies convexity of \(R\). Moreover, we assume that \(\Psi\) is a proper, non-negative and convex function that is continuous on \(\text{dom}(\Psi)\), which implies that \(B_{\Psi}\) is proper, non-negative, convex in its second argument and continuous in its first argument for every \(y^{\delta}\in\text{dom}(\Psi)\). Then, for every \(g\in\text{dom}(\Psi)\) there exists \(x\) with \[B_{\Psi}(g,Wx+b)+\alpha R(x)<\infty\,.\] Last but not least, we assume that \(R\) and \(\Psi\) are chosen such that for each \(g\in\text{dom}(\Psi)\) and \(\alpha>0\) we have \[\|x\|\leq c(a,b,\|g\|),\qquad\text{if}\quad B_{\Psi}(g,Wx+b)\leq a\quad\text{ and}\quad\alpha R(x)\leq d\,,\] for constants \(a,d\) and a constant \(c\) that depends monotonically non-decreasing on all arguments. With these assumptions, we can then verify the following lemma. **Theorem 1**.: _Let the assumptions outlined in the previous paragraph be satisfied._ 1. _Then, for every_ \(y\in\left\{g\in\text{dom}(\Psi)\,\,\Big{|}\arg\min_{x,\in\mathbb{R}^{n},R(x)< \infty}B_{\Psi}(g,Wx+b)\neq\emptyset\right\}\) _the selection operator_ \[\mathcal{S}(y)=\operatorname*{arg\,min}_{x\in\mathbb{R}^{n}}\left\{R(x)\,\, \bigg{|}\,x\in\operatorname*{arg\,min}_{\tilde{x}\in\mathbb{R}^{n}}B_{\Psi}(y,W\tilde{x}+b)\right\}\] _is well-defined._ 2. _The regularisation operator_ \(\mathcal{R}_{\alpha}\) _as defined in (_2_) is well-defined in the sense that for every_ \(y\in\text{dom}(\Psi)\) _there exists_ \(x_{\alpha}\in\mathbb{R}^{n}\) _with_ \(x_{\alpha}\in\mathcal{R}_{\alpha}(y)\)_. Moreover, the set_ \(\mathcal{R}_{\alpha}(y)\) _is a convex set._ 3. _For every sequence_ \(y_{n}\to y\in\text{dom}(\Psi)\) _there exists a subsequence_ \(x_{n_{k}}\in\mathcal{R}_{\alpha}(y_{n_{k}})\) _converging to an element_ \(x^{*}\in\mathcal{R}_{\alpha}(y)\)_._ Proof.: The results follow directly from (Banning and Burger, 2018), Lemma 5.5, Theorem 5.6 and Theorem 5.7. The latter statement originally only implies convergence in the weak-star topology; however, since we are in a finite-dimensional Hilbert space, this automatically implies strong convergence here. ### Error estimates Having established that (2) is a regularisation operator, we now want to prove that it is also a convergent regularisation operator in the sense of the estimate \[D_{R}(x^{\dagger},x^{\alpha})\leq C\delta\,, \tag{6}\] such that \[\lim_{\delta\to 0}\sup\left\{D_{R}(x^{\dagger},x^{\alpha})\,\,\Big{|}\,x^{ \alpha}\in\mathcal{R}_{\alpha}(y^{\delta}),\,y^{\delta}\in\text{dom}(\Psi),\, B_{\Psi}(y^{\delta},y)\leq\delta^{2}\right\}=0\,.\] Here, the term \(D_{R}\) denotes the (generalised) Bregman distance (or divergence) (cf. (Bregman, 1967; Kiwiel, 1997)) with respect to \(R\), i.e. \[D_{R}(x,\tilde{x})=R(x)-R(\tilde{x})-\langle\tilde{q},x-\tilde{x}\rangle\,,\] for two arguments \(x,\tilde{x}\in\text{dom}(R)\) and a subgradient \(\tilde{q}\in\partial R(\tilde{x})=\{q\in\mathbb{R}^{n}\,|\,R(x)\geq R(\tilde {x})+\langle q,x-\tilde{x}\rangle,\,\forall\,x\in\text{dom}(R)\}\). The vector \(x^{\alpha}\) is a solution of (2) with data \(y^{\delta}\) for which we assume \(B_{\Psi}(y^{\delta},y)\leq\delta^{2}\), and \(C\geq 0\) is a constant. The vector \(x^{\dagger}\) is an element of the selection operator as specified in Lemma 1.1, i.e. \(x^{\dagger}\in\mathcal{S}(y)\) for \(y\in\text{dom}(\Psi)\). Note that \(x^{\dagger}\in\mathcal{S}(y)\) is equivalent to \(x^{\dagger}\) being a \(R\)-minimising vector amongst all vectors that satisfy \(0=W^{*}\left(\sigma(Wx^{\dagger}+b)-y\right)\), where \(\sigma\) denotes the proximal map with respect to \(\Psi\). This is due to the fact that \(x^{\dagger}\in\arg\min_{\tilde{x}\in\mathbb{R}^{n}}B_{\Psi}(y,W\tilde{x}+b)\) is equivalent to \(0=\nabla B_{\Psi}(y,Wx^{\dagger}+b)=W^{*}\left(\sigma(Wx^{\dagger}+b)-y\right)\). Assuming that \(\sigma(Wx^{\dagger}+b)-y\) does not lie in the nullspace of \(W^{*}\), this further implies \(y=\sigma(Wx^{\dagger}+b)\). In order to be able to derive error estimates of the form (6), we restrict ourselves to solutions \(x^{\dagger}\) that are in the range of \(\mathcal{R}_{\alpha}\). This means that there exists \(y^{\dagger}\) such that \(x^{\dagger}\in\mathcal{R}_{\alpha}(y^{\dagger})\). Considering the optimality condition of (2) for \(y^{\dagger}\), this implies \[W^{*}\left(\frac{y^{\dagger}-\sigma(Wx^{\dagger}+b)}{\alpha}\right)\in\partial R (x^{\dagger})\,,\] which for \(v^{\dagger}:=(y^{\dagger}-\sigma(Wx^{\dagger}+b))/\alpha=(y^{\dagger}-y)/\alpha\) is equivalent to the existence of a source condition element \(v^{\dagger}\) that satisfies the source condition (cf. Engl et al. (1996); Benning and Burger (2018)) \[W^{*}v^{\dagger}\in\partial R(x^{\dagger})\,,\] (SC) In the following, we verify that the symmetric Bregman distance with respect to \(R\) between a solution of the regularisation operator and the solution of the inverse problem is converging to zero if the error in the data is converging to zero. The symmetric Bregman distance or Jeffreys distance between two vectors \(x\) and \(\tilde{x}\) simply is the sum of two Bregman distances with interchanged arguments, i.e. \[D_{R}^{\text{symm}}(x,\tilde{x}):=D_{R}(x,\tilde{x})+D_{R}(\tilde{x},x)=\langle x -\tilde{x},q-\tilde{q}\rangle\,,\] for \(q\in\partial R(x)\) and \(\tilde{q}\in\partial R(\tilde{x})\); hence, an error estimate in the symmetric Bregman distance also implies an error estimate in the classical Bregman distance. Before we begin our analysis, we recall the concept of the _Jensen-Shannon divergence_(Lin, 1991), which for general proper, convex and lower semi-continuous functions \(F:\mathbb{R}^{n}\to\mathbb{R}\cup\{\infty\}\) generalises to so-called _Burbea-Rao divergences_(Burbea and Rao, 1982a,b; Nielsen and Boltz, 2011) and are defined as follows. [Burbea-Rao divergence] Suppose \(F:\mathbb{R}^{n}\to\mathbb{R}\cup\{\infty\}\) is a proper, convex and lower semi-continuous function. The corresponding Burbea-Rao divergence is defined as \[J_{F}(x,\tilde{x}):=\frac{1}{2}\left(F(x)+F(\tilde{x})-2F\left(\frac{x+\tilde {x}}{2}\right)\right)\,, \tag{7}\] for all \(x,\tilde{x}\in\text{dom}(F)\). Another important concept that we need in order to establish error estimates is that of Fenchel conjugates (cf. Beck (2017)). [Fenchel conjugate] The Fenchel (or convex) conjugate \(F^{*}:\mathbb{R}^{n}\to\mathbb{R}\cup\{-\infty,\infty\}\) of a function \(F:\mathbb{R}^{n}\to\mathbb{R}\cup\{-\infty,+\infty\}\) is defined as \[F^{*}(w)\colon=\sup_{x\in\mathbb{R}^{n}}\langle x,w\rangle-F(x)\,.\] The Fenchel conjugate that is of particular interest to us is the conjugate of the function \(B_{\Psi}(y,z)\) with respect to the second argument, which we characterise with the following lemma. **Lemma 1**.: _The Fenchel conjugate of \(F_{y}(z):=B_{\Psi}(y,z)\) with respect to the second argument \(z\) reads_ \[F_{y}^{*}(w)=\left(\frac{1}{2}\|\cdot\|^{2}+\Psi\right)(y+w)-\left(\frac{1}{2} \|\cdot\|^{2}+\Psi\right)(y)\,.\] Proof.: From the definition of the Fenchel conjugate we observe \[F_{y}^{*}(w) =\sup_{z\in\mathbb{R}^{m}}\left\langle z,w\right\rangle-F_{y}(z)\] \[=\sup_{z\in\mathbb{R}^{m}}\left\langle z,w\right\rangle-\left( \frac{1}{2}\|\cdot\|^{2}+\Psi\right)(y)-\left(\frac{1}{2}\|\cdot\|^{2}+\Psi \right)^{*}(z)+\left\langle y,z\right\rangle\] \[=-\left(\frac{1}{2}\|\cdot\|^{2}+\Psi\right)(y)+\sup_{z\in \mathbb{R}^{m}}\left\langle z,w+y\right\rangle-\left(\frac{1}{2}\|\cdot\|^{2 }+\Psi\right)^{*}(z)\] \[=-\left(\frac{1}{2}\|\cdot\|^{2}+\Psi\right)(y)+\left(\frac{1}{2 }\|\cdot\|^{2}+\Psi\right)(w+y)\,,\] which concludes the proof. Having defined the Burbea-Rao divergence and having established the Fenchel conjugate of \(B_{\Psi}(y,z)\) with respect to the second argument \(z\) for fixed \(y\), we can now present and verify our main result that is motivated by (Benning and Burger, 2011). **Theorem 2**.: _Suppose \(R\) and \(\Psi\) satisfy the assumptions outlined in Section 3.1. Then, for data \(y^{\delta}\) and \(x^{\dagger}\) that satisfy \(B_{\Psi}(y^{\delta},Wx^{\dagger}+b)\leq\delta^{2}\) with \(\delta\geq 0\), a solution \(x^{\alpha}\in\mathcal{R}_{\alpha}(y^{\delta})\) of the variational regularisation problem (2), and a solution \(x^{\dagger}\) of the perceptron problem \(y=\sigma(Wx^{\dagger}+b)\) that satisfies \(x^{\dagger}\in\mathcal{S}(y)\) and (SC), we observe the error estimate_ \[\begin{split}(1-c)B_{\Psi}(y^{\delta},Wx_{\alpha}+b)+\alpha D_{R} ^{\text{symm}}(x_{\alpha},x^{\dagger})&\leq(1+c)\delta^{2}+ \frac{\alpha^{2}}{c}\|v^{\dagger}\|^{2}\\ &\quad+2cJ_{\Psi}\left(y^{\delta}+\frac{\alpha}{c}v^{\dagger},y^ {\delta}-\frac{\alpha}{c}v^{\dagger}\right)\end{split}, \tag{8}\] _for a constant \(c\in(0,1]\)._ Proof.: Every solution \(x_{\alpha}\) that satisfies \(x_{\alpha}\in\mathcal{R}_{\alpha}(y^{\delta})\) can equivalently be characterised by the optimality condition \[W^{*}\left(\sigma(Wx_{\alpha}+b)-y^{\delta}\right)+\alpha p_{\alpha}=0\,,\] for any subgradient \(p_{\alpha}\in\partial R(x_{\alpha})\). Subtracting \(p^{\dagger}\in\partial R(x^{\dagger})\) from both sides of the equation and taking a dual product with \(x_{\alpha}-x^{\dagger}\) then yields \[\left\langle\sigma(Wx_{\alpha}+b)-y^{\delta},Wx_{\alpha}-Wx^{\dagger}\right\rangle +\alpha D_{R}^{\text{symm}}(x_{\alpha},x^{\dagger})=-\alpha\langle p^{\dagger}, x_{\alpha}-x^{\dagger}\rangle\,. \tag{9}\] We easily verify \[D_{B_{\Psi}(y^{\delta},W\cdot+b)}(x^{\dagger},x_{\alpha})=B_{\Psi}(y^{\delta},Wx^ {\dagger}+b)-B_{\Psi}(y^{\delta},Wx_{\alpha}+b)-\left\langle\sigma(Wx_{\alpha}+b )-y^{\delta},Wx^{\dagger}-Wx_{\alpha}\right\rangle;\] hence, we can replace \(\left\langle\sigma(Wx_{\alpha}+b)-y^{\delta},Wx_{\alpha}-Wx^{\dagger}\right\rangle\) with \(D_{B_{\Psi}(y^{\delta},W\cdot+b)}(x^{\dagger},x_{\alpha})+B_{\Psi}(y^{\delta}, Wx_{\alpha}+b)-B_{\Psi}(y^{\delta},Wx^{\dagger}+b)\) in (9) to obtain \[D_{B_{\Psi}(y^{\delta},W\cdot+b)}(x^{\dagger},x_{\alpha})+B_{\Psi}(y^{\delta}, Wx_{\alpha}+b)+\alpha D_{R}^{\text{symm}}(x_{\alpha},x^{\dagger})=B_{\Psi}(y^{ \delta},Wx^{\dagger}+b)-\alpha\langle p^{\dagger},x_{\alpha}-x^{\dagger} \rangle\,.\] We know \(0\leq D_{B_{\Psi}(y^{\delta},W\cdot+b)}(x^{\dagger},x_{\alpha})\) due to the convexity of \(B_{\Psi}(y^{\delta},W\cdot+b)\), and we also know that (SC) enables us to choose \(p^{\dagger}=W^{*}v^{\dagger}\). Hence, we can estimate \[B_{\Psi}(y^{\delta},Wx_{\alpha}+b)+\alpha D_{R}^{\text{symm}}(x_{\alpha},x^{ \dagger})\leq B_{\Psi}(y^{\delta},Wx^{\dagger}+b)-\alpha\langle v^{\dagger},Wx _{\alpha}-Wx^{\dagger}\rangle\,.\] Next, we introduce the constant \(c\in(0,1]\) to split the loss functions \(B_{\Psi}(y^{\delta},Wx_{\alpha}+b)\) and \(B_{\Psi}(y^{\delta},Wx^{\dagger}+b)\) into \((1-c)B_{\Psi}(y^{\delta},Wx_{\alpha}+b)+cB_{\Psi}(y^{\delta},Wx_{\alpha}+b)\) and \((1+c)B_{\Psi}(y^{\delta},Wx^{\dagger}+b)-cB_{\Psi}(y^{\delta},Wx^{\dagger}+b)\), respectively. This means we estimate \[(1-c)B_{\Psi}(y^{\delta},Wx_{\alpha}+b)+\alpha D_{R}^{\text{symm }}(x_{\alpha},x^{\dagger}) \leq(1+c)B_{\Psi}(y^{\delta},Wx^{\dagger}+b)\] \[\quad+\left\langle\alpha v^{\dagger},Wx^{\dagger}+b\right\rangle -cB_{\Psi}(y^{\delta},Wx^{\dagger}+b)\] \[\quad-\left\langle\alpha v^{\dagger},Wx_{\alpha}+b\right\rangle -cB_{\Psi}(y^{\delta},Wx_{\alpha}+b)\,.\] Next, we make use of Lemma 1 to estimate \[\left\langle\alpha v^{\dagger},Wx^{\dagger}+b\right\rangle-cB_{\Psi}(y^{\delta },Wx^{\dagger}+b)\leq c\left(\left(\frac{1}{2}\|\cdot\|^{2}+\Psi\right)\left( y^{\delta}+\frac{\alpha}{c}v^{\dagger}\right)-\left(\frac{1}{2}\|\cdot\|^{2}+ \Psi\right)\left(y^{\delta}\right)\right)\,,\] and \[-\langle\alpha v^{\dagger},Wx_{\alpha}+b\rangle-cB_{\Psi}(y^{\delta},Wx_{ \alpha}+b)\leq c\left(\left(\frac{1}{2}\|\cdot\|^{2}+\Psi\right)\left(y^{ \delta}-\frac{\alpha}{c}v^{\dagger}\right)-\left(\frac{1}{2}\|\cdot\|^{2}+ \Psi\right)\left(y^{\delta}\right)\right)\,.\] Adding both estimates together yields \[\left\langle\alpha v^{\dagger},Wx^{\dagger}+b\right\rangle-cB_{ \Psi}(y^{\delta},Wx^{\dagger}+b)-\left\langle\alpha v^{\dagger},Wx_{\alpha}+b \right\rangle-cB_{\Psi}(y^{\delta},Wx_{\alpha}+b)\,,\] \[\leq\frac{\alpha^{2}}{c}\|v^{\dagger}\|^{2}+c\left(\Psi\left(y^{ \delta}+\frac{\alpha}{c}v^{\dagger}\right)+\Psi\left(y^{\delta}-\frac{\alpha} {c}v^{\dagger}\right)-2\Psi(y^{\delta})\right)\,,\] \[=\frac{\alpha^{2}}{c}\|v^{\dagger}\|^{2}+2cJ_{\Psi}\left(y^{\delta }+\frac{\alpha}{c}v^{\dagger},y^{\delta}-\frac{\alpha}{c}v^{\dagger}\right)\,,\] which together with the error bound \(B_{\Psi}(y^{\delta},Wx^{\dagger}+b)\leq\delta^{2}\) concludes the proof. **Remark 1**.: _We want to emphasise that for continuous \(\Psi\) and \(c>0\) we automatically observe_ \[\lim_{\alpha\to 0}J_{\Psi}\left(y^{\delta}+\frac{\alpha}{c}v^{\dagger},y^{\delta }-\frac{\alpha}{c}v^{\dagger}\right)=0\,,\] in which case the important question from an error estimate point-of-view is if the term converges quicker to zero than \(\alpha\), as we would need to guarantee \(\lim_{\alpha\to 0}J_{\Psi}\left(y^{\delta}+\frac{\alpha}{c}v^{\dagger},y^{\delta}- \frac{\alpha}{c}v^{\dagger}\right)/\alpha=0\) in order to guarantee that the symmetric Bregman distance in (8) converges to zero for \(\alpha\to 0\)._ **Example 1** (ReLU perceptron).: _Let us consider a concrete example to demonstrate that (5) is a convergent regularisation with respect to the symmetric Bregman distance of \(R\). We know that for \(\sigma(z)=\text{prox}_{\Psi}(z)=\max(0,z)\) to hold true we have to choose \(\Psi(z)=\begin{cases}0&z\in[0,\infty)^{m}\\ \infty&\text{else}\end{cases}\). This means that for \(B_{\Psi}(y^{\delta},z)\) to be well-defined for any \(z\) we require \(y_{i}^{\delta}\geq 0\) for all \(i\in\{1,\ldots,m\}\). In order for the Burbea-Rao divergence to be well-defined, we further require_ \[-\frac{c}{\alpha}y_{i}^{\delta}\leq v_{i}^{\dagger}\leq\frac{c}{\alpha}y_{i}^ {\delta}\,,\] _for all \(i\in\{1,\ldots,m\}\), or \(\|v^{\dagger}\|_{\infty}\leq(c\|y^{\delta}\|_{\infty}/\alpha)\) in more compact notation. If \(\|v^{\dagger}\|_{\infty}\leq(c\|y^{\delta}\|_{\infty}/\alpha)\) is guaranteed, we observe \(J_{\Psi}\left(y^{\delta}+\frac{\alpha}{c}v^{\dagger},y^{\delta}-\frac{\alpha} {c}v^{\dagger}\right)=0\). Hence, we can simplify the estimate (8) to_ \[\frac{1-c}{\alpha}B_{\Psi}(y^{\delta},Wx_{\alpha}+b)+D_{R}^{\text{ symm}}(x_{\alpha},x^{\dagger})\leq\frac{1+c}{\alpha}\delta^{2}+\frac{\alpha}{c}\|v^{ \dagger}\|^{2}\,,\] _where we have also divided by \(\alpha\) on both sides of the inequality. If we choose \(\alpha(\delta)=\sqrt{c(1+c)}\delta/\|v^{\dagger}\|\), we obtain the estimate_ \[\frac{(1-c)\|v^{\dagger}\|}{\delta\sqrt{c(1+c)}}B_{\Psi}(y^{\delta},Wx_{\alpha (\delta)}+b)+D_{R}^{\text{symm}}(x_{\alpha(\delta)},x^{\dagger})\leq 2 \sqrt{\frac{1+c}{c}}\|v^{\dagger}\|\delta\,,\] _as long as we can ensure_ \[\left\|\frac{v^{\dagger}}{\|v^{\dagger}\|}\right\|_{\infty}\leq\sqrt{\frac{c} {1+c}}\left\|\frac{y^{\delta}}{\delta}\right\|_{\infty}\,.\] _Together with \(D_{R}^{\text{symm}}(x_{\alpha(\delta)},x^{\dagger})\geq D_{R}(x^{\dagger},x_{ \alpha(\delta)})\) we have established an estimate of the form (6), with constant \(C=2\sqrt{\frac{1+c}{c}}\|v^{\dagger}\|\). Hence, we have verified that the variational regularisation method (2) is not only a regularisation method but even a convergent regularisation method in this specific example._ We want to briefly comment on the extension of the convergence analysis to the general case \(L>1\) with the following remark. **Remark 2**.: _The presented convergence analysis easily extends to a sequential, layer-wise inversion approach. Suppose we have \(L\) layers and begin with the final layer, then we can formulate the variational problem_ \[x_{L-1}^{\alpha}\in\operatorname*{arg\,min}_{x_{L-1}}\left\{B_{\Psi_{L}}(y^{ \delta},W_{L}x_{L-1}+b_{L})+\alpha_{L-1}\Psi_{L-1}(x_{L-1})\right\}\,,\] _which is also of the form of (5), but where \(R\) has been replaced with \(\Psi_{L-1}\). Alternatively, one can also replace \(\Psi_{L-1}\) with another function \(R_{L-1}\) if good prior knowledge for the auxiliary variable \(x_{L-1}\) exists._ Once we have estimated \(x_{L-1}^{\alpha}\), we can recursively estimate \[x_{l-1}^{\alpha}\in\operatorname*{arg\,min}_{x_{l-1}}\left\{B_{\Psi_{l}}(x_{l}^{ \alpha},W_{l}x_{l-1}+b_{l})+\alpha_{l-1}\Psi_{l-1}(x_{l-1})\right\}\,,\] for \(l=L-1,\ldots,2\) and subsequently compute \(x_{\alpha}\) as a solution of (2) but with data \(x_{1}^{\alpha}\) instead of \(y^{\delta}\). The advantage of such a sequential approach is that every individual regularisation problem is convex and the previously presented theorems and guarantees still apply. The disadvantage is that for this approach to work in theory, we require bounds for every auxiliary variable of the form \(B_{\Psi_{l}}(x_{l}^{\alpha},W_{l}x_{l-1}^{\alpha}+b_{l})\leq\delta_{l}^{2}\), which is a rather unrealistic assumption. Moreover, it is also not realistic to assume that good prior knowledge for the auxiliary variables exist. Please note that showing that the simultaneous approach (2) is a (convergent) variational regularisation is beyond the scope of this work as it is harder and potentially requires additional assumptions for the following reason. The overall objective function in (2) is no longer guaranteed to be convex with respect to all variables simultaneously, which means that we cannot simply carry over the analysis of the single-layer to the multi-layer perceptron case. This concludes the theoretical analysis of the perceptron inversion model. In the following section we focus on how to implement (5) and its more general counterpart (2). ## 4 Implementation In this section, we describe how to computationally implement the proposed variational regularisation for both the single-layer and the multi-layer perceptron setting. More specifically, we show that the proposed variational regularisation can be efficiently solved via a generalised primal-dual hybrid gradient method and a coordinate descent approach. ### Inverting perceptrons To begin with, we first consider the example of inverting a (single-layer) perceptron. For \(L=1\), Problem (2) reduces to (5), which for a composite regularisation function \(R\circ K\) reads \[x^{\alpha}\in\operatorname*{arg\,min}_{x}\left\{B_{\Psi}\left(y^{\delta},f(x, \Theta)\right)+\alpha R(Kx)\right\}\,. \tag{10}\] Here \(K\) is a matrix and \(\alpha R(Kx)\) denotes the regularisation function acting on the argument \(x\). The above Problem (10) can be reformulated to the saddle-point problem \[\min_{x}\max_{z}B_{\Psi}\left(y^{\delta},f(x,\Theta)\right)+\left\langle z,Kx \right\rangle-\alpha R^{*}(z)\,, \tag{11}\] where \(R^{*}\) denotes the convex conjugate of \(R\). Computationally, we can then solve the saddle-point problem with a generalised primal-dual hybrid gradient (PDHG) method (Zhu and Chan, 2008; Pock et al., 2009; Esser et al., 2010; Chambolle and Pock, 2011, 2016; Benning and Riis, 2021): \[x^{k+1} =x^{k}-\tau_{x}\left(\left(\text{prox}_{\Psi}\left(f(x^{k},\Theta )\right)-y^{\delta}\right)\mathcal{J}_{f}^{x}(x^{k},\Theta)+\alpha K^{\top}z^ {k}\right) \tag{12a}\] \[z^{k+1} =\text{prox}_{\tau_{z}R^{*}}\left(z^{k}+\tau_{z}\alpha K\left(2x ^{k+1}-x^{k}\right)\right)\,. \tag{12b}\] where we alternate between a descent step in the \(x\) variable and an ascent step in the dual variable \(z\). Since (10) is a convex minimisation problem, (12) is guaranteed to converge globally for arbitrary starting point, given that \(\tau_{x}\) and \(\tau_{z}\) are chosen such that \(\tau_{x}\tau_{z}<1/\|K\|\). In this work, we will focus on the discrete total variation \(\|\nabla x\|_{p,1}\), (Rudin et al., 1992; Chambolle and Lions, 1997), as our regularisation function \(R(Kx)\), but other choices are certainly possible. If we consider a two-dimensional scalar-valued image \(x\in\mathbb{R}^{H\times W}\), we can define a finite forward difference discretisation of the gradient operator \(\nabla:\mathbb{R}^{H\times W}\to\mathbb{R}^{H\times W\times 2}\) as \[(\nabla x)_{i,j,1}=\begin{cases}x_{i+1,j}-x_{i,j}\;\text{ if }1\leq i<H,\\ 0\;\text{ else,}\end{cases},\quad\quad(\nabla x)_{i,j,2}=\begin{cases}x_{i,j+ 1}-x_{i,j}\;\text{ if }1\leq j<W,\\ 0\;\text{ else.}\end{cases}.\] The discrete total variation is defined as the \(\ell_{1}\) norm of the \(p\)-norm of the pixel-wise image gradients, i.e. \[\|\nabla x\|_{p,1}=\sum_{i=1}^{H}\sum_{j=1}^{W}\left|\left(\nabla x\right)_{i,j}\right|_{p}=\sum_{i=1}^{H}\sum_{j=1}^{W}\left((\nabla x)_{i,j,1}^{p}+( \nabla x)_{i,j,2}^{p}\right)^{1/p}\,.\] For our numerical results we consider the isotropic total variation and consequently choose \(p=2\). Hence for a perceptron with affine-linear transformation \(f(x,\Theta)=Wx+b\), and with \(\sigma=\text{prox}_{\Psi}\) denoting the activation function, the PDHG approach (12) of solving the perceptron inversion problem (5) can be summarised as \[x^{k+1} =x^{k}-\tau_{x}\left(W^{\top}\left(\sigma(Wx^{k}+b)-y\right)- \alpha\text{div}z^{k}\right)\,, \tag{13a}\] \[z^{k+1} =\text{prox}_{\tau_{z}\|\cdot\|_{2,1}^{*}}\left(z^{k}+\tau_{z} \left(2\alpha\nabla x^{k+1}-\alpha\nabla x^{k}\right)\right)\,. \tag{13b}\] Please note that we define the discrete approximation of the divergence div such that it satisfies \(\text{div}=-\nabla^{\top}\) in order to be the negative transpose of the discretised finite difference approximation of the gradient in analogy to the continuous case, which is why the sign in (13a) is flipped in comparison to (12a). The proximal map with regards to the convex conjugate of \(\|\cdot\|_{2,1}^{*}\) is simply the argument itself if the maximum of the Euclidean vector-norm per pixel is bounded by one or the projection onto this unit ball. ### Inverting multi-layer perceptrons We now discuss the implementation of the inversion of multi-layer perceptrons with \(L\) layers as described in (2). Note that in this case in order to minimise for \(x\), we also need to optimise with respect to the auxiliary variables \(x_{1},\ldots,x_{L-1}\). For the minimisation of (2) we consider an alternating minimisation approach, also known as _coordinate descent_(Beck and Tetruashvili, 2013; Wright, 2015; Wright and Recht, 2022). In this approach we minimise the objective with respect to one variable at a time. In particular, we focus on a semi-explicit coordinate descent algorithm, where we linearise with respect to the smooth functions of the overall objective function. This breaks down the overall minimisation problem into \(L\) sub-problems, where for \(x_{0}\) and each \(x_{l}\) variable for \(l\in\{1,\ldots,L-1\}\), we have individual minimisation problems of the following form: \[x_{0}^{k+1} = \tag{14a}\] \[x_{l}^{k+1} \tag{14b}\] Note that one advantage for adopting this approach is that we exploit that the overall objective function is convex in each individual variable when all other variables are kept fixed. In the following, we will discuss different strategies to computationally solve each sub-problem. When optimising with respect to the input variable \(x_{0}\), the structure of sub-problem (14a) is identical to the perceptron inversion problem that we have discussed in Section 4.1. Hence, we can approximate \(x_{0}^{k+1}\) with (11), but now with respect to \(x_{1}^{k}\) instead of \(y^{\delta}\), which yields the iteration \[x_{0}^{k+1} =x_{0}^{k}-\tau_{x_{0}}\left(\left(\text{prox}_{\Psi}\left(f(x_{0} ^{k},\Theta_{1})\right)-x_{1}^{k}\right)\mathcal{J}_{f}^{x}(x_{0}^{k},\Theta_{ 1})+\alpha K^{\top}z^{k}\right)\,, \tag{15a}\] \[z^{k+1} =\text{prox}_{\tau_{z}R^{*}}\left(z^{k}+\tau_{z}\alpha K\left(2x ^{k+1}-x^{k}\right)\right)\,. \tag{15b}\] For each auxiliary variable \(x_{l}\) with \(l\in\{1,\ldots,L-1\}\), the sub-problem associated with (14b) amounts to solving a proximal gradient step with suitable step-size \(\tau_{x_{l}}\), which we can rewrite to \[x_{l}^{k+1}=\text{prox}_{\frac{\tau_{x_{l}}}{1+\tau_{x_{l}}}\Psi _{l}}\left(\frac{1}{1+\tau_{x_{l}}}\left(x_{l}^{k}-\tau_{x_{l}}\left(\left( \text{prox}_{\Psi_{l}}\left(f(x_{l}^{k},\Theta_{l+1})\right)-x_{l+1}^{k}\right) \mathcal{J}_{f}^{x}(x_{l}^{k},\Theta_{l+1})\right.\right.\right. \tag{16}\] \[\left.\left.\hskip 14.226378pt-f(x_{l-1}^{k+1},\Theta_{l}) \right)\right)\] This concludes the discussion on the implementation of the regularised single-layer and multi-layer perceptron inversion. In the next section, we present some numerical results to demonstrate the effectiveness of the proposed approaches empirically. ## 5 Numerical Results In this section, we present numerical results for the perceptron inversion problem implemented with the PDHG algorithm as outlined in (13), and for the multi-layer perceptron inversion problem implemented with the coordinate descent approach as described in (15) and (16). All results have been computed using PyTorch 3.7 on an Intel Xeon CPU E5-2630 v4. ### The Perceptron We present results for two experiments: the first one is the perceptron inversion of the image of a circle from the noisy output of the perceptron, where we compare the Landweber regularisation and the total-variation-based variational regularisation (5). For the second experiment, we perform perceptron inversion for samples from the MNIST dataset and compare them with the performance of linear and nonlinear decoders. **Circle** We begin with the toy example of recovering the image of a circle from noisy measurements of a ReLU perceptron. To prepare the experiment, we generate a circle image \(x^{\dagger}\in\mathbb{R}^{64\times 64}\), as shown in Figure 1. We construct a perceptron with ReLU activation function using random weights and biases where \(W\in\mathbb{R}^{512\times 4096},b\in\mathbb{R}^{512\times 1}\). The weights operates on the column-vector representation of x, where \(x\in\mathbb{R}^{4096\times 1}\). The noise-free data is generated via the forward operation of the model, i.e. \(y=\sigma(Wx^{\dagger}+b)\). We generate noisy data \(y^{\delta}\) by adding Gaussian noise with mean 0 and standard deviation \(0.005\). Note that we clip all the negative values of \(y^{\delta}\) to ensure \(y^{\delta}\in\text{dom}(\Psi)\). A first attempt to solve this ill-posed perceptron inversion problem is via Landweber regularisation (Landweber, 1951). In Figure 2 we see the reconstructed image obtained with Landweber regularisation in combination with early stopping following Morozov's discrepancy principle Morozov (2012); Engl et al. (1996). Even though the Landweber regularised reconstruction matches the data up to the discrepancy value \(\|\sigma(Wx^{K}+b)-y^{\delta}\|\), the recovered image does not resemble the image \(x^{\dagger}\). We will discuss shortly the reason for this visually poor inversion. In comparison, we see a regularised inversion via the total variation regularisation approach following (13) in Figure 3. The regularisation parameter for this reconstruction is chosen as \(\alpha=1.5\times 10^{-2}\). Both \(x_{0}\) and \(z\) are initialised with zero vectors. The stepsize-parameters are chosen as \(\tau_{x}=1.99/\|W\|_{2}^{2}\) and \(\tau_{z}=1/(8\alpha)\), see (Chambolle, 2004). We stop the iterations when changes in \(x_{0}\) and \(z\) in norm are less than a threshold of \(10^{-5}\) or when we reach the maximum number of iterations, which we set to \(10000\). As shown in Figure 3, the TV-regularisation approach is capable of finding a (visually) more meaningful solution. To explain why the Landweber iteration performs worse compared to the total variation regularisation for this specific example, we compare the \(\ell_{2}\) norms of each two solutions and the groundtruth image \(x^{\dagger}\). The \(\ell_{2}\) norm of the Landweber solution in Figure 2 measures \(6.58\) while the TV-regularised solution as in Figure 3 and the groundtruth image \(x^{\dagger}\) measure \(25.69\) and \(28.07\) respectively. This is not surprising, as the Landweber iteration is known to converge to a minimal Euclidean norm solution if the noise level converges to zero. On the other hand, when we compare the TV semi-norm of each solution, the groundtruth image in measures \(128.0\), while the Landweber solution in Figure 2 and TV-regularised solution in Figure 3 measure \(707.02\) and \(114.93\) respectively, suggesting that the TV-semi-norm is a more suitable regularisation function for the inversion of cartoon-like images such as \(x^{\dagger}\). **MNIST** In this second example, we perform perceptron inversion on the MNIST dataset (LeCun et al., 1998). In particular, we consider the following experimental setup. We first train an autoencoder \(\mathcal{A}(x)=\mathcal{D}(\mathcal{E}(x,\mathbf{\Theta}_{\mathcal{E}}), \mathbf{\Theta}_{\mathcal{D}})\), where \(\mathcal{D}(\cdot,\mathbf{\Theta}_{\mathcal{D}})\) and \(\mathcal{E}(\cdot,\mathbf{\Theta}_{\mathcal{E}})\) denotes the decoder and the encoder, parametrised by parameters \(\mathbf{\Theta}_{\mathcal{D}}\) and \(\mathbf{\Theta}_{\mathcal{E}}\) respectively. We pre-train the autoencoder \(\mathcal{A}\), compute the code \(\mathcal{E}(x,\mathbf{\Theta}_{\mathcal{E}})\) and assign it to the noise-free data variable \(y\), and solve the inverse problem for the input \(x\) from the perturbed code \(y^{\delta}\) \[\mathcal{E}(x,\mathbf{\Theta}_{\mathcal{E}})=y^{\delta}\.\] To be more precise, we first train a two-layer fully connected autoencoder \(y=W_{2}(\sigma(W_{1}x+b_{1}))+b_{2}\) using the vanilla stochastic gradient method (SGM) by minimising the mean squared error (MSE) on the MNIST training dataset. We set the code dimension to 100 and use ReLU as the activation function. Hence \(\mathbf{\Theta}_{\mathcal{E}}=(W_{1},b_{1})\) where \(W_{1}\in\mathbb{R}^{784\times 100}\) and \(b_{1}\in\mathbb{R}^{100\times 1}\). All MNIST images are centred as a means of pre-processing. Algorithmically, we follow (13) to computationally solve (10). The stepsize-parameters are chosen at \(\tau_{x}=1.99/\|W_{1}\|_{2}^{2}\) and \(\tau_{z}=1/(8\alpha)\). We choose the regularisation parameter \(\alpha\) in the range \([10^{-4},10^{-2}]\) and set to \(5\times 10^{-3}\) for all sample images from the training set, and set to \(\alpha=5\times 10^{-2}\) for all sample images from the validation set. These choices work well with regards to the visual quality of the inverted images. In Figure 4 and Figure 5, we show visualisations of five sample images from the training set, and from the validation set respectively. In comparison, we have also visualised the decoder output. As can be seen, using the code that contains the same compressed information, the inverted images show more clearly Figure 4: Groundtruth input images from the MNIST training dataset, together with the MNIST validation dataset, together with the corresponding autoencoder output images and inverted input images of the perceptron defined edges and better visual quality than the decoded outputs. This is to be expected as we compare a nonlinear regularised inversion method with a linear decoder. ### Multi-layer perceptrons In this section, we present numerical results for inverting multi-layer perceptrons. In particular, we consider feedforward neural networks with convolutional layers (CNN), where in the network architecture two-dimensional convolution operations are used to represent the linear operations in the affine-linear functions \(f(x,\Theta)\). Similar to the experimental design described in Section 5.1, we consider a multi-layer neural network inversion problem where we infer input image \(x\) from a noise perturbed code \(y^{\delta}\). More specifically, we first train a six-layer convolutional autoencoder on the MNIST training dataset via stochastic gradient method to minimise the MSE. The encoder \(\mathcal{E}(x,\mathbf{\Theta}_{\mathcal{E}})\) consists of two convolutional layers, both with \(4\times 4\) convolutions with stride \(2\), each followed by the application of a ReLU activation function. As image spatial dimension reduce by half, we double the number of feature channels from 8 to 16. We use a fully-connected layer with weights \(W_{3}\in\mathbb{R}^{300\times 784}\) and bias \(b_{3}\in\mathbb{R}^{300\times 1}\) to generate the code. The decoder network first expands the code with an affine-linear transformation with weights \(W_{4}\in\mathbb{R}^{784\times 300}\) and bias \(b_{4}\in\mathbb{R}^{784\times 1}\). This is followed by two layers of transpose convolutionals with kernel size \(4\times 4\), where each is followed by a ReLU activation function. The number of feature channels halves each time as we double the spatial dimension. Figure 6: Inverted input images of the CNN from the MNIST training dataset, together with from the MNIST validation dataset, together well-trained autoencoder output images and with well-trained autoencoder output images and groudtruth input images Following the implementation details outlined in Section 4.2, we iteratively compute the update steps (15) and (16). For the PDHG method, we choose the stepsize-parameters as \(\tau_{x}=1.99/\|W_{1}\|_{2}^{2}\) and \(\tau_{z}=1/(8\alpha)\). The initial values \(x_{0}\) and \(z\) are both zero. The update steps stop either after reaching the maximum iterations of \(1500\) or when the improvements on \(x_{0}\) and \(z\) are less than \(10^{-5}\) in norm. For the coordinate descent algorithm, the stepsize-parameters are set to \(\tau_{x_{l}}=1.99/\|W_{l+1}\|_{2}^{2}\) for each layer. In Figure 6 and Figure 7, we visualise the inverted images, the decoder output images, along with the groundtruth images, from the training dataset and validation dataset respectively. For each image, \(\alpha\) is chosen in the range \([10^{-4},10^{-2}]\) and set at \(9\times 10^{-3}\) for both training sample images and validation sample images for best visual inversion quality. In Figure 8 we further compare how total variation regularisation and decoder respond to different levels of data noise. The noisy data is produced by adding Gaussian noise to perturb the code of each image. We start with zero mean Gaussian noise with standard deviation 0.33 and gradually reduce the noise level, this translates to decreasing \(\delta^{2}\) from 6.80 down to 0.00. Please note that for each noise level the regularisation factor \(\alpha\) is manually selected in the range \([10^{-4},10^{-2}]\) for the best PSNR value. As we can see, for the noise level with standard deviation \(0.33\) where \(\delta^{2}\) is at 6.80, the decoder is only capable of producing a blurry distorted output, while the inverted image shows the structure of the digit more clearly. When we decrease the noise level down to \(0.00\), the inverted image becomes more clean-cut while the decoded image is still less sharply defined. Figure 9 plots the PSNR value of the decoded and inverted image against decreasing noise level. We want to emphasise that it would be more rigorous to compute and compare \(D_{R}^{\text{symm}}(x_{\alpha(\delta)},x^{\dagger})\) as suggested in the error estimate bound in (8), but empirically the PSNR value does also support the notion of a convergent regularisation. ## 6 Conclusions & Outlook We have introduced a novel variational regularisation framework based on a lifted Bregman formulation for the stable inversion of feed-forward neural networks (also known as multi-layer perceptrons). We have proven that the proposed framework is a convergent regularisation for the single-layer perceptron case under the mild assumption that the inverse problem solution has to be in the range of the regularisation operator. We have derived a general error estimate as well as a specific error estimate for the case that the activation function is the ReLU activation function. We have also addressed the extension of the theory to Figure 8: Visualisation of the comparison between inverted image and decoded image against various levels of noise. **Top:** Decoded output image from the trained convolutional autoencoder. **Bottom:** Inverted input image from the CNN with total variation regularisation. the multi-layer perceptron case, which can be carried out sequentially, albeit under unrealistic assumptions. We have discussed implementation strategies to solve the proposed scheme computationally, and presented numerical results for the regularised inversion of the image of a circle and piecewise constant images of hand-written digits from single- and multi-layer perceptron outputs with total variation regularisation. Despite all the positive achievements presented in this work, the proposed framework also has some limitations. The framework is currently restricted to feed-forward architectures with affine-linear transformations and proximal activation functions. While it is straight-forward to extend the framework to other architectures such as ResNets (He et al., 2016) or U-Nets (Ronneberger et al., 2015), it is not straight-forward to include nonlinear operations that cannot be expressed as proximal maps of convex functions, such as max-pooling. However, for many examples there exist remedies, such as using average pooling instead of max-pooling in the previous example. An open question is how a convergence theory without restrictive, unrealistic assumptions can be established for the multi-layer case. One issue is the non-convexity of the proposed formulation. A remedy could be the use of different architectures that lead to lifted Bregman formulations that are jointly convex in all auxiliary variables. And last but not least, one would also like to consider other forms of regularisation, such as iterative regularisation, data-driven regularisations (Kabri et al., 2022), or even combinations of both (Aspri et al., 2020). However, a convergence analysis for such approaches is currently an open problem. ## Conflict of Interest Statement The authors declare that the research was conducted in the absence of any commercial or financial relationships that could be construed as a potential conflict of interest. Figure 9: Comparison of PSNR values of total variation-based reconstruction and decoder output per noise level. Each curve reports the change of PSNR value over gradually decreasing levels of Gaussian noise, with \(\delta^{2}\) ranging from 0.00 to 6.80. ## Author Contributions XW has programmed and contributed all numerical results as well as Section 4 and Section 5. MB has contributed the introduction (Section 1) as well as the theoretical results (Section 3). Both authors have contributed equally to Section 2 and Section 6. ## Acknowledgments The authors acknowledge support from the Cantab Capital Institute for the Mathematics of Information, the Cambridge Centre for Analysis (CCA) and the Alan Turing Institute (ATI). ## Data Availability Statement The programming code for this study can be found in the University of Cambridge data repository at 10.17863/CAM.94404.
2310.09554
Neural network scoring for efficient computing
Much work has been dedicated to estimating and optimizing workloads in high-performance computing (HPC) and deep learning. However, researchers have typically relied on few metrics to assess the efficiency of those techniques. Most notably, the accuracy, the loss of the prediction, and the computational time with regard to GPUs or/and CPUs characteristics. It is rare to see figures for power consumption, partly due to the difficulty of obtaining accurate power readings. In this paper, we introduce a composite score that aims to characterize the trade-off between accuracy and power consumption measured during the inference of neural networks. For this purpose, we present a new open-source tool allowing researchers to consider more metrics: granular power consumption, but also RAM/CPU/GPU utilization, as well as storage, and network input/output (I/O). To our best knowledge, it is the first fit test for neural architectures on hardware architectures. This is made possible thanks to reproducible power efficiency measurements. We applied this procedure to state-of-the-art neural network architectures on miscellaneous hardware. One of the main applications and novelties is the measurement of algorithmic power efficiency. The objective is to allow researchers to grasp their algorithms' efficiencies better. This methodology was developed to explore trade-offs between energy usage and accuracy in neural networks. It is also useful when fitting hardware for a specific task or to compare two architectures more accurately, with architecture exploration in mind.
Hugo Waltsburger, Erwan Libessart, Chengfang Ren, Anthony Kolar, Regis Guinvarc'h
2023-10-14T10:29:52Z
http://arxiv.org/abs/2310.09554v1
# Neural network scoring for efficient computing ###### Abstract Much work has been dedicated to estimating and optimizing workloads in high-performance computing (HPC) and deep learning. However, researchers have typically relied on few metrics to assess the efficiency of those techniques. Most notably, the accuracy, the loss of the prediction, and the computational time with regard to GPUs or/and CPUs characteristics. It is rare to see figures for power consumption, partly due to the difficulty of obtaining accurate power readings. In this paper, we introduce a composite score that aims to characterize the trade-off between accuracy and power consumption measured during the inference of neural networks. For this purpose, we present a new open-source tool allowing researchers to consider more metrics: granular power consumption, but also RAM/CPU/GPU utilization, as well as storage, and network input/output (I/O). To our best knowledge, it is the first fit test for neural architectures on hardware architectures. This is made possible thanks to reproducible power efficiency measurements. We applied this procedure to state-of-the-art neural network architectures on miscellaneous hardware. One of the main applications and novelties is the measurement of algorithmic power efficiency. The objective is to allow researchers to grasp their algorithms' efficiencies better. This methodology was developed to explore trade-offs between energy usage and accuracy in neural networks. It is also useful when fitting hardware for a specific task or to compare two architectures more accurately, with architecture exploration in mind. ## I Introduction Comparing the performance of different software and hardware architecture in the field of deep neural networks is a challenging endeavor. To establish a benchmark for comparison between various architectures, one must identify relevant metrics comparable across a wide variety of architectures and systems. Those metrics must have an adequate level of precision. However, the literature shows that benchmarks seldom comprise metrics other than the time required for the execution, the accuracy of algorithms, and the number of parameters and necessary multiply-adds [1, 2, 3, 4]. This approach is relevant in a paradigm where algorithms need to run faster and more accurately, with little regard to the marginal cost of increased performance. However, this approach is not optimal if the objective is to optimize the power consumption of the algorithm, be it out of ecological concern or due to constraints on the hardware available. Such purposes require specific metrics. We advocate that comparing systems should be done using more criteria. The aim is to balance out accuracy and efficiency, specifically in power efficiency. This goal can be achieved by using scores. One of the first scores in the literature, characterizing the trade-off between accuracy and complexity, was introduced in [5] as: \[Score=\frac{\text{Accuracy}}{\text{Number of parameters}} \tag{1}\] With the idea of representing the amount of accuracy captured by a single parameter. However, the number of parameters does not always correlate well with the complexity of a network [6]. Especially, convolutional neural networks comprise few parameters but are computationally expensive. Another iteration in neural network scoring, NetScore, taking multiply-accumulates (MACs) into account, was thus introduced in [7]. They propose Netscore, which they define as \[Netscore=20\log_{10}\left(\frac{\text{Accuracy}^{2}}{\sqrt{\text{MACs}\times \text{Parameters}}}\right) \tag{2}\] Netscore offers a more comprehensive view of the accuracy-efficiency trade-off of a neural network and seems especially relevant for convolutional neural network scoring. To elaborate upon this work, we want to introduce something that better reflects efficiency - especially in terms of power efficiency and adequation between hardware and software. This paper presents a new score that uses measurements rather than technical information on the network. We believe introducing measurements in neural network scoring is necessary to characterize a neural network's behavior accurately. To obtain the necessary metrics, we introduce Tub.ai [8], a new open-source tool that provides researchers with more diverse and granular metrics on their systems. We believe this methodology can be used in many fields - autonomous vehicles/drones, spaceborne applications, high-performance computing - and not only in AI. Its use is measuring both software and hardware performance. This paper also presents a benchmark of our score computed on various NN architectures during inference. Scoring was realized on various hardware platforms. This paper will first provide an overview of the motivation behind our new score and the tools we use in section II. We will then take measurements during inference using Tub.ai in section III, before presenting the scores obtained by several state-of-the-art NN architectures in section IV. ## II Proposed score and tooling As seen in section I, some methodologies for NN-scoring already exist. However, they are solely computed using the accuracy and parameters from the neural networks' technical sheets (MACs and parameters). When considering power efficiency, the literature shows [6] that power consumption does not scale linearly with either multiply-accumulates or parameters, which are the more common estimators for complexity in deep learning. Moreover, while these scores provide an estimation of the trade-off between accuracy and complexity, they are not measures. Since our logic is not to maximize accuracy, the best neural network for a specific application will depend on the hardware. We aim to strike an optimum between accuracy and power consumption. Only the inference phase is considered here. What seemed the most important to us was (i) accuracy, (ii) speed of inference, and (iii) power consumption per inference (in mWh). After several tests, we chose the formula in equation (3): \[Composite\ Score=\frac{\text{Accuracy}^{2}}{\text{Power consumption per inference}} \tag{3}\] This formulation, when developed as \[Score=\frac{\left(\frac{\text{Number of correct inforness}}{\text{Number of inferences}}\right)^{2}}{\left(\frac{\text{Total Power consumption}}{\text{Number of inferences}}\right)}\] Simplifies as \[Score=\frac{\text{Accuracy}}{\text{Average power consumed to obtain one correct inference}} \tag{4}\] We found that the power consumption per inference was sufficiently dependent on the speed of inference (the slower the inference, the higher the power consumption per inference) not to include the speed of inference as is. Using the rate of inference seemed to favor fast neural networks too much. This version of the score is easily comparable and has meaning from a physics standpoint. As shown in equation (4), it represents the accuracy captured by the average amount of energy consumed to obtain a single correct inference. As stated above, this score requires measurements made during inference. Therefore, a way of obtaining reliable measurements of energy consumption was needed. One of the main problems encountered when attempting to measure power consumption is how to measure metrics on our systems precisely. To do this, we created a new tool, Tub.ai. Using various software and protocols, Tub.ai allows us to gather utilization metrics from our machines. Here, these metrics were gathered directly from the CPU[9] and GPU[8] drivers, via RAPL and Nvidia-DCGM measurements. Once the data sources are set up, we need to aggregate them to exploit said data efficiently. To do this, we use a time series database that will store our data and allow us to query it at will. Over this database, we add a display engine that runs in the browser for easy visualization. Once all the individual bricks have been aggregated, we obtain the architecture displayed in figure 1. Tub.ai only uses open-source applications and will be made open-source for the community to use after publication. Tub.ai is highly modular and can be used to gather an extensive range of data pertaining to the usage of a computer, including custom metrics. ## III Curtating data on different NN architectures In this section, we extract data from our system while several computer vision NN architectures infer on the ILSVRC2012 dataset [14]. This dataset was chosen due to its size and the amount of research available on it. It comprises 1000 classes, with a training dataset containing 1.28 million images, a test dataset containing 100,000 images, and a validation dataset containing 50,000 images. We chose to test several versions of the Inception-ResnetV2 [10], NasNet [11], MobileNetV3 [12] and EfficientNetv2 [13] architectures. These architectures, released between 2016 and 2021, have either achieved then state of the art performance or approached it closely. The experiment consists of inferences on ILSVRC2012. All models were implemented using Tensorflow 2.10 with Keras, Cuda 11.4, CudNN 8.3, and Python 3.10. We used several different testing machines representing several grades of computers. * For HPC servers: A single A100 GPU with 40GB of V-RAM, coupled with an AMD EPYC 7742 Processor (128 cores) and 504GB of RAM * For upper-grade workstations: A Bi-Xeon 5222 workstation with 64GB of RAM and a Quadro RTX 5000 GPU with 16GB of V-RAM. * For lower grade machines: A laptop comprising an i7-8565 CPU and 8GB of RAM For the sake of readability, all runs will be given different tags: "A100" for the A100 runs, "Quadro" for the RTX 5000 runs, "Bi-Xeon" for the dual Xeon 5222 runs, and "i7" for the laptop runs. Each neural network's implementation was downloaded with pre-trained weights via the Tensorflow API. Figure 1: Flowchart of Tub.ai’s architecture Figure 2 presents the instantaneous power consumption measured by Tub.ai for the A100 GPU during several inferences runs on the training dataset using three different architectures. EfficientNet S and NasNet Mobile were run three times in succession with no timeout. MobileNet Small was run ten times with a 30 seconds timeout between each run to provide a reference. It can be seen that the instantaneous power consumption may exhibit significant variations over a single run. It is interesting to observe that NasNet Mobile and MobileNet Small yield a much lower power consumption than EfficientNet. This suggests that the former architectures are bandwidth-bound on this setup, while the computing capabilities of the GPU bind the latter architecture. In table I, we provide the data obtained on the Nvidia A100 tests. All key indicators were measured during three inferences on the complete ImageNet validation dataset. Using three inferences was deemed robust enough as the results proved very consistent: even when chaining ten successive inferences over 1 million images each, the average deviation to the mean for each run settled below 2%. The most significant observed outlier remained within 5% of the average across all runs. No occurrences of thermal throttling or startup lag were observed. CPU usage can be considered a good indicator of the model's throughput for GPU runs since the CPU handles the I/O.The CPU performance overhead introduced by Tub.ai is negligible compared to the CPU resources used by the inference during the benchmark: we measured an average load of 0.05%. The GPU's constant 99% memory usage is due to TensorFlow's inner workings, systematically reserving as much V-RAM as possible. When comparing the least and most consuming architectures, we can remark that there is a more than two-fold factor between instantaneously available metrics on this setup. We also observe a fifty-fold total power consumption factor. ## IV Scoring neural networks This metric aims to be a tool to evaluate the efficiency of different neural network architectures. It can be helpful in constrained systems, where there are limitations on both power consumption and computing power. It can also be used to evaluate the main leverage of any advancement in neural network architectures. The edge of an architecture may be its capacity to leverage Moore's Law and the algorithmic advances made on the various frameworks [1], or it can be a less quantifiable change made in the structure of the architecture that makes it sparser, faster or lighter. Finally, other researchers may want to employ different coefficients or consider more factors for specific use cases. We hope that our approach and the developed tooling will be valuable for the community to introduce new scores. Using our score, we obtain the ranking presented in table II-and table II. First, our ranking seems generally consistent with the scores obtained using [5] and [7]. Second, we observe a difference \begin{table} \begin{tabular}{|c||c|c|c|c|} \hline Model & Score[5] & Netscore & A100 score & Xeon score \\ \hline \hline ResNetV2 & 5 & 5 & 4 & 4 \\ \hline NasNet Mobile & 3 & 3 & 3 & 2 \\ \hline NasNet Large & 7 & 7 & 7 & 6 \\ \hline MobileNetV3 S & 1 & 1 & 1 & 1 \\ \hline MobileNetV3 L & 2 & 2 & 2 & 3 \\ \hline EfficientNetV2 S & 4 & 4 & 5 & 5 \\ \hline EfficientNetV2 M & 6 & 6 & 6 & 7 \\ \hline EfficientNetV2 L & 8 & 8 & 8 & 8 \\ \hline \end{tabular} \end{table} Table II: Ranking of NN architectures using different scores \begin{table} \begin{tabular}{|c c c c c c c c c|} \hline Model Name & Year & Validation accuracy & Inference time (s) & Average GPU power consumption (W) & Total power used (Wh) & Average GPU usage (\%) & Average GPU memory usage (\%) & Average CPU usage (\%) \\ \hline \hline Inception ResNet V2 [10] & 2016 & 80.3\% & 76 & 211 & 4.5 & 92 & 99 & 4.3 \\ \hline NasNet Mobile [11] & 2017 & 74.4\% & 39 & 144 & 1.6 & 57 & 99 & 5.3 \\ \hline NasNet Large [11] & 2017 & 82.5\% & 204 & 264 & 15 & 95 & 99 & 2.7 \\ \hline MobileNetV3 Small [12] & 2019 & 68.1\% & 15 & 107 & 0.5 & 40 & 99 & 10.7 \\ \hline MobileNetV3 Large [12] & 2019 & 75.6\% & 16 & 162 & 0.7 & 62 & 99 & 9.9 \\ \hline EfficientNetV2 S[13] & 2021 & 83.9\% & 89 & 253 & 6.3 & 88 & 99 & 4.7 \\ \hline EfficientNetV2 M[13] & 2021 & 85.1\% & 212 & 259 & 15.3 & 93 & 99 & 3.4 \\ \hline EfficientNetV2 L[13] & 2021 & 85.7\% & 365 & 262 & 26.5 & 96 & 99 & 3.2 \\ \hline \hline \end{tabular} \end{table} Table I: Comparison of NN architectures based on Tub.ai’s metrics, inference on ILSVRC2012 validation dataset, Nvidia A100 Figure 2: Nvidia A100 power consumption for 3 architectures in the hierarchy depending on the setup: on the Bi-Xeon platform, NasNet Mobile outperforms MobileNetV3 Large, and NasNet Large outperforms EfficientNetV2 Medium. Third, by observing the factor of proportionality between our scores and the A100 score (in small fonts next to each of our scores), we can see that some architectures (Inception ResNetV2, EfficientNetv2 Large) are much more penalized than other architectures (MobileNet, NasNet) when changing setup. This result confirms the value of taking measurements on neural network inferences rather than relying on platform-independent metrics. We hypothesize that this difference is due to a balance between computing and bandwidth requirements making some architectures less hardware constrained. Despite having the highest average power consumption of all platforms, the A100 has the highest score across all architectures. While higher-grade hardware has higher idle and in-charge energy usage, it usually exhibits a lower power consumption per inference due to increased inference speed. Notwithstanding, while the bi-Xeon setup outperforms the i7 on most architectures, the i7 fares better on MobileNets. This result emphasizes the need to study the envisioned application of a given neural network to extract its maximum performance. It also calls for more work on the architecture of neural networks to identify the limiting factor across different hardware settings and obtain the best hardware-software fit. MobileNetv3 Small has a net lead over all other networks and ranks first on all platforms, which seems reasonable since the MobileNet architecture was created to be _"a class of efficient models [...] for mobile and embedded vision applications"_[15]. Some of the more recent models perform worse than older models in terms of score. It seems likely that, in the future, the discrepancy between networks made for optimum efficiency and those created solely for performance will drift apart further. This observation leads to new approaches, with some recent architectures [16][17] seeking to optimize training/inference speed rather than accuracy or parameter efficiency and advocating for better architecture-algorithm adequation. We hope that it will be more commonplace in the future that some benchmarks rank neural network architectures using not only the validation accuracy but also more metrics, especially power consumption measured on both training and inference. ## V Conclusion and future works In this paper, we attempted to create a score based not on a technical datasheet but on measurements made on a platform. The idea is to measure the algorithm-architecture adequation between specific NNs and hardware. To obtain the required metrics to compute our score, we created Tub.ai. Tub.ai provides researchers with various metrics that can be leveraged to create meaningful comparisons between different software implementations and architectures. Tub.ai is open source, induces very little overhead in terms of performance, and is easy to use. This approach significantly benefits system developers who have to develop or optimize algorithms for specific hardware. Our deep neural network architecture benchmarks estimate how well they are fitted to be run on different platforms. The score values we have obtained across several architectures show that there can be significant discrepancies between platforms for the same neural network - which proves the interest of scoring using measurements. To our best knowledge, this is the first time power efficiency measurements have been included in the performance evaluation of neural network architectures. In a context of growing concern for the ecological impact of machine learning and high-performance computing in general, it is a step forward in the field of HPC where the main focus is not solely the algorithm's or architecture's performance but also their power efficiency. In the future, we plan on furthering the work we have done on scoring by exploring other hardware, architectures, and frameworks. Using identical neural network architectures implemented on different frameworks and running them on various test hardware, we would like to evaluate how well available deep learning frameworks can exploit the hardware's capabilities. An examination of the power efficiency of specialized neural processing units with regard to our score is planned. Similar undertakings on other datasets are considered. We also plan on updating Tub.ai and making it more precise and easier to use. We would be especially interested in seeing the results of neural network architecture search using this new score as the optimizing criterion. \begin{table} \begin{tabular}{c c c c c c c c c c c c} \hline \hline Model & Validation & \multicolumn{3}{c}{Power consumption/inference (\(\mu\)Wh)} & Score [5] & NetScore & \multicolumn{3}{c}{Our Score} \\ & accuracy & A100 & Quadro & Bi-Xeon & i7 & & & A100\(\pm\)00 & Quadro\(\pm\)00 & Bi-Xeon\(\pm\)000 & i7\(\pm\)000 \\ \hline \hline ResNetV2 [10] & 80.3\% & 89 & 290 & 3,017 & 3,961 & 1.44 & 47 & 7.2\(\pm\) & 2.2\(\pm\)3 & 0.21\(\pm\)0.0 & 0.16\(\pm\)0.0 \\ \hline NasNet Mobile [11] & 74.4\% & 31 & 63 & 302 & 580 & 14 & 70.1 & 17.9\(\pm\) & 8.8\(\pm\) & 1.84\(\pm\)9 & 0.95\(\pm\)0.0 \\ \hline NasNet Large [11] & 82.5\% & 299 & 792 & 4,792 & 9,766 & 0.9 & 42.4 & 2.3\(\pm\) & 0.862.6 & 0.14\(\pm\)0.0 & 0.07\(\pm\)0.0 \\ \hline MobileNetV3 S [12] & 68.1\% & 9 & 16 & 143 & 120 & **28.4** & **83.1** & **51.5\(\pm\)** & **29.0\(\pm\)** & **3.24\(\pm\)** & **3.87\(\pm\)** \\ \hline MobileNetV3 L [12] & 75.6\% & 14 & 29 & 334 & 293 & 14 & 74.5 & 40.8\(\pm\) & 19.5\(\pm\)1 & 1.70\(\pm\)0.0 & 1.95\(\pm\)1 \\ \hline EfficientNetV2 S [13] & 83.9\% & 125 & 286 & 3,340 & 4,195 & 3.9 & 54.2 & 5.6\(\pm\) & 2.46\(\pm\)2.3 & 0.21\(\pm\)0.0 & 0.17\(\pm\)0.0 \\ \hline EfficientNetV2 M [13] & 85.1\% & 305 & 877 & 8,794 & 12,236 & 1.6 & 46.0 & 2.4\(\pm\) & 0.83\(\pm\)0.9 & 0.08\(\pm\)0.0 & 0.06\(\pm\)0.0 \\ \hline EfficientNetV2 L [13] & 85.7\% & 530 & 1,539 & 16,698 & 24,346 & 0.7 & 39 & 1.4\(\pm\) & 0.48\(\pm\)0.9 & 0.04\(\pm\)0.0 & 0.03\(\pm\)0.0 \\ \hline \hline \end{tabular} \end{table} Table II: Power efficiency of neural network architectures based on our new metric
2309.02576
Emphysema Subtyping on Thoracic Computed Tomography Scans using Deep Neural Networks
Accurate identification of emphysema subtypes and severity is crucial for effective management of COPD and the study of disease heterogeneity. Manual analysis of emphysema subtypes and severity is laborious and subjective. To address this challenge, we present a deep learning-based approach for automating the Fleischner Society's visual score system for emphysema subtyping and severity analysis. We trained and evaluated our algorithm using 9650 subjects from the COPDGene study. Our algorithm achieved the predictive accuracy at 52\%, outperforming a previously published method's accuracy of 45\%. In addition, the agreement between the predicted scores of our method and the visual scores was good, where the previous method obtained only moderate agreement. Our approach employs a regression training strategy to generate categorical labels while simultaneously producing high-resolution localized activation maps for visualizing the network predictions. By leveraging these dense activation maps, our method possesses the capability to compute the percentage of emphysema involvement per lung in addition to categorical severity scores. Furthermore, the proposed method extends its predictive capabilities beyond centrilobular emphysema to include paraseptal emphysema subtypes.
Weiyi Xie, Colin Jacobs, Jean-Paul Charbonnier, Dirk Jan Slebos, Bram van Ginneken
2023-09-05T20:54:41Z
http://arxiv.org/abs/2309.02576v1
# Emphysema Subtyping on Thoracic Computed Tomography Scans using Deep Neural Networks ###### Abstract Accurate identification of emphysema subtypes and severity is crucial for effective management of COPD and the study of disease heterogeneity. Manual analysis of emphysema subtypes and severity is laborious and subjective. To address this challenge, we present a deep learning-based approach for automating the Fleischner Society's visual score system for emphysema subtyping and severity analysis. We trained and evaluated our algorithm using 9650 subjects from the COPDGene study. Our algorithm achieved the predictive accuracy at 52%, outperforming a previously published method's accuracy of 45%. In addition, the agreement between the predicted scores of our method and the visual scores was good, where the previous method obtained only moderate agreement. Our approach employs a regression training strategy to generate categorical labels while simultaneously producing high-resolution localized activation maps for visualizing the network predictions. By leveraging these dense activation maps, our method possesses the capability to compute the percentage of emphysema involvement per lung in addition to categorical severity scores. Furthermore, the proposed method extends its predictive capabilities beyond centrilobular emphysema to include paraseptal emphysema subtypes. ## Introduction Chronic obstructive pulmonary disease (COPD) is the third leading cause of death worldwide, causing 3.23 million deaths in 2019 [1]. COPD is characterized by irreversible airway obstruction, which can be caused by small airway diseases and emphysema. However, the extent to which each contributes to airflow obstruction varies among individuals, leading to significant heterogeneity among COPD patients [2]. To better understand this heterogeneity, researchers have used computed tomography (CT) scans to assess the distribution, severity, and progression of the disease in vivo [3, 4]. Additionally, many studies have attempted to identify COPD subtypes based on patterns observed on CT scans [5, 6, 7, 8]. The Fleischner Society has developed a structured scoring system for classifying subtypes of centrilobular and paraseptal emphysema based on the severity of the disease as observed on chest CT scans [8]. This scoring system, which we refer to in this work as the Fleischner system, utilizes six ordinal scales to evaluate centrilobular emphysema as absent, trace, mild, moderate, confluent, or advanced destructive, and paraseptal emphysema as absent, mild, or substantial. Previous studies of the Fleischner system [9, 10] have primarily focused on centrilobular emphysema and have reported good reader agreement in scoring centrilobular emphysema among human readers on scans from 3171 participants in the COPDGene study cohort [11] (a subset of the data used in our current study). These studies also demonstrated that visual scores of centrilobular emphysema are associated with mortality. To improve the efficiency of using the Fleischner system in research and clinical practice, a deep learning algorithm [10], referred to in this work as the Humphries algorithm, has been developed to automatically score centrilobular emphysema according to the Fleischner system. When comparing the predicted scores of the Humphries algorithm with visual scores for 7143 subjects from the COPDGene study, the Humphries algorithm achieved a linear weighted kappa statistic of 0.60 and a classification accuracy of 45%. Furthermore, the scores produced by the Humphries algorithm were found to be associated with mortality [10]. In this paper, we present a novel method that addresses two limitations of the existing Humphries algorithm: its focus on centrilobular scores and its lack of model interpretability. Our proposed method not only calculates severity scores for centrilobular emphysema, but also for paraseptal emphysema, enabling the analysis of both subtypes. Furthermore, it generates more interpretable high-resolution emphysema activation maps, allowing for the quantification of the percentage of emphysema per lung for further analysis. ## Methods ### Data Collection and Partitioning In this study, we utilized chest CT scans from the COPDGene clinical trial, which included data from 21 imaging centers in the United States and enrolled 10,192 subjects between 2008 and 2011. From this dataset, we used a subset of 9650 subjects for analysis, which is the same data as used in the previous study by Humphries et al. [10]. Using the common data set (including the partitioning) enabling us to directly compare our algorithm with the Humphries's algorithm [10]. The cohort of 9650 subjects includes all available COPDGene subjects having a baseline inspiration CT scan, the Fleischner visual scores, and mortality data during the Humphries's study. The lungs of these subjects on their inspiration CT scans were then segmented semi-automatically by trained analysts from Thirona, a company specializing in chest CT analysis. Following the Humphries's study [10], 9650 subjects were partitioned into a development set (\(n=2507\)) and an evaluation set (\(n=7143\)), with the development set further divided into a training set (\(n=2407\)) and a validation set (\(n=100\)). Only 2507 subjects were used as the development set because these were all available subjects with inspiration CT scans and Fleischner visual scores, excluding those previously included in an earlier analysis [9]. The evaluation set was used for statistical analysis and the reporting of performance metrics. The slice thickness of the CT scans ranged from 0.625-0.9mm and the pixel spacing ranged from 0.478-1.0mm. Most scans were performed using a tube voltage of 120kVp, a tube current of 200mAs, and reconstruction kernels B31f and B35f. The full CT protocols are detailed in Rega et al. [11]. Table 1 provides the distribution of COPD GOLD stages and Fleischner visual scores in the data selection, as well as the expected range of emphysema percentage per lung for each severity score. For example, a centrilobular emphysema score of 1 indicates an estimated emphysema percentage per lung between 1% and 5%. These percentage ranges were used to train our algorithm to capture the differences in disease severity scores. Patient demographics and lung functional parameters for the evaluation set (\(n=7143\)) can be found in the previous study by Humphries et al. [10]. #### Reference Standard CT scans were visually scored according to the Fleischner system by analysts who did not have prior experience in radiology interpretation. The annotation process is described in more detail in previous research by Lynch et al. [8, 9]. A reader study conducted on 3171 scans from our data selection by two analysts found good agreement in scoring centrilobular emphysema using the Fleischner system [9]. \begin{table} \end{table} Table 1: Distribution of GOLD stages [11] and the Fleischner visual scores [8] in our data selection in the development set (dev) and the evaluation set (eval). No PFT: spirometry data not available; PRISM: Preserved Ratio Impaired spirometry [12]. #### Lung Segmentation The lungs were extracted using commercialized software (LungQ, Thirona, Nijmegen, NL), followed by manual refinement if needed. We used lung segmentations for preprocessing CT scans in developing our algorithm. ### Algorithm Design #### Pre-processing of CT scans All CT scans in this work were preprocessed by clamping the intensity values between \([-1150\sim-300]\), rescaling to \([0\sim 1]\), cropping using lung segmentations, and resizing using trilinear interpolation to \(128\times 224\times 288\) in the axial, coronal, and sagittal dimensions, respectively. Note that the spacing may not be isotropic following this resizing process. The primary goal of resizing the images to a fixed input size is to maintain consistent GPU memory consumption throughout the inference process, thereby enhancing the practical utility of the proposed algorithm. By utilizing an input size of \(128\times 224\times 288\), we can accommodate a batch size of 4 within our network architecture while adhering to our computational budget (NVDIA A100 GPU with 40 gigabytes GPU memory). And the lung segmentations were used to set values outside of the lungs to zero, allowing the algorithm to focus on learning features within the lungs. #### Neural Network Architecture In building our algorithm, we chose to use the ResNet variant with 34 layers [13] as the backbone, as ResNet is a widely used convolutional neural network architecture in image recognition. As shown in Fig. 1, the network begins with a 3D convolution operation (kernel size=7, stride=2) using 64 filters to reduce the spatial size of the input by half. All convolutions in our network are isotropic, followed by batch normalization and a rectifier linear unit (ReLU) activation function, unless otherwise specified. We then reduce the spatial resolution by half using a max pooling layer (kernel size=3, stride=2). The pooled features serve as the input to four stacked ResNet layers, each consisting of several ResNet blocks. The number of ResNet blocks per layer increases from the first to the fourth layer, with 3, 4, 6, and 3 blocks, respectively. Each ResNet block includes two convolution operations with kernel size 3. From the second layer onwards, the first convolution in each block doubles the number of filters and, at the second layer, also reduces the spatial resolution by half using a stride of 2. This results in the input size being reduced by a factor of 8. The Resnet backbone generates convolutional features at a resolution that is eight times lower than the input resolution, which can compromise the interpretability of the model using standard techniques such as class activation maps (as demonstrated in the Humphries algorithm [10]). To address this limitation, we propose the inclusion of a reconstruction network on top of the ResNet backbone for the generation of dense features. As shown in Figure 2, the reconstruction network takes features extracted from the Resnet backbone as the inputs and comprises two upsampling layers, each of which includes one trilinear upsampling Figure 1: The overview of our ResNet-based backbone with 34 layers (a), consisting of four stacked ResNet layers (b). Each layer consists of 3, 4, 6, and 3 ResNet blocks (c), respectively, from top to bottom. operation and two 3x3 convolution filters to reduce upsampling artifacts. The upsampled features are then concatenated with the features from the ResNet backbone using a skip connection, as the one utilized in 3D-UNet[14]. The reconstruction network serves the same purpose as the decoder in 3D-UNet, where the ResNet backbone can be seen as the encoder. On top of the reconstruction head, we utilize two output heads depending on the training strategy. For classification training, the dense features from the reconstruction network are reshaped to have the appropriate number of channels for the number of target classes. Two \(1\times 1\times 1\) convolutions are employed to reshape the features, one for predicting centrilobular scores and the other for predicting paraseptal scores. The reshaped feature maps are then processed using global average pooling and activated using the softmax function to produce class probabilities. We refer to the reshaped dense features before pooling as dense class activation maps. For regression training, the reconstructed features are reshaped into two single-channel feature maps using \(1\times 1\times 1\) convolutions, one for predicting the percentage of centrilobular emphysema per lung and the other for predicting the percentage of paraseptal emphysema per lung. The sigmoid function is then applied to both feature maps, and the resulting features are averaged inside the lung segmentation to produce two floating numbers (emphysema percentages per lung). The sigmoid-activated dense features before pooling are referred to as the dense regression activation maps. #### Algorithm Training We refer to the network with the classification output head as the classification network, and the network with the regression output head as the regression network. We train each network separately and compare their results with the Humphries algorithm as the baseline. In the classification output head, we utilize a two-way convolutional layer with \(1\times 1\times 1\) kernels to predict two targets, following the definitions of the Fleischner system. This is depicted in Figure 2a. The first target is to classify six levels of centrilobular severity: absent (0), trace (1), mild (2), moderate (3), confluent (4), or advanced destructive (5). The second target is to classify three levels of paraseptal severity: absent (0), mild (1), and substantial (2). During the training phase, we employ a weighted cross-entropy loss function, where the weights are initially determined by the inverse frequency of the target classes and are subsequently updated at the conclusion of each epoch in order to penalize classes with low per-class accuracy. Training a convolutional neural network to classify emphysema severity scores in a multi-class classification setup may appear counter-intuitive. By definition, severity scores reflect the degree of involvement of emphysema in the lung and are directly correlated with the volume measurements of emphysematous regions. To correctly predict a severity score, the sum Figure 2: The reconstruction network on top of the ResNet backbone for producing dense features. The output of the reconstruction network is fed into either classification or the regression output head depending on the training strategy for predicting centrilobular scores (CLE out) and paraseptal scores (PSE out). Note that we do not use both output heads together for multi-tasking. of the corresponding channel for that score in the class activation maps must be larger than the sum in the other channels, resulting in one channel suppressing activations in the other channels (being discriminative). As a result, the class activation maps generated by the trained network may not necessarily represent the underlying disease, emphysema, but rather highlight areas that were used to make the correct classification. For example, the zero-indexed channel corresponding to the "absent" class is expected to be more heavily activated than the other channels when there is no emphysema present in the image. Therefore, instead of directly predicting visual scores, we propose a regression training strategy to estimate the percentage of emphysema involvement per lung using the interval regression loss proposed in previous research [15]. In the Fleischner system [8], severity scores are defined based on the percentage of emphysema involvement in the lung. Therefore, we convert the severity scores into intervals of emphysema percentage per lung using a predefined mapping table. For example, a centrilobular severity score of 2 (mild) indicates that the estimated centrilobular emphysema-affected region should occupy between 1-5% of the lung. In this way, each visual score corresponds to an interval of emphysema percentage in the lung. We use the mapping in Table 1b and Table 1c to convert visual scores into percentage intervals for training, and subsequently map the predicted percentage back to visual scores for evaluation. The regression output head produces two single-channel dense feature maps using a two-way convolution layer with \(1\times 1\times 1\) kernels for estimating the emphysema percentage in the lung for centrilobular and paraseptal subtypes, respectively. Denoting the estimated percentage as \(p\), and the target emphysema percentage range \((r_{l},r_{u})\), the interval regression loss \(L_{INT}\) can be written as: \[\begin{array}{l}K=(0.5*(r_{l}-r_{u}))^{2}.\\ \text{min:}\ L_{INT}=max(0,(p-0.5*(r_{l}+r_{u}))^{2}-K)\end{array} \tag{1}\] The dense regression activation maps, which are sigmoid-activated single-channel dense feature maps before the lung-wise mean pooling, represent the probability of emphysema. During training, we impose two constraints on the dense regression activation maps. The first constraint is the overlapping loss, which ensures that the dense regression activation maps for two emphysema subtypes do not overlap, as each voxel can only be assigned to one subtype (either centrilobular or paraseptal). Denoting the dense regression activation map for centrilobular emphysema as \(p_{C}^{j}\) and the dense regression activation map for paraseptal emphysema as \(p_{S}^{j}\) where \(i\) is the location index, the overlapping loss \(L_{OL}\) can be written as: \[\text{min:}\ L_{OL}=\frac{2*\sum_{i}(p_{C}^{j}p_{S}^{j})}{\sum(p_{C}^{j})+ \sum(p_{S}^{j})}. \tag{2}\] The overlapping loss is used to compute the soft Dice coefficient between two dense regression activation maps (probability maps). The second constraint is the segmentation loss. To generate the segmentation pseudo labels, we identify the low-attenuation areas (LAA-950) in the lungs by applying an intensity threshold of -950 HU to CT images. This threshold is commonly used in the analysis of emphysema on CT scans [8]. The segmentation loss ensures that the union of dense regression activation maps from both subtypes matches the LAA-950. Using the previous notations, the segmentation loss \(L_{SEG}\) can be written as: \[\begin{array}{l}p^{i}=min(max(0.0,p_{C}^{i}+p_{S}^{j}),1.0)\\ \text{min:}\ L_{SEG}=\sum_{i}(-*log(p^{i}*t^{i}+(1.0-p^{i})(1.0-t^{i})))\end{array} \tag{3}\] where \(t^{i}\) is the segmentation target indexed at the voxel location \(i\), and \(s\) is the smoothness factor. The segmentation loss is a binary cross-entropy loss with label smoothing [16]. We apply label smoothing to encourage the network to be less confident in the target pseudo labels. The joint emphysema probability map is then generated by clamping the values of the summation of two dense regression activation maps between 0 and 1. The final loss \(L\) for regression training is the sum of the interval regression loss, the overlapping loss, and the segmentation loss as \(L=L_{INT}+L_{OL}+L_{SEG}\). We used a variety of data augmentation techniques in training both networks, including flips and rotations, intensity and contrast jittering, cropping, Gaussian smoothing, and additive noise. These augmentations were applied randomly and all spatial transforms were preserved using trilinear interpolation to maintain the original size of the images. Both networks were trained for a maximum of 200 epochs with an initial learning rate of 1e-5, using an Adam optimizer and a learning rate scheduler with exponential decay of 0.9. Training was terminate if there was no improvement in the validation set performance for 10 consecutive epochs. #### Evaluation Metrics and Statistical Analysis To assess the classification performance, we use classification accuracy (ACC), the F-measurement (harmonic mean of precision and recall), and linear weighted kappa (\(K\) statistics) as evaluation metrics. The ACC and F-measurement are calculated using the Sklearn python package (version 1.1.2) [17], while the \(K\) statistics are calculated using the _rel_ software package in R (version 3.6.2). We also create confusion matrices and compute per-class metrics for each method. The level of agreement between algorithm predictions and visual scores is classified as slight, fair, moderate, good, or excellent based on \(K\) values of 0.20 or less, 0.21-0.40, 0.41-0.60, 0.61-0.80, and 0.81 or higher, respectively [18]. ## Results We compared the performance of our classification and regression networks in predicting both centrilobular and paraseptal visual scores on an evaluation set. We also compared our results to those obtained using the Humphries algorithm for classifying centrilobular severity scores on the same evaluation set. As shown in Table 2, both the classification and regression networks outperformed the Humphries algorithm in terms of overall classification accuracy for predicting centrilobular severity scores. Both networks achieved predictive accuracy above 51%, while the Humphries algorithm only reached 45%. In terms of kappa statistics, the agreements between automated scores and visual scores for both the classification and regression networks were good for centrilobular emphysema, slightly better than the moderate agreement reported by the Humphries algorithm. The agreements between our networks and paraseptal visual scores were moderate. The Humphries algorithm did not report results for paraseptal emphysema. Interestingly, the comparison between the classification and regression networks showed that the classification network outperformed the regression network in predicting centrilobular severity scores, but underperformed when predicting paraseptal scores in terms of overall accuracy and kappa statistics. These findings suggest that the two models may fit differently into the underlying target distribution. Examining the confusion matrices in Table 3 (a,b), we observed that the classification network performed poorly in recognizing trace levels of centrilobular emphysema, with 31.15% precision and 34.11% recall. Analysis of the results revealed that most of these errors were caused by mislabeling trace emphysema as absent or vice versa. Similarly, in distinguishing paraseptal severity scores, the classification network had a high error rate for mild emphysema, with 36.90% precision and 50.51% recall. Furthermore, the regression network also exhibited a high rate of mislabeling between absence, trace and mild centrilobular emphysema. Specifically, the regression network performed the worst when labeling trace and mild centrilobular emphysema, with 29.43% precision and 48.03% recall in trace, and 43.19% precision and 27.89% recall in mild. In distinguishing paraseptal severity scores, the regression network also had the worst performance for mild emphysema, with 38.57% precision and 41.72% recall. The suboptimal performance observed in the lighter grades of emphysema severity may be attributed to the nuanced distinctions in lung involvement that define these grades (scores less than 2), resulting in a high degree of ambiguity in the scoring process. This challenge is also reflected in the results of the Humphries algorithm (Table 4), highlighting the prevalent difficulty in accurately assessing the severity of emphysema. We identified a discrepancy in the performance of the Humphries algorithm and our methods in classifying the severity of centrilobular emphysema. Specifically, the Humphries algorithm demonstrated a tendency to overestimate the presence of emphysema in cases where it is actually absent, with 1495 cases being mislabeled as trace. Conversely, our methods tended to underestimate the severity in cases where it is present in minimal levels (trace), resulting in 536 cases of trace emphysema being mislabeled as absence by the regression network. The regression network has an advantage in terms of error distribution in confusion matrices, as it produces a percentage of lung involvement by averaging the dense regression maps within the lung volume. This improves its consistency in predicting severity scores. We observed a consistent shift in the error distribution in the confusion matrix, with the network more often mislabeling the target as one grade lower (Table 3 (c,d)). For example, in the case of centrilobular classification, the regression network classified 536 scans as absent and 121 scans as mild emphysema when they were manually scored as trace emphysema, and mislabeled 682 scans as trace and 117 scans as moderate when the actual labels were mild emphysema. In contrast, the error distribution was not consistent in the results of the classification network, which made more errors on one grade higher in the confluent centrilobular emphysema, with 141 scans mislabeled as moderate and 189 scans as advanced emphysema. However, for other grades, errors were made by mislabeling them as one grade lower. In the extreme cases, the classification network mislabeled one case of absent centrilobular emphysema as advanced emphysema and classified 205 cases as substantial paraseptal emphysema when the visual score indicated absent. These critical errors suggest that the classification network was sometimes confused between centrilobular and paraseptal CT patterns, \begin{table} \begin{tabular}{|l|l|l|l|l|} \hline Method & Subtype & ACC(\%) & F-measure & Linear Weighted Kappa (95\% CI) \\ \hline The Humphries algorithm [10] & centrilobular & 45 & - & 60 \\ \hline Ours (classification) & centrilobular & 52.23 & 51.00 & 64.29 (63.16-65.42) \\ \hline Ours (classification) & paraseptal & 59.12 & 57.12 & 42.03 (40.21-43.85) \\ \hline Ours (regression) & centrilobular & 51.32 & 49.61 & 64.24 (63.14-65.35) \\ \hline Ours (regression) & paraseptal & 64.62 & 60.74 & 52.06 (50.40-53.73) \\ \hline \end{tabular} \end{table} Table 2: Results of the classification and regression networks on the evaluation set (\(n=7143\)). The classification accuracy (ACC), F-measurements (F-measure), and linear weighted kappa are calculated against the visual scores. We also list the results from the Humphries algorithm, obtained on the same test set, where only ACC and kappa were reported for predicting centrilobular emphysema severity scores. \begin{table} \begin{tabular}{l|l l l l l|l} \hline \hline & \multicolumn{6}{c|}{Visual Scores} & \\ \hline Predict & Absent & Trace & Mild & Moderate & Confluence & Advanced & Precision (\%) \\ \hline Absent & 1621 & 530 & 259 & 21 & 0 & 0 & 66.68 \\ Trace & 625 & 451 & 322 & 50 & 0 & 0 & 31.15 \\ Mild & 230 & 294 & 664 & 288 & 4 & 0 & 44.86 \\ Moderate & 22 & 42 & 142 & 514 & 141 & 7 & 59.22 \\ Confluence & 0 & 3 & 15 & 153 & 322 & 42 & 60.19 \\ Advanced & 1 & 2 & 7 & 23 & 189 & 159 & 41.73 \\ \hline Recall (\%) & 64.87 & 34.11 & 47.13 & 49.00 & 49.09 & 76.44 & 52.23 (ACC\%) \\ \hline \multicolumn{6}{c}{**(a)** Classification Network in Predicting Centrilobular Emphysema Severity} \\ \hline \hline \multicolumn{6}{c}{Visual Scores} \\ \hline Predict & Absent & Mild & Substantial & Precision (\%) \\ \hline Absent & 2508 & 740 & 181 & 73.14 \\ Mild & 1144 & 942 & 467 & 36.90 \\ Substantial & 205 & 183 & 773 & 66.58 \\ \hline Recall (\%) & 65.02 & 50.51 & 54.40 & 59.12 (ACC\%) \\ \hline \multicolumn{6}{c}{**(b)** Classification Network in Predicting Paraseptal Emphysema Severity} \\ \hline \hline \end{tabular} \end{table} Table 3: Confusion metrics of the classification and regression network for classifying centrilobular and paraseptal emphysema severity scores against the visual scores on the evaluation set (\(n=7143\)). Advanced destructive emphysema is denoted as Advanced. possibly due to the co-existence of both subtypes in some training scans. We also noticed that the regression network produced fewer critical errors in paraseptal classification, mistakenly labeling 97 scans as substantial when they were manually scored as absent. This number was 205 in the result of the classification network. This improvement may be due to the introduction of training constraints in the regression training, which enforce that dense predictions for centrilobular and paraseptal emphysema are mutually exclusive. However, we also observed that the regression network labeled 104 scans as absent when the visual scores indicated substantial paraseptal emphysema. This suggests that the regression network may under-segment or completely miss paraseptal emphysema in some cases. ### Visual Interpretation We utilized dense activation maps to visualize the features that correspond to the classification decisions. As shown in Figure 3, we present the dense class and regression activation maps on two examples of predicting centrilobular and paraseptal emphysema subtypes. Each example consists of two images, with \(3\times 3\) tiles, where the left image displays the dense class activation maps and the right image displays the dense regression activation maps. The three columns in each image are sampled axial slices from the input CT scan. For each image, the rows represent the preprocessed input CT scan, the activation map for centrilobular emphysema, and the activation map corresponding to paraseptal emphysema. In general, the dense class activation maps do not necessarily align with object contours, e.g., blobs of paraseptal emphysema in the second case (Fig. 3 Case II (a)). Naturally, class activation maps only reflect discriminative regions responsible for classification. By utilizing the reconstruction network to generate dense features, our network's dense class activation maps already provide improved localization compared to the class activation maps generated by the Fleischer algorithm (which tend to be blurry blobs, as seen in their publication). The application of regression training further improves lesion localization, as can be seen in the subpleural paraseptal emphysema in the second case (Figure 3, Case II(b)) and small blobs following the secondary lobular structures in the first case (Figure 3, Case I(b)). Additionally, due to the use of the overlapping loss (Eq.2), the centrilobular and paraseptal activations do not overlap in the dense regression activation maps (Figure3, Case II(b)), unlike in the class activation maps. For instance, in the first case, both class activation maps responded to the same regions in the right lobe (Figure 3, Case I(a)). This highlights the effectiveness of our proposed method in providing improved lesion localization compared to the Fleischer algorithm. ### Ablation Study On Neural Network Architecture In our ablation study, we assessed three variants of ResNet architectures as the backbone network. ResNet18 comprised 2, 2, and 2 ResNet layers. Both ResNet34 and ResNet50 consisted of 3, 4, 6, and 3 ResNet layers. ResNet50 uses BottleNeck blocks, while ResNet34 uses the basic ResNet blocks [13]. As reported in Table 5, ResNet34 has the largest number of parameters (64.79 million) compared with the ResNet18 (34.48 million) and ResNet50 (47.86 million). ResNet50 has more convolution operations than ResNet34 but has fewer number of parameters because of replacing ResNet blocks (two \(3\times 3\times 3\) convolutions) in ResNet34 with BottleNeck blocks (one \(3\times 3\times 3\) convolutions connecting two \(1\times 1\times 1\) convolutions). BottleNeck blocks employed in the ResNet50-based networks greatly reduce the number of parameters in 3D convolutions. However, the use of BottleNeck blocks in the ResNet50-based network leads to convolution features at the lowest resolution having a significantly larger number of channels (2048) compared to the ResNet34-based network (512). As a consequence, there is a substantial increase in the number of GMACs in the first upsampling layer, thereby contributing to an overall increase in GMACs for the ResNet50-based network when compared to the ResNet34-based network. Details regarding the BottleNeck blocks can be found elsewhere [13]. Among the tested ResNet architectures, ResNet50 exhibited the highest computational intensity, reaching approximately 1702 GMACs (Giga Multiply-Add Operations). \begin{table} \begin{tabular}{l|l l l l l l|l} \hline \hline & \multicolumn{6}{c|}{Visual Scores} & \multicolumn{1}{c}{} \\ \hline Predict & Absent & Trace & Mild & Moderate & Confluence & Advanced & Precision (\%) \\ \hline Absent & 637 & 126 & 35 & 2 & 0 & 0 & 79.62 \\ Trace & 1495 & 751 & 380 & 23 & 1 & 0 & 28.82 \\ Mild & 324 & 377 & 678 & 166 & 4 & 0 & 43.77 \\ Moderate & 41 & 66 & 296 & 643 & 154 & 8 & 53.22 \\ Confluence & 2 & 2 & 20 & 211 & 428 & 108 & 55.51 \\ Advanced & 0 & 0 & 0 & 4 & 69 & 92 & 55.57 \\ \hline Recall (\%) & 25.49 & 56.80 & 48.11 & 61.29 & 65.24 & 44.23 & 45.21 (ACC\%) \\ \hline \hline \end{tabular} \end{table} Table 4: Confusion matrix of the Humphries algorithm for classifying centrilobular emphysema severity scores against the visual scores on the evaluation set (\(n=7143\)). Advanced destructive emphysema is denoted as Advanced. Figure 3: Dense class activation maps (left) versus dense regression activation maps (right), We show two cases, and each consists of three rows. The first row shows the input image (cropped and masked by the lung segmentation), the second row illustrates the activation maps for the centrifugal emphysema, and the third row shows the activation maps for the paraseptal emphysema. ResNet34 demonstrates superior predictive accuracy compared to ResNet18 and ResNet50 in both the classification and regression networks. This suggests that volumetric data may necessitate higher complexity (more parameters) for optimal fitting. Notably, the regression networks generally attained higher performance (especially in linear weighted Kappa values) than the classification networks in predicting parasegtal labels. This improvement could be attributed to the incorporation of mutual exclusive constraints in regression training, as discussed in Section 2. ResNet18 exhibits the lowest performance, indicating that the smaller network's complexity may not be adequate for effectively addressing the subtyping problem. We also observed that the linear-weighted kappa values are generally higher than accuracy and F-measure in centrifugal predictions, while kappa values are lower than accuracy and F-measure in parasegtal predictions. These disparities are particularly pronounced in the results of the classification networks. This indicates a heightened occurrence of critical errors when attempting to predict parasegtal labels, as also evidenced by the observed confusion matrices (refer to Table 3) in the results of ResNet34. ## Discussion In this study, we propose a novel approach for automating the Fleischer scoring system for identifying emphysema subtypes on CT images using deep neural networks. Our method incorporates a reconstruction sub-network, which is utilized to generate high-resolution activation maps, providing more localized information for model interpretation in comparison to the low-resolution heatmaps produced by the Fleischer algorithm. Additionally, our regression-based training strategy offers an estimation of emphysema percentage in the lungs and generates the regression activation maps which offer improved emphysema localization. The regression training approach is more intuitive as it utilizes the semantic link between severity scores and emphysema involvement in the lungs, compared to the classification approach which only aims to identify discriminative features between different severity grades. The target labels for regression training are percentage intervals translated from categorical scores using a predefined mapping table, and the network is trained using an interval regression loss to ensure that the predicted percentage falls within the target interval. This approach could be used for automating many other scoring systems used in radiology based on visual assessment of the (relative) size of the affected volume. We use lung-wise average pooling to aggregate the sigmoid-activated dense features (dense regression activation maps) to estimate the emphysema percentage per lung, and we incorporate the overlapping loss to ensure that each voxel is only assigned to one of the two emphysema subtypes (centrilobular or parasegtal). Additionally, we use low-attenuation areas in the lung (LAA-950) as visual cues in the regression training to provide localized information to the network. Our method generates both categorical visual scores and estimated emphysema percentages for both centrilobular and parasegtal subtypes, offering additional features in comparison to the existing method, which can only produce centrilobular severity scores. The dense regression activation maps generated by our approach provide detailed emphysema localization, potentially enabling further clinical research in this field. The results of our study showed that our method (both the classification and regression networks) outperformed the Fleischer \begin{table} \end{table} Table 5: Results of Ablation Study of three variants (ResNet18, ResNet34, and ResNet50) of ResNet as our backbone network. algorithm in terms of classification accuracy for predicting centrilobular severity grades (52% versus 45%). Our method also had better reader agreement as measured by kappa statistics. The regression approach has several advantages compared to the classification approaches. It resulted in fewer critical errors in the confusion matrix comparison, such as mislabeling heavily diseased cases as disease-free. In addition, the errors were distributed more consistently, with a shift to a lower severity grade in the confusion matrix (Table 3 (c)), which is not observed in the results of the classification approach (Table 3 (a)). The ablation study (Refer to Table 5) showcased consistent observations regarding the classification performances and their patterns across various subtyping tasks using different ResNet backbones. In terms of qualitative analysis, the dense regression activation maps were observed to provide superior localization, particularly in the case of paraseptal emphysema with sub-pleural bullae. In contrast, the dense class activation maps were observed to be less specific, as they included many surrounding regions, and were not able to distinguish different emphysema subtypes. There are several limitations to consider in this study. First, our systems were only trained using CT scans from the COPDGene study, which had a specific data acquisition protocol and carefully curated scans. This may limit the generalizability of our algorithms to other datasets with different CT acquisition processes. We attempted to mitigate this risk by using data augmentation techniques that introduce common noise patterns and using early stopping to prevent overfitting. Second, our algorithms require the availability of lung segmentation for both training and inference, which may be a challenge to implement in clinical practice, although fast and accurate publicly available systems for CT lung segmentation are available [15, 19]. Third, we did not validate the segmentation performance using the generated dense regression activation maps, although these maps appear to be capable of localizing emphysema patterns based on visual inspection. This was due to the lack of voxel-wise annotations of emphysema patterns with different subtypes. ## Model Availability Our algorithms are available at GitHub ([https://github.com/DIAGNijmegen/bodyct-dram-emph-subtype](https://github.com/DIAGNijmegen/bodyct-dram-emph-subtype)). We integrated our trained regression network as a ready-to-use web service hosted on the Grand-challenge platform ([https://grand-challenge.org/algorithms/weakly-supervised-emphysema-subtyping/](https://grand-challenge.org/algorithms/weakly-supervised-emphysema-subtyping/)). ## Data Availability To access the COPDGene data used in this study for research purposes, please visit [https://www.ncbi.nlm.nih.gov/projects/gap/cgi-bin/study.cgi?study_id=phs000179.v6.p2](https://www.ncbi.nlm.nih.gov/projects/gap/cgi-bin/study.cgi?study_id=phs000179.v6.p2) and submit an ancillary study proposal. We received approval for this work under the ANC-251 proposal. To submit your proposal, contact the COPDGene Administrative Core Executive Secretary, Sara Penchev, at [email protected]. The corresponding author ([email protected]) may be reached for data inquiry.
2308.15323
Occlusion-Aware Deep Convolutional Neural Network via Homogeneous Tanh-transforms for Face Parsing
Face parsing infers a pixel-wise label map for each semantic facial component. Previous methods generally work well for uncovered faces, however, they overlook facial occlusion and ignore some contextual areas outside a single face, especially when facial occlusion has become a common situation during the COVID-19 epidemic. Inspired by the lighting phenomena in everyday life, where illumination from four distinct lamps provides a more uniform distribution than a single central light source, we propose a novel homogeneous tanh-transform for image preprocessing, which is made up of four tanh-transforms. These transforms fuse the central vision and the peripheral vision together. Our proposed method addresses the dilemma of face parsing under occlusion and compresses more information from the surrounding context. Based on homogeneous tanh-transforms, we propose an occlusion-aware convolutional neural network for occluded face parsing. It combines information in both Tanh-polar space and Tanh-Cartesian space, capable of enhancing receptive fields. Furthermore, we introduce an occlusion-aware loss to focus on the boundaries of occluded regions. The network is simple, flexible, and can be trained end-to-end. To facilitate future research of occluded face parsing, we also contribute a new cleaned face parsing dataset. This dataset is manually purified from several academic or industrial datasets, including CelebAMask-HQ, Short-video Face Parsing, and the Helen dataset, and will be made public. Experiments demonstrate that our method surpasses state-of-the-art methods in face parsing under occlusion.
Jianhua Qiua, Weihua Liu, Chaochao Lin, Jiaojiao Li, Haoping Yu, Said Boumaraf
2023-08-29T14:20:13Z
http://arxiv.org/abs/2308.15323v2
# Occlusion-Aware Deep Convolutional Neural Network via Homogeneous Tanh-transforms for Face Parsing ###### Abstract Face parsing infers a pixel-wise label map for each semantic facial component. Previous methods generally work well for uncovered faces, however overlook the facial occlusion and ignore some contextual area outside a single face, especially when facial occlusion has become a common situation during the COVID-19 epidemic. Inspired by the illumination theory of image, we propose a novel homogeneous tanh-transforms for image preprocessing, which made up of four tanh-transforms, that fuse the central vision and the peripheral vision together. Our proposed method addresses the dilemma of face parsing under occlusion and compresses more information of surrounding context. Based on homogeneous tanh-transforms, we propose an occlusion-aware convolutional neural network for occluded face parsing. It combines the information both in Tanh-polar space and Tanh-Cartesian space, capable of enhancing receptive fields. Furthermore, we introduce an occlusion-aware loss to focus on the boundaries of occluded regions. The network is simple and flexible, and can be trained end-to-end. To facilitate future research of occluded face parsing, we also contribute a new cleaned face parsing dataset, which is manually purified from several academic or industrial datasets, including CelebAMask-HQ, Short-video Face Parsing as well as Helen dataset and will make it public. Experiments demonstrate that our method surpasses state-of-art methods of face parsing under occlusion. keywords: face parsing, face occlusion, convolutional neural networks + PACS: 0000, 1111 2000 MSC: 0000, 1111 ## 1 Introduction Face parsing aims to predict labels for each pixel in input face images based on pixel semantics, and the parsed results are widely used for other applications, such as face analysis (Selfa and Qazi, 2005), face editing (De Clerck and Proffit, 2015), face swapping (Bitouk et al., 2008) and face recognition (Zhao et al., 2003). While parsing a face is very similar to generic scene segmentation (Hariharan et al., 2014; Noh et al., 2015), they are not the same because faces have similar contexts and translation invariant. With the rapid development of convolutional neural networks (CNN) (LeCun et al., 1989), a plethora of methods for basic face parsing tasks has been widely developed. (Yin et al., 2021). Previous face parsing methods struggle to handle occlusions. According to the modelling ideas, classical face parsing methods are divided into global methods and local methods. The former examines an entire face (Liu et al., 2015a), whereas the latter models each facial component individually. (Liu et al., 2017; Luo et al., 2012). Lin et al. (2019)'s experiment shows that the global methods can label the background and hair better, but their performance is worse than local methods and they mostly process the face in Cartesian coordinates system. The recent emergence of non-Cartesian coordinate systems provides an alternative to the constraints of classical methods. Liu et al. (2017) and Lin et al. (2019) perform the face parsing tasks in a new coordinate system and achieve significant improvement. However, when key face components, such as the nose and mouth, are occluded, the performance of these methods suffers. Because of the COVID-19 pandemic, the number of people wearing masks to cover their faces has increased significantly (Wang et al., 2020), making occluded face parsing difficult. Sunglasses, eye masks, and fake noses are also examples of facial occlusions. In addition, sunglasses, eye masks, and fake noses are examples of facial occlusions. As a result, when analyzing occluded faces, classical methods are prone to misidentify occlusions as face components with similar positions, resulting in unsatisfactory results. The main cause of the aforementioned issues is summarized, which is that previous methods frequently failed to pay attention to the edges of the face. As a result, our method attempts to focus on the four corners of a face, drawing inspiration from image illumination theory. More facial details can be captured with the illumination theory when divide a face image into four parts and perform a kind of transform into a non-Cartesian coordinate system, because this is equivalent to dispersing a center point light source into an area light source. The four slices of face details can be enhanced separately by this process, and occlusions have a limited effect on all slices. This process can improve the four slices of face details individually, and occlusions have a limited effect on all slices. Based on this characteristic, we propose a novel homogeneous Tanh-transforms, called four-point transform, which transforms the image to the four Tanh-polar coordinate systems using the four corner points of the face as the origin respectively. Tanh-polar representation differs from the original Cartesian representation and it contains the contextual information of the face image. Then, the transformed face is fed into an occlusion-aware convolutional neural network. A new building block, called Four-point block (FPB) and a special occlusion-aware loss are designed to better extract occluded features. When compared to existing face parsing method, the proposed architecture improves the robustness of face parsing under occlusion and can be trained in an end-to-end fashion. In order to improve the anti-occlusion capability of our model and to validate the superiority of the method in facial occlusion, we present Sheltered Face Parsing Dataset which contains 52,097 in-the-wild images. The annotation categories are reorganized for these images to include 11 face regions and 3 occlusions. Extensive experiments show that these approaches have strong anti-occlusion capabilities, as well as excellent performance for both intra-dataset and cross-dataset evaluation. Fig. 1 shows the benefit of the proposed method on a few samples from the test set. Our method is insensitive to various forms of occlusions and more importantly, arrive at much stable predictions that hard to attain with ordinary coordinate. Overall, our contributions are summarized as follows: * A novel four-point transform neural network (FTNet) is proposed to address the problem of face parsing under occlusion which takes full advantage of the contextual information of the face image and report experimental results in face parsing dataset. To the best of our knowledge, it is the first attempt to use the relationship between occlusion and illumination theory of image. * The homogeneous Tanh-transforms, called four-point transform, is introduced, which is used to warp faces into the Tanh-polar coordinate system by four corner points of expanded bounding box. In Tanh-polar coordinate systems with four points as the origin respectively, the key information of the facial components is enhanced which can improve the generalization capability of occluded face parsing. * Leveraging the proposed homogeneous Tanh-transforms, the structure of basic convolutional neural network with Four-point Block (FPB) is designed for occluded faces. Using our coordinate transform as constraints, a new loss function named occlusion-aware loss is created, which enhances occlusion segmentation. Our overall approach is simple and can be trained end-to-end. * As an additional contribution, the Sheltered Face Parsing Dataset is presented, which is a novel in-the-wild sheltered face parsing dataset with over 54 thousand images and we intend to make public to aid future research. The remainder of the paper is organized as follows. Section 2 discusses Figure 1: Examples from our Sheltered Face Parsing Dataset and the color-coded labels predicted by our proposed method, which performs precise parsing of each facial component when some objects cover the face. related work, Section 3 describes our proposed method, Section 4 reports the experimental result and Section 5 concludes our contribution along with future work. ## 2 Related Work Face parsing research has yielded impressive results, thanks in large part to advances in deep learning. This section provides a brief overview of related work on face parsing, image polar transform, and occlusion handling. ### Face Parsing Most existing approaches for face parsing can be categorized into two groups: global-based and local-based. Global-based methods analyze the entire image and directly predict per-pixel semantic labels. Earlier works concentrated on developing a model to represent the spatial relationships of entire images (Warrell and Prince, 2009; Smith et al., 2013). With the rapid development of CNN, face parsing models tend to use network designs with multiple loss functions (Liu et al., 2015). Zhou et al. (2017) created a unified framework by combining FCN, super-pixel information, and the CRF model. Nonetheless, Lin et al. (2019)'s experiment showed that these global-based approaches can only provide a limited accuracy due to the lack of focus on facial components. Local-based methods train the model for each facial component separately in order to predict the mask for each part individually. Early works on local-based methods predicted all facial components separately, then combined them based on spatial correlations (Luo et al., 2012). Liu et al. (2017) improved accuracy using a two-stage approach that included a shallow CNN and a spatially variant recurrent neural network. ICNN (Zhou et al., 2015) incorporates two stages of face parsing, first locating the facial component and then labelling the pixels of the identified facial parts. Local-based methods can improve facial component accuracy, but their accuracy in predicting hair and background is limited. ### Image Polar Transform Most existing computer vision models are built on images in a Cartesian coordinate system. These models are very sensitive to many complex affine transformations such as rotation and scaling due to the large number of irreversible interpolations required. Therefore, many image processing algorithms that convert the original image to a representation in another coordinate system have been investigated. Among them, polar coordinate is a well-known sampling method in the field of image processing. Salehinejad et al. (2018) used a sampling method based on radial transformation to augment training data, which transform each input image into multiple images in polar coordinate systems, thus facilitate the training of models from limited source data. Kim et al. (2018) proposed a user-guided point as the origin of the polar coordinate system. The transformed image is then segmented using a CNN. Jiang and Mei (2019) created a novel polar coordinate CNN (PC-CNN) for rotation invariant feature learning, which transformed the rotation invariance of training samples into translation invariance through polar coordinate transform. Fu et al. (2018) introduced a polar transform to represent the original image in a polar coordinate system, which further improved the segmentation performance of the proposed architecture. Furthermore, Lin et al. (2019) used the RoI Tanh-Warping to alter the image's coordinate system, which transformed the face in the image's center. The performance was then improved by Lin et al. (2021) by proposing a Tanh-polar representation and introducing a well-designed CNN backbone. However, unlike our proposed method, these methods ignore the impact of occluded scenes on the face parsing task, rendering them ineffective in the presence of occlusion. ### Occlusion Handling Occlusion handling strategies have been extensively studied. Gao et al. (2011) proposed a segmentation-aware model with binary variables to handle occlusions, which denote the visibility of objects in each bounding box cell. Ghiasi et al. (2014) used deformable models with local templates to handle occlusion in human pose estimation. Chen et al. (2015) used an energy minimization framework to address the occlusion problem by incorporating top-down class-specific inference and shape prediction as well as bottom-up segments. Zheng et al. (2020) proposed an effective feature extraction approach to capture the local and contextual information for occluded face recognition. Ke et al. (2021) addressed occlusion through explicit modelling of occlusion patterns in shape and appearance. Albalas et al. (2022) developed a model to detect occluded or masked faces based on fused spatial-based convolutional graphs of key facial features. However, they only focus on the occlusions in other natural scenes, rather than the more difficult occlusions on the face. ## 3 Methodology This paper introduces a four-point transform network (FTNet) with homogeneous Tanh-transforms for occluded face parsing. The homogeneous Tanh-transforms perform four Tanh-polar transforms based on four points of an image, so we also call it four-point transform, which will be explained in section 3.1. Given a face image of Cartesian coordinate and a bounding box of the target face, four-point transform warps the entire image into four Tanh-polar coordinate systems and stitches them together. The proposed four-point transform focuses on the non-occluded area of the target face to extract more robust spatial features under occlusion. The whole pipeline of our method is shown in Fig. 2. Our framework consists of four major components: 1) the four-point transform, which warps input face image of Cartesian coordinate into occlusion-aware Tanh-polar coordinate; 2) the backbone feature extraction module, which extracts informative features from the warped face for subsequent operations; 3) the parsing and restoring modules, which predict the segmentation scores through up-samplings on the feature map and restore the result into Cartesian coordinate; 4) the occlusion-aware loss, which introduces a penalty coefficient Figure 2: The overview of proposed FTNet structure. Given an input image and bounding box (in green), the four-point transform is applied to convert the RoI (in red) of input image to a new representation. The warped origin of input image (in white light) is defined as the corner of bounding box. The proposed occlusion-aware CNN is mainly composed of multiple Four-point Block (FPB) detailed in 3.2 to extract feature from the warped image. An occlusion-aware loss is designed to guide the warped parsing label prediction. Finally, the warped label is restored to the regular coordinate system. for the false prediction of occlusions. Next, each part will be introduced in detail. ### Homogeneous Tanh-transforms and Restore Previous face parsing works typically used face alignment techniques, which resulted in peripheral information loss (Liu et al., 2015). This is due to large variations in the target face's position, rotation, and size, and the network's input typically ignores the importance of the uncovered facial components. Traditional FCN can handle a large portion of face parsing, but its accuracy is limited, particularly when occlusion is present, due to a lack of focusing on each non-occluded individual part. To solve this problem, we propose homogeneous Tanh-transforms, called four-point transform, which warps the target face into Tanh-polar coordinate through four focusing points and makes precise parsing. Our warping approach transforms the entire image to the multiple homogeneous Tanh-polar representation, which expands the ratio of the region of interest (RoI) and compresses the background information, which lead to less data loss (Lin et al., 2019, 2021). Fig. 3 illustrates the process of the homogeneous Tanh-transforms. Given an image \(I\), as shown in Fig. 3, the RoI rectangle \(r=(x_{1}^{\prime},x_{2}^{\prime},x_{3}^{\prime},x_{4}^{\prime})\) is presented by multiplying the size of the bounding box \(b=(x_{1},x_{2},x_{3},x_{4})\) by a variable zoom factor \(l\) and all subsequent calculations are performed in the RoI region. Following the concept of warping, our method chooses four points as the original warping points, which chosen from the corner of bounding box \(b\). These points divide the entire image into four warping regions for Figure 3: The homogeneous Tanh-transforms pipeline, namely, four-point transform. (1) Input image, bounding box and the RoI area (2) Four warping regions according to four corners of bounding box (3) An example of the homogeneous Tanh-transforms in one warping area (4) The image in Tanh-Cartesian coordinate system and warping output in Tanh-polar coordinate system. Note that semi-transparent area which is out of RoI area do not participate in the calculation. four-point transform. According to the bounding box \(b=(x_{1},x_{2},x_{3},x_{4})\), calculate the width and height of \(r\): \(w=x_{2}-x_{1},h=y_{2}-y_{1}\). Then, the image that warped by four-point transform can be defined as: \[I^{{}^{\prime}}=FT(I,r)=P(W(I_{i},I_{j},w,h)),\forall I_{i}\in I_{x},\forall I_ {j}\in I_{y}\] where \(I^{\prime}\) is the warped image, \(FT\) is the function of four-point Transform, \(P\) is a bilinear interpolation function which can resample discrete coordinates of an image and project them onto determined coordinates system linearly by using a typical interpolation method (Jaderberg et al., 2015; Tai et al., 2019), and \(W\) is the mapping function that projects every pixel to the Tanh-polar coordinate. In general, the center of bounding box is considered as the original point. However, to determine the mapping function of four-point transform \(W(i,j,w,h)\) for each pixel \((i,j)\), it first need to transform the pixel position to make sure the original points are separately located at the four corners of bounding box. For an example, in the warping area 1 which highlighted in red in Fig. 3, the relative position \((i^{\prime},j^{\prime})\) of (i,j) is defined as: \[i^{{}^{\prime}}=i-\frac{i}{|i|}\frac{w}{2},j^{{}^{\prime}}=j-\frac{j}{|j|} \frac{h}{2}\] As Fig. 3 shows, the vector \((x,y)\) is parallel to the vector \((i^{\prime},j^{\prime})\), and \((x,y)\) is described by the canonical equation of the ellipse \(\frac{x^{2}}{a^{2}}+\frac{y^{2}}{b^{2}}=1\), whose major axes \(a=\frac{w}{2\sqrt{\pi}}\) and minor axes \(b=\frac{w}{2\sqrt{\pi}}\) are related to the height/width of the bounding box. Therefore, \(x\) and \(y\) satisfy the following equation: \[x^{2}=\frac{(\frac{w}{2\sqrt{\pi}})^{2}\cdot((\frac{h}{2\sqrt{\pi}})^{2}-y^{2} )}{(\frac{h}{2\sqrt{\pi}})^{2}}=\frac{w^{2}}{h^{2}}(\frac{h^{2}}{4\pi}-y^{2})\] Then, the Tanh-polar coordinate system by mapping function is defined as: \[W(i,j,w,h)=(\theta,\rho)=(\tanh(\frac{\mathrm{j}^{\prime}}{\mathrm{i}^{\prime }}),\tanh(\frac{\sqrt{\mathrm{i}^{\prime 2}+\mathrm{j}^{\prime 2}}}{\sqrt{\mathrm{a}^{2}+ \mathrm{b}^{2}}}))\] where \(\theta\), \(\rho\) are the polar angle and diameter, respectively. For the other three warping regions, the homogeneous Tanh-transforms are the same as described above. The only difference is the relative position \((i^{\prime},j^{\prime})\) when different corners are used as the origin of the coordinate system. Four transforms on the four warping regions constitute our four-point transform method. As shown in Fig. 3, the image \(I\) is warped into four parts after this mapping algorithm and then merged together. It maps each original Tanh-Cartesian coordinate system pixel to four Tanh-polar coordinate systems and then interpolates unmapped pixels. Each part focuses on one corner of the bounding box, and its area takes up the majority of the image. Though our homogeneous Tanh-transforms, fixed-size images with higher proportions of RoI regions can be produced. The transformed image contains all information inside the bounding box, and some losses occur outside of the bounding box, while enhancing the compressed information of non-RoI regions for use in feature extraction modules. For restore, it first recovers four split labels from four parts, then calculates and combines them based on a selected basis. However, because some duplicated warping areas exist in more than one part, as shown in Fig. 3, it is necessary to perform the following step to restore the transformation, which restore four individual sections that correspond to four parts in \[I=FT^{-1}(I^{{}^{\prime}},r)=P(W^{-1}_{combine}(W^{-1}(I^{{}^{\prime}}_{i},I^{{} ^{\prime}}_{j},w,h))),\forall I^{{}^{\prime}}_{i}\in I^{{}^{\prime}}_{x},\forall I ^{{}^{\prime}}_{j}\in I^{{}^{\prime}}_{y}\] where \(W^{-1}_{combine}\) combines these four sections, then the selected basis calculates and combines overlapped areas. In our system, the mean function is chosen as our base calculation. Figure 4: Comparison of original image and restored image. Observing that outside the RoI area, some information losses. Fig. 4 provides the comparison between the original image \(I\) and the restored image \(W^{(}-1)W(I)\). As the figure illustrates, we can observe that \(W^{(}-1)W(I)\) restores most of the information in the RoI area, and other areas are basically recovered. Although some losses happen in the areas outside of RoI, the losses are limited since most important labels are inside the RoI area for face parsing. ### Four-point Block Given the warped face image \(W(I,r)\), which contains the compressed information of whole image through the four-point transform, the backbone feature extraction modules are deployed to capture implicit features under Tanh-polar coordinate. However, although the information of the rotation equivariance can be preserved, four-point transform may face a risk of losing the translation equivariance. Therefore, we upgrade the original residual block of feature extraction to a new building block, called Four-point Block. It is able to extract features more efficiently in a Tanh-polar coordinate. Fig. 2 illustrates the branch structure of the FPB in detail. The four-point branch in Tanh-polar coordinate system learns the rotation equivariant representation. The Tanh-Cartesian branch, which transforms feature maps into Tanh-Cartesian coordinate systems, learns the translation equivariant representation, so as to achieve the fundamental purpose of complementary learning. The Tanh-Cartesian coordinate system can be defined by \[TC(\vec{v}):=\tanh(\frac{\mathrm{i}^{\prime}}{\sqrt{\mathrm{x}^{2}+\mathrm{y}^ {2}}})\mathrm{tanh}(\frac{\mathrm{j}^{\prime}}{\sqrt{\mathrm{x}^{2}+\mathrm{ y}^{2}}})\] where \(TC(i,j)\) is the function of Tanh-Cartesian transform. The input to FPB is a four-point representation \(X_{fp}\) of shape \((h,w,c)\). The residual path uses a stack of \(1\times 1\), \(3\times 3\) and \(1\times 1\) convolutions following the bottleneck design (He et al., 2016). The first \(1\times 1\) conv layer is used to reduce the channel dimension. Its output feature maps are divided into two branches as described above. In Tanh-Cartesian branch, the feature maps are split back to four four-point warping regions and transformed to the Tanh-Cartesian space, respectively. In Tanh-cartesian coordinate system, four \(1\times 1\) conv layers are used to compute these four-point feature maps, which then are transformed to the Tanh-polar space through four-point transform and merged together. In four-point branch, a \(3\times 3\) conv layer is used to compute feature maps in Tanh-polar space. Then, the feature maps from these two branches are multiplied in Tanh-polar coordinate system. The last \(1\times 1\) conv layer restores the channel dimension so the residual representation can be added to the input \(X_{fp}\). ### FTNet Architecture Through homogeneous Tanh-transforms, namely, four-point transform, the input image of the Tanh-polar coordinate system is obtained which compresses more RoI key information and surrounding semantics. For a higher quality feature extraction module fusing the advantage of Tanh-Cartesian and Tanh-polar representation, we propose FPB for composing our new backbone network, four-point transform network (FTNet). FPBs are stacked according to the structure of ResNet to build FTNet for feature extraction. Thanks to the grouped conv \(1\times 1\) and the conv \(3\times 3\) with halved channels, the overall number of parameters are less than the ResNet50 backbone. To predict the masks, we use the FCN-8's (Long et al., 2015) decoder. More advanced decoders necessitate dedicated hyperparameter tuning, which can significantly affect performance. To map the feature maps to pixel-wise prediction logits, the decoder employs two conv \(3\times 3\) layers and a bilinear up-sampling layer. Each component of the transformed image is invertible in theory. ### Occlusion-aware Loss Based on homogeneous tanh-transforms, we design an occlusion robust network as described above, namely FTNet. The focus of the loss function used in the current face parsing field is mainly on the classification of pixels, while ignoring the adverse effects of masks, glasses and other occlusions. Therefore, to train our FTNet, an especial occlusion-aware loss is introduced to further address the face occlusion problem in face parsing. Furthermore, in order to better focus on occlusion semantic information, different weights are assigned to occluded pixels and non-occluded pixels in contrast to treating all pixel equally as the shape of the parsed face will be destroyed by occlusion. So, the loss weight of the pixels in the occluded face region are increased which added as the constraints of the loss function as follows, \[L_{FTNet}=l\cdot L_{ce}+(1-l)L_{dice}+\alpha\frac{1}{N}\sum_{i}P(g_{i}^{f})||g_{ i}^{f}-s_{i}^{f}||_{2}^{2}\] where \[L_{ce}=\frac{1}{N}\sum_{i}\sum_{c}g_{i}^{c}\log s_{i}^{c}\] \[L_{dice}=1-\frac{2\sum_{i}\sum_{c}g_{i}^{c}s_{i}^{c}}{\sum_{i}\sum_{c}g_{i}^{c2}+ \sum_{i}\sum_{c}s_{i}^{c2}}\] Here, \(N\) is the total training samples of a batch, \(\alpha\) is the hyperparameters of constraints, \(g_{i}^{c}\) denotes the ground truth of class \(c\) in \(i\)-th sample, \(s_{i}^{c}\) denotes the predicted probability of class \(c\) in \(i\)-th sample, \(f\) denotes the face skin class, \(P(g_{i}^{f})\) is the occlusion value of \(g_{i}^{f}\) calculated from the mean of itself and the surrounding 8 pixels (\(P(g_{i}^{f})\) is high when \(g_{i}^{f}\) is occluded) and the weight \(l\) is determined by the average point to curve Euclidean distance among points around curve of predicted segmentation to the ground truth. ## 4 Experimental Evaluation ### Implementation Details **Dataset**. We perform experiments on a new dataset called Sheltered Face Parsing Dataset (SFPD). SFPD has 52097 images, collected from CelebAMaskHQ (Lee et al., 2020), the Short-video Face Parsing (denoted as SVFP) (maadaa.ai, 2021), and the HELEN dataset (Le et al., 2012) which contains facial occlusion challenges. Table 1 compares the number of different datasets and illustrates that SFPD contains in-the-wild images and more occluded images which is of higher difficulty to face parsing. The collected images are carefully screened for no watermarks or blurring, and manually reannotated to eliminate label discrepancies. Furthermore, SFPD is more concerned with facial occlusions which presented by elaborate pixel-wise annotation, including 9 general face part categories and 3 additional face occlusion categories (i.e., sunglasses, eyeglasses and face mask). Note that the hand occlusion is directly reflected on the face skin annotation and are not classified as a separate occlusion category. The images are divided into 42097 samples for training, 5000 for validation and 5000 for testing, respectively. **Training**. Our method is implemented on PyTorch and trained on two Tesla V100S GPUs. For data preparation, we apply data augmentation techniques for all the training samples to avoid over-fitting, e.g., random rotation and scale augmentation. The rotation angle is randomly selected from \((-30^{\circ},30^{\circ})\), while the scale factor is randomly selected from \((0.75,1.25)\). During training, our four-point transformed images are warped from original images and resized to \(512\times 512\). For our proposed occlusion-aware loss, the hyperparameters \(\alpha\) is set to 2. For optimization, we adopt the Stochastic Gradient Descent (SGD) and we use the poly learning rate schedule (Chen et al., 2017), \(lr^{*}=(1-\frac{iter}{max\_iter})^{p}\), \(p=0.9\), in which the initial \(lr\) is \(0.01\). The \(max\_iter\) is \(epochs\times batchsize\), where \(batchsize=8\) and \(epochs=50\). **Evaluation**. All the testing procedures are carried out on a single Tesla V100S GPU. For each test sample, the size of the predicted labels is set to \(512\times 512\) and scaled to original size for visualization. For evaluation, we report F1 score (F1) for all categories and their mean. The predicted masks are evaluated on the original image scale. The F1 can be represented by the formula as follow: \[F=\frac{2\text{Precision}\cdot\text{Recall}}{\text{Precision}+\text{Recall}}\] ### Comparisons The thorough comparisons are performed between our model and 6 state-of-the-arts (i.e., Wei et al. (2019), Lin et al. (2019), Masi et al. (2020), Lin et al. (2021), Huang et al. (2021), and Kim et al. (2022)) on our dataset in Tab. 2. Lin et al. (2019) and Lin et al. (2021) are related to our work which also adopt image transform, while other methods (Wei et al., 2019; Masi et al., 2020; Huang et al., 2021; Kim et al., 2022) are currently performing well in face parsing. These methods focus on the related to the shape of facial components to improve the face parsing performance, in detail, including consistent based learning mechanism (Wei et al., 2019; Masi et al., 2020), and attention based feature extraction (Huang et al., 2021; Kim et al., 2022). Results are measured by F1 which is commonly used by existing face parsing literature. We show the comparison results on SFPD in Table 2. Each column shows the F1 percentage corresponding to a specific face label, including our reannotation and the overall F1-score as well. \begin{table} \begin{tabular}{c c c c} \hline \hline Benchmark & images & In-the-wild & occluded images \\ \hline CelebAMask-HQ & 27176 & \(\times\) & 828 \\ SVFP & 19445 & \(\checkmark\) & 974 \\ Helen & 2000 & \(\checkmark\) & 60 \\ Ours & 42097 & \(\checkmark\) & 1381 \\ \hline \hline \end{tabular} \end{table} Table 1: The comparison of training set of face parsing datasets. Our FTNet achieves a huge boost in average F1 (2.37 % better than the second best method Kim et al. (2022), and 2.80 % better than the third best method Lin et al. (2021)). In term of the occlusions, our model surpasses the second best by 3.66, 2.31, 8.5 % on eyeglasses, sunglasses and face mask, respectively. As shown in Tab.2, Lin et al. (2021) outperforms our model in skin and inner mouth parsing, however, it falls far short of our model in face mask occlusion (by 8.5). This is because Lin et al. (2021) perform the center as the origin of the transform. As in the illumination theory, the radiation \begin{table} \begin{tabular}{c c c c c c} \hline \hline Methods & skin & l\_brow & r\_brow & l\_eye & r\_eye \\ \hline Wei et al. (2019) & 92.54 & 90.14 & 85.65 & 83.44 & 92.69 \\ Lin et al. (2019) & 91.17 & 88.85 & 84.95 & 92.49 & 91.23 \\ Masi et al. (2020) & 90.47 & 89.16 & 85.21 & 92.07 & 91.39 \\ Lin et al. (2021) & **93.93** & 90.70 & 90.10 & 85.12 & 94.84 \\ Huang et al. (2021) & 90.26 & 89.23 & 85.13 & 90.14 & 90.72 \\ Kim et al. (2022) & 92.68 & 91.20 & 91.05 & 91.18 & **95.77** \\ \hline FTNet(Ours) & 91.77 & **94.31** & **93.26** & **92.71** & 91.50 \\ \hline \hline Methods & nose & u\_lip & l\_lip & inner\_mouth & eye\_glasses \\ \hline Wei et al. (2019) & 90.84 & 85.40 & 82.73 & 93.41 & 90.73 \\ Lin et al. (2019) & 88.75 & 85.76 & 91.85 & 92.09 & 89.39 \\ Masi et al. (2020) & 86.97 & 83.98 & 89.81 & 91.63 & 88.09 \\ Lin et al. (2021) & 90.25 & 90.96 & 84.28 & **95.59** & 89.75 \\ Huang et al. (2021) & 88.48 & 83.39 & 89.47 & 91.07 & 88.46 \\ Kim et al. (2022) & 86.62 & 90.06 & 83.74 & 96.14 & 90.59 \\ \hline FTNet(Ours) & **93.97** & **92.56** & **92.60** & 92.22 & **93.41** \\ \hline \hline Methods & sunglasses & mouth\_mask & overall & & \\ \hline Wei et al. (2019) & 85.71 & 82.08 & 87.95 & & \\ Lin et al. (2019) & 85.70 & 91.13 & 89.45 & & \\ Masi et al. (2020) & 84.37 & 90.15 & 88.61 & & \\ Lin et al. (2021) & 91.16 & 84.25 & 90.08 & & \\ Huang et al. (2021) & 84.96 & 90.22 & 88.54 & & \\ Kim et al. (2022) & 91.68 & 85.45 & 90.51 & & \\ \hline FTNet(Ours) & **93.47** & **92.75** & **92.88** & & \\ \hline \hline \end{tabular} \end{table} Table 2: Comparison with state-of-the-art methods on SFPD. F1 scores are represented in percentage. range of the surface light source is better than that of the point light source, so that the performance of their model will greatly reduce when the center is occluded, such as face mask occlusion. However, under such occlusion, our method can utilize the homogeneous tanh-transforms of the four corners to alleviate the adverse effect of occlusion on face parsing. The testing results on SFPD show that our method outperforms all state-of-the-art methods. As Table 2 shows, our model achieves slightly better performance on face parts while significantly outperforms others on occlusions since our method has a strong capability to occlusion. Such performance gains are particularly impressive considering that improvement on our dataset is very challenging. ### Ablation Study To demonstrate how each component in our FTNet contributes to the performance, a series of ablation experiments are conducted on SFPD using F1 metric. As the proposed homogeneous Tanh-transforms, i.e., four-point transform, provides a more general and powerful form of image representation, we first quantity the effectiveness of each essential component of FTNet (Section 4.3.1), and then perform in-depth analyses of homogeneous tanh-transforms (Section 4.3.2). This would better verify our main points and coincide with the experiments in prior conference papers. The training and evaluation followed the same protocol as in Section 4.1. #### 4.3.1 Ablation Study for Each Component of FTNet Table 3 shows the evaluation of our FTNet compared to ablated version without certain key components, including homogeneous Tanh-transform, four-point block, occlusion-aware loss. \(V_{1}\) denotes the ablated version without homogeneous tanh-transforms, \(V_{2}\) denotes the ablated version without four-point block, \(V_{3}\) denotes the ablated version without occlusion-aware loss and \(V_{0}\) denotes the full FTNet. All the variants are retrained independently with their specific architectures. we report their average performance on face parts and occlusions (i.e., sunglasses, eyeglasses, face mask) respectively. _Homogeneous tanh-transforms_.Consider the first rows in Table 3, we can find that the homogeneous tanh-transforms provides substantial performance gain. Note that the ablated network uses the original image as the input directly instead of four-point transformed image. This demonstrates the benefit of four-point transform and Tanh-polar representation in occluded face parsing. _Four-point block._ Instead of original block in backbone, four-point block can also bring a performance gain (85.28-92.76 for face parts, 85.16-93.21 for occlusion). This suggests that feature fusion of Tanh-Cartesian and Tanh-polar coordinate systems enables comprehensive understanding of facial occlusion semantics. _Occlusion-aware loss._ Comparing the performance of our full FTNet and the ablated version without occlusion-aware loss, we can conclude that the occlusion-aware loss boosts performance, as the occluded face margin can be con-strained. This also provides a new glimpse into the learning objective and constraint for occlusion handling. #### 4.3.2 In-depth Analyses for Homogeneous Tanh-transforms In above section, we investigate the necessity of comprehensive exploring homogeneous tanh-transforms and the other component of FTNet. Next,we discuss the effectiveness of the homogeneous Tanh-transforms representation. Concretely, we studied three related transforms, as list in Tab. 4: 1) resize, 2) Tanh-Cartesian transform by (Lin et al., 2019), 3) Tanh-Polar transform by (Lin et al., 2021), 4) No transform. All transforms are applied to the dataset before extracting features to constitute the variant model. All five variant models use same backbone and other training parameters. We also evaluate these five models on masked images, then check the dice loss, our loss and \begin{table} \begin{tabular}{c c c} \hline \hline Network & F1 for face parts & F1 for occlusions \\ \hline full FTNet \(V_{0}\) & & \\ (homogeneous tanh-transforms & & \\ + four-point block & 92.76 & 93.21 \\ + occlusion-aware loss) & & \\ ablated FTNet \(V_{1}\) & & \\ (four-point block & 85.46 & 83.43 \\ + occlusion-aware loss) & & \\ ablated FTNet \(V_{2}\) & & \\ (homogeneous tanh-transforms & 86.71 & 88.31 \\ + occlusion-aware loss) & & \\ ablated FTNet \(V_{3}\) & & \\ (homogeneous tanh-transforms & 85.28 & 85.16 \\ + four-point block) & & \\ \hline \hline \end{tabular} \end{table} Table 3: Result on Different Transform. F1 scores are represented in percentage. the F1 score for face parts or occlusions. We can draw a main conclusion that our homogeneous tanh-transforms, i.e., four-point trans-form, helps with semantic learning of occluded faces as our full model is significantly better than the one without four-point transform which further proves the generality of our method. ### Qualitative Results Finally, we compare the proposed FTNet with two most related competitors (i.e., RoI Tanh-warping (Lin et al., 2019) and RoI Tanh-polar (Lin et al., \begin{table} \begin{tabular}{c c c} \hline \hline Transform & face parts & sheltered areas \\ \hline None & 80.75 & 73.79 \\ Resize & 74.56 & 70.39 \\ Tanh-Cartesian transform & 82.66 & 79.03 \\ Tanh-Polar transform & 85.75 & 81.37 \\ four point transform(Ours) & **92.76** & **93.21** \\ \hline \hline \end{tabular} \end{table} Table 4: Result on Different Transform. F1 scores are represented in percentage. Figure 5: Qualitative comparisons in cropped images between previous methods RoI Tanh-warping (Lin et al., 2019), RoI Tanh-polar (Lin et al., 2021) and ours on the SFPD. The proposed four-point transform addressed the typical occlusion, including sunglasses, eyeglasses, hand and face mask. Figure 6: Qualitative comparisons in wild scenes between previous methods RoI Tanhwarping (Lin et al., 2019), RoI Tanh-polar (Lin et al., 2021) and ours. Figure 7: Qualitative results on other challenging images with complicate occlusions. 2021)) on SFPD. Some qualitative comparison results on the cropped images are depicted in Fig. 5. We can see that our approaches output more precise parsing results than other competitors under the occlusions, including sunglasses, eyeglasses, hand and face mask. Neither RoI Tanh-warping (Lin et al., 2019) nor RoI Tanh-polar (Lin et al., 2021) can precisely parse face parts under all occlusion conditions. The performance of these two methods can be accepted under sunglasses and eyeglasses (2nd column), because this kind of occlusion differ greatly from the skin color and can be easily distinguished in most cases. However, when the occlusion prone to skin color confusion occurs, such as face masks and hands, these methods are prone to parsing errors and far inferior to our proposed method. In addition, with its better leveraging of illumination theory, our four-point transform eliminates the interference from the occlusion and gets more robust results. The qualitative comparisons on the complete scene image are shown in Fig. 6 and Fig. 7 gives some other challenging case, where our FTNet still correctly recognizes the confusing parts of the person under occlusion. The qualitative results show that the significant improvement brought by our FTNet in parsing occluded faces. ### Failure Case Analysis To give a deeper insight into our method, we present two representative failure cases in Fig. 8. As seen our proposed model face difficulties with low quality images or low-light occluded scenes. In the future, we will therefore focus on addressing these issues. Figure 8: Visualizations of typical failure cases on SFPD test set, including (a) low-quality images, (b) low-light images. ## 5 Conclusion In this paper, we propose a novel occlusion-aware network combined with homogeneous tanh-transforms for occluded face parsing, namely, four-point trans-form neural network FTNet. We use four-point transform to warp the image to four Tanh-polar coordinate systems, which provides a high anti-occultation ability. Our occlusion-aware network utilizes receptive fields of different shapes for warped images, while compressing more information of surrounding context. Moreover, an occlusion-aware loss also enhances the robustness of the model to occluded face parsing. Ablation studies show the effectiveness of four-point transform and our proposed method. The superior performance show that we have solved the dilemma of face parsing on occluded faces in most wild scenes and our method is highly capable on face parsing tasks with face coverings. In the future work, we would like to focus on the addressing difficult case, including low-quality and low-light images, as well as apply our method into other occluded image segmentation tasks, such as human parsing and object segmentation.
2304.03694
High Accuracy Uncertainty-Aware Interatomic Force Modeling with Equivariant Bayesian Neural Networks
Even though Bayesian neural networks offer a promising framework for modeling uncertainty, active learning and incorporating prior physical knowledge, few applications of them can be found in the context of interatomic force modeling. One of the main challenges in their application to learning interatomic forces is the lack of suitable Monte Carlo Markov chain sampling algorithms for the posterior density, as the commonly used algorithms do not converge in a practical amount of time for many of the state-of-the-art architectures. As a response to this challenge, we introduce a new Monte Carlo Markov chain sampling algorithm in this paper which can circumvent the problems of the existing sampling methods. In addition, we introduce a new stochastic neural network model based on the NequIP architecture and demonstrate that, when combined with our novel sampling algorithm, we obtain predictions with state-of-the-art accuracy as well as a good measure of uncertainty.
Tim Rensmeyer, Benjamin Craig, Denis Kramer, Oliver Niggemann
2023-04-05T10:39:38Z
http://arxiv.org/abs/2304.03694v1
High Accuracy Uncertainty-Aware Interatomic Force Modeling with Equivariant Bayesian Neural Networks ###### Abstract Even though Bayesian neural networks offer a promising framework for modeling uncertainty, active learning and incorporating prior physical knowledge, few applications of them can be found in the context of interatomic force modeling. One of the main challenges in their application to learning interatomic forces is the lack of suitable Monte Carlo Markov chain sampling algorithms for the posterior density, as the commonly used algorithms do not converge in a practical amount of time for many of the state-of-the-art architectures. As a response to this challenge, we introduce a new Monte Carlo Markov chain sampling algorithm in this paper which can circumvent the problems of the existing sampling methods. In addition, we introduce a new stochastic neural network model based on the NequIP architecture and demonstrate that, when combined with our novel sampling algorithm, we obtain predictions with state-of-the-art accuracy as well as a good measure of uncertainty. ## 1 Introduction Despite the fact that the laws of quantum mechanics, which underly chemistry, were discovered almost a century ago, their application for the _ab initio_ prediction of many chemical phenomena remains a formidable task [1, 2]. This is in large parts a result of the sheer computational complexity involved in solving these equations numerically as well as the enormous phase space that needs to be considered[1, 2]. Molecular dynamics (MD), where the time evolution of molecular systems is investigated, is particularly affected by this challenge. While computational methods such as Density Functional Theory (DFT) have been developed that can calculate interatomic forces with very high accuracy, these methods are in general computationally expensive and scale badly with growing system sizes. Thus, it remains very difficult to model larger systems with high accuracy and a large enough time horizon. To circumvent these difficulties, the learning of interatomic forces via machine learning models such as neural networks has become a highly active area of research [3]. However, the cost of generating training data from _ab initio_ simulations prevents the generation of large training sets commonly required to construct sufficiently predictive neural networks. Recent innovations in neural network designs have already made it possible to learn highly accurate interatomic force fields for a given compound with limited data by incorporating hard constraints in the form of symmetry properties and energy conservation into the model architecture [4, 5, 6, 7, 8, 9]. However, training models to have chemical accuracy for entire classes of compounds still requires large amounts of data [4, 5, 8, 9], owing in large part to the vastness of the space of possible atomic configurations. The creation of predictive and transferable models is, therefore, still a challenging task. Additionally, the existing state-of-the-art models generally lack a measure of uncertainty in their prediction [3, 10], which makes it impossible to tell which of the predictions are reliable. This limits the applicability of active learning strategies, where uncertainty can be used to select useful training data from the large configuration space more efficiently [11, 12, 13, 14, 15] by only labeling outlier configurations where the model predicts a high likelihood of a large error. Further, for a deployed model detected outliers can either be recomputed on-the-fly in DFT to ensure the accuracy of a neural network-based MD trajectory or used to retroactively discard trajectories that are likely to be physically inaccurate. All of these factors hinder their extension towards more general models, required for the prediction and optimization of complex (dynamic) properties of materials, where a vast amount of diverse atomic configurations need to be screened with an overall high accuracy and a good measure of uncertainty. The latter can be used to decide which of the samples that are predicted, should undergo additional investigation through _ab initio_ calculations or experiments and which are likely to be false positives. An uncertainty measure is also attractive to ensure high accuracy of modeling rare events that often govern longer time-scale dynamics, but are seriously under-represented in MD trajectories [14]. Configurations close to transition states are exponentially less likely to be sampled relative to near ground-state configurations. But these states often have peculiar electronic configurations and bonding characteristics that do not feature in low energy configurations. Hence, an uncertainty measure would allow on-the-fly identification of configurations that require additional learning to bias active learning strategies towards relevant "new chemistry" such as transition states. Furthermore, many existing state-of-the-art models are currently optimized in a somewhat intricate way on smaller datasets to improve performance, where artificial noise is introduced to the optimization process via a large learning rate and small batch size [4, 5, 6, 7, 9]. While this works well empirically, there is no established theoretical foundation for the utility of such optimization and consequently, there is no guide in choosing appropriate batch sizes and learning rates except trial and error. As a response to these challenges, we investigate here the viability of combining Bayesian Neural Networks (BNNs) with state-of-the-art neural networks for modeling interatomic forces, as BNNs have a robust measure of uncertainty and an inherent principled way of adding noise to the optimization process via Monte Carlo Markov Chain (MCMC) methods. Further, they offer a good framework for the incorporation and data-based updating of prior beliefs, such as approximate physics-guided interatomic force-fields, which may be utilized in the future to further improve data efficiency and generalization. However, we found that current off-the-shelf MCMC methods are unsuited for dealing with the vastly different gradient scales that different parameter groups exhibit in modern models. This results in an unpractically slow traversal through the parameter space to the point where no convergence is achievable in reasonable amounts of time, which explains their current lack of use. Hence, a new MCMC algorithm is needed for high-quality Bayesian uncertainty quantification with neural network-based interatomic force models. The contributions of this paper are the following: * We develop a new stochastic neural network model based on the NguuIP architecture [7] for uncertainty-aware interatomic force modeling with state-of-the-art accuracy. * We provide a novel Bayesian MCMC algorithm that produces high-accuracy models with high-quality uncertainty estimates in a practical amount of time without relying on finetuned batch sizes and learning rates. * We show that the current optimization methods based on high learning rates and small batch sizes already mimic Bayesian MCMC methods to a degree. * We discuss shortcomings as well as possible further improvements and extensions of the proposed neural network model and sampling algorithm. Notation commonly used in this paper is summarized in Table 1. ### Related Work While BNNs to date have found very few applications in this context, some use cases exist in the literature [15, 16, 17, 18]. However, in [16, 17] Monte Carlo dropout was used for Bayesian inference. While this method can in some instances be interpreted as Bayesian variational inference [19], it yields a poor approximation of the true posterior distribution even for variational inference-based methods [19] and typically results in much poorer uncertainty quantification than MCMC methods [20]. While a much more accurate Bayesian algorithm was used in [15], the use case was very limited in scope to diatomic systems. Further, all of the above instances were limited to very small fully connected neural networks while we utilize a state-of-the-art graph neural network-based architecture. We only found one attempt to reconcile graph neural network-based architectures with sampling schemes based on simulating a stochastic process in the literature. This was done in a recently published preprint by Thaler et al. [18]. However, they failed to get competitive results while attempting to sample the Bayesian posterior and had to resort to sampling an artificially sharpened distribution. Even then they found that to reliably quantify uncertainty, they had to generate samples from multiple different stochastic processes while we generate samples from a single Markov chain. ## 2 The Base Model ### The Formal Setting The aim of the neural network-based interatomic force model is to map a configuration of atoms \(\boldsymbol{x}=\{(\boldsymbol{r}_{1},z_{1}),...,(\boldsymbol{r}_{n},z_{n})\}\), where \(\boldsymbol{r}_{i}\) denotes the position of the nucleus of atom \(i\) and \(z_{i}\) refers to its nuclear charge, to the forces \(\{\boldsymbol{F}_{1},...,\boldsymbol{F}_{n}\}\) acting on the individual nuclei. \begin{table} \begin{tabular}{|c|c|} \hline **Notation** & **Meaning** \\ \hline Bold case symbol & Vector-valued quantities \\ \(N(\boldsymbol{\mu},\Sigma)\) & Normal distribution \\ \(\boldsymbol{N}(\boldsymbol{\mu},\Sigma)\) & Random variable \(N(\boldsymbol{\mu},\Sigma)\) \\ \(\boldsymbol{F}\) & Potential energy \\ \(D\) & The dataset \\ \(l\) & The identity matrix \\ \(\boldsymbol{\theta}\) & Neural network parameters \\ \(\boldsymbol{x}\) & Independent variable \\ \(y\) & Dependent variable \\ \(\boldsymbol{y}|\boldsymbol{x}\) & \(\boldsymbol{y}\) conditioned on \(\boldsymbol{x}\) \\ \(r\) & Atomic coordinates \\ \(z\) & Nuclear charges \\ \(\boldsymbol{ab}\) & Element-wise product of \(\boldsymbol{a}\) \\ & and \(\boldsymbol{b}\) \\ \hline \end{tabular} \end{table} Table 1: Commonly used notation These forces are then used to simulate the movement of the nuclei based on Newton's equations of motion via a solver for Ordinary Differential Equations (ODEs) (Figure 1). One important aspect of this form of data is, that it is unstructured, meaning the order in which the atoms are enumerated is arbitrary. A suitable neural network model should therefore be equivariant under a reordering of the data. Another important constraint is, that these forces are conservative and can therefore be derived as the negative gradients of a single potential energy surface \[\boldsymbol{F}_{i}=-\nabla_{\boldsymbol{r}_{i}}E((\boldsymbol{r}_{1},z_{1}),...,(\boldsymbol{r}_{n},z_{n})).\] The potential energy surface itself is invariant under any distance preserving transformation of the atomic coordinates. This was at first incorporated into neural network models by using only the interatomic distances \(r_{ij}\) and nuclear charges as input, which have these invariances themself. Even though it is in principle possible to extract directional information from the set of interatomic distances, in practice incorporating directional information explicitly can improve data efficiency and accuracy quite a lot [10] and has become a key feature of many state-of-the-art neural network models [4, 5, 6, 8, 7, 9]. ### The NequIP Model One of the most powerful neural network models for interatomic force modeling that currently exists is the NequIP model [7] (Figure 2). This model takes all the previous considerations into account and consists of a model base and projection layers. The model base maps an atomic configuration \(\{(\boldsymbol{r}_{1},z_{1}),...,(\boldsymbol{r}_{n},z_{n})\}\) to a set of high dimensional latent feature vectors \(\{\boldsymbol{v}_{1},...,\boldsymbol{v}_{n}\}\) that are invariant under distance-preserving transformations. The projection layers then map \(\{(\boldsymbol{v}_{1},z_{1}),...,(\boldsymbol{v}_{n},z_{n})\}\) to (virtual) atomic energies \(\{E_{1},...,E_{n}\}\). The potential energy \(E\) is then calculated as the sum of the atomic energies. Finally, the forces acting on the nuclei are then calculated as the negative gradients of the potential energy with respect to the nuclear coordinates. The last step can be achieved straightforwardly using the automatic differentiation functionalities of modern deep-learning libraries. ## 3 The Bayesian Model ### Bayesian Neural Networks The goal of classical neural network optimization is to find a single set of parameters, i.e. weights and biases, which models the underlying data distribution, from which the training data was sampled, well. In the Bayesian approach, in contrast, the parameters of the neural network are modeled probabilistically. To keep the notation simple, we use \(\boldsymbol{\theta}\) to denote a vector containing a complete set of neural network parameters. For BNNs it is assumed that some prior knowledge exists about what constitutes a good set of parameters, which is expressed in the form of a prior density \(p(\boldsymbol{\theta})\). This prior density then gets refined through the training data \(D=\{(\boldsymbol{x}_{1},\boldsymbol{y}_{1}),...,(\boldsymbol{x}_{l}, \boldsymbol{y}_{l})\}\) by invoking Bayes rule for calculating the posterior density: \[p(\boldsymbol{\theta}|D)=\frac{p(D|\boldsymbol{\theta})p(\boldsymbol{\theta}) }{p(D)}=\frac{p(D|\boldsymbol{\theta})p(\boldsymbol{\theta})}{\int p(D| \boldsymbol{\theta})p(\boldsymbol{\theta})d\boldsymbol{\theta}}.\] A prediction on a new data point \((\boldsymbol{x},\boldsymbol{y})\) can now be made via: \[p(\boldsymbol{y}|\boldsymbol{x},D)=\int p(\boldsymbol{y}|\boldsymbol{x}, \boldsymbol{\theta})p(\boldsymbol{\theta}|D)d\theta\] \[=\mathbb{E}_{p(\boldsymbol{\theta}|D)}\left[p(\boldsymbol{y}|\boldsymbol{x}, \boldsymbol{\theta})\right].\] For BNNs this integral is almost always analytically intractable. However, by generating samples \(\boldsymbol{\theta}_{1},...,\boldsymbol{\theta}_{k}\) from \(p(\boldsymbol{\theta}|D)\) it can be estimated through the law of large numbers as: \[p(\boldsymbol{y}|\boldsymbol{x},D)\approx\frac{1}{k}\sum_{i=1}^{k}p( \boldsymbol{y}|\boldsymbol{x},\boldsymbol{\theta}_{i}).\] ### The Stochastic Model In order to achieve state-of-the-art accuracy combined with a good measure of predictive uncertainty in modeling interatomic forces, a new stochastic neural network model is required, which we will introduce in this section. To build a stochastic model of the data, we make the following assumptions on the conditional independence of the data: \[p(D) =p(\boldsymbol{y}_{1},...,\boldsymbol{y}_{l}|\boldsymbol{x}_{1},...,\boldsymbol{x}_{l})p(\boldsymbol{x}_{1},...,\boldsymbol{x}_{l})\] \[=p(\boldsymbol{x}_{1},...,\boldsymbol{x}_{l})\Pi_{i=1}^{l}p( \boldsymbol{y}_{i}|\boldsymbol{x}_{i}).\] Figure 1: An illustration of a molecular dynamics workflow with neural network predictions for the forces. \(p(\mathbf{y}_{i}|\mathbf{x}_{i})\) will be inferred by a neural network as \(p(\mathbf{y}_{i}|\mathbf{x}_{i},\mathbf{\theta})\) while \(p(\mathbf{x}_{1},...,\mathbf{x}_{l})\) depends on the data generation process. More specifically we model the conditional densities \[p(\mathbf{y}|\mathbf{x},\mathbf{\theta})=p(E,\mathbf{F}_{1},...,\mathbf{F}_{n}|(\mathbf{r}_{1},z_{1}),...,(\mathbf{r}_{n},z_{n}),\mathbf{\theta})\] as \[\mathbf{y}|\mathbf{x},\mathbf{\theta}\sim N(\mu_{E }(\mathbf{\theta},\mathbf{x}),\sigma_{E}^{2}(\mathbf{\theta},\mathbf{x}))\] \[\times\Pi_{i=1}^{n}N(\mathbf{\mu}_{Fi}(\mathbf{\theta}, \mathbf{x}),\sigma_{\mathbf{F}_{i}}^{2}(\mathbf{ \theta},\mathbf{x})I),\] where \(\mathbf{y}|\mathbf{x},\mathbf{\theta}\) denotes \(y\) conditioned on \(x\) and \(\theta\), \(\mathbf{x}=\{(\mathbf{r}_{1},z_{1}),...,(\mathbf{r }_{n},z_{n})\}\), the means \(\mu_{E}(\mathbf{\theta},\mathbf{x})\) and \(\mathbf{\mu}_{Fi}(\mathbf{\theta},\mathbf{x})\) are the regular point predictions of the NequIp model, the standard deviations \(\sigma_{E}(\mathbf{\theta},\mathbf{x})\) and \(\sigma_{\mathbf{F}_{i}}(\mathbf{\theta},\mathbf{x})\) are predicted by two separate Multi-Layer Perceptrons (MLPs) from the outputs of the NequIp base \(\mathbf{v}_{1},...,\mathbf{v}_{n}\) and \(I\) denotes the identity matrix (Figure 3). Note that a single invariant standard deviation is calculated for all three force components to ensure equivariance of the predicted density under any distance-preserving transformation of the atomic coordinates. We include the potential energy \(E\) here as an additional dependent variable because it can be useful in applications such as the determination of ground state configurations and is calculated as a byproduct of force calculations in DFT anyway. Lastly, we use the simple Gaussian mean field prior \(\mathbf{\theta}\sim N(\mathbf{0},I)\). ### Sampling from the Posterior Distribution Generating high-quality sample weights from the posterior distribution is usually done via the simulation of a Markov chain which converges in distribution to the posterior. While several Markov chains methods have been constructed for neural network applications, we found them unsuitable for this use case. The main difficulty we encountered was, that the scale of the gradients with respect to the different sets of parameters corresponding to the different layers of the neural network vary by several orders of magnitude. This makes the use of a single step size for all parameters impossible, as it would cause the sets of parameters with smaller gradients to be frozen during the optimization. While modern neural network optimizers circumvent this problem through an adaptive step size for each parameter [21], this is only possible to a very limited degree for Markov chains [22] without changing the stationary distribution to which they converge. Furthermore, this typically requires the calculation of higher-order derivatives [22] which is computationally expensive. To deal with these challenges, we develop here a new approach to sampling the posterior distribution based on the Stochastic Gradient Hamiltonian Monte Carlo (SGHMC) algorithm introduced by Chen et al. [23]. In its basic form, the algorithm is given by the Markov chain \[\Delta\mathbf{w}_{t}=-\left(\nabla_{\mathbf{ \theta}_{t}}u(\mathbf{\theta}_{t})+\mathbf{M}^{-1}\mathbf{C}\mathbf{w}_{t-1}\right)\Delta t+\sqrt{2\mathbf{C$ }\Delta t}\mbox{\boldmath$\mathcal{N}}_{t}(\mathbf{0},I),\] \[\Delta\mathbf{\theta}_{t}=\mathbf{M}^{-1}\mathbf{w}_{t}\Delta t.\] where \[u(\mathbf{\theta}):=-\ln p(\mathbf{\theta})-\sum_{i=1}^{l} \ln p(\mathbf{y}_{i}|\mathbf{x}_{i},\mbox{\boldmath$\theta$ }),\] \(\mathbf{M}^{-1}\) and \(C\) are vectors containing strictly positive values, \(\Delta t<<1\) is the step size and \(\mathbf{\mathcal{N}}_{t}(\mathbf{0},I)\) denotes a random variable with a multivariate standard normal distribution. To keep the notation simple, we use the convention here, that all operations on vectors (multiplication, inversion, etc.) are to be taken element-wise. The auxiliary variable \(\mathbf{w}_{t}\) has the same dimension as \(\mathbf{\theta}_{t}\). A physical intuition of SGHMC can be gained by noticing that these equations also describe the diffusion of particles with coordinates \(\theta\), potential energy \(u(\mathbf{\theta})\), momenta \(\mathbf{w}_{t}\) and masses \(M\) under friction. In this analogy, the vector \(C\) would represent the friction coefficients. From a machine learning perspective, \(\mathbf{w}_{t}\) represents a momentum term similar to the ones used in many modern neural network optimizers [21]. In fact, Chen et al. used some substitutions which lead to a Bayesian analog to stochastic gradient descent with momentum [23], but we will make somewhat different substitutions that lead to a natural way to include adaptive step sizes: \(\alpha=\Delta t\mathbf{M}^{-1}\mathbf{C}\), \(\gamma=(\Delta t)^{2}|D|\alpha^{-1}\) and \(\mathbf{v}_{t}=\gamma^{-1}\Delta t\mathbf{w}_{t}\) which yields: \[\Delta\mathbf{v}_{t}=-\alpha\frac{1}{|D|}\nabla_{\mathbf{ \theta}_{t}}u(\mathbf{\theta}_{t})-\alpha\mathbf{v}_{t-1}+ \alpha\sqrt{\frac{2\mathbf{M}}{|D|\gamma}}\mathbf{\mathcal{N} }_{t}\left(0,I\right),\] \[\Delta\mathbf{\theta}_{t}=\gamma\mathbf{M}^{-1}\mathbf{v}_{t}\] where \(|D|\) is the size of the dataset \(D\). This is up to the noise term \(\mathbf{\mathcal{N}}_{t}\left(0,I\right)\) equivalent to the updates of the Adam optimizer [24]. Figure 2: The computational graph of the NequIp model for predicting the potential energy \(E\) and atomic forces \(\mathbf{F}_{i}\) from the atomic numbers \(z_{i}\) and coordinates \(\mathbf{r}_{i}\). Unfortunately, the mass term \(\mathbf{M}\) used in the standard Adam optimizer can vary a lot even during later stages of the training and this variation depends on the value of \(\mathbf{\theta}_{t}\) at the previous time steps. As a consequence, the resulting process \((\mathbf{\theta}_{t},\mathbf{v}_{t})\) would not even be a Markov chain, and the Bayesian posterior would most likely no longer be the distribution \(\mathbf{\theta}_{t}\) converges to [22]. For many neural network architectures, timely convergence to the posterior can be achieved by simply setting \(\mathbf{M}=I\). However, the vastly varying gradient scales of the different parameter groups in the model make this approach not feasible. As a solution, we introduce now a new adaptive step size method for the SGHMC algorithm which still converges to the posterior distribution without requiring the computation of higher-order derivatives. In order to achieve this, we set \(\mathbf{M}\) as the denominator of the AMSGrad algorithm [25] during the first phase of the optimization: \[\mathbf{a}_{t}=(1-\beta)\frac{1}{|D|^{2}}\left(\nabla_{\mathbf{\theta}_{t}}u(\mathbf{ \theta}_{t})\right)\left(\nabla_{\mathbf{\theta}_{t}}u(\mathbf{\theta}_{t})\right)+ \beta\mathbf{a}_{t-1},\] \[\mathbf{D}_{t}=\max(\mathbf{D}_{t-1},\mathbf{a}_{t}),\] \[\mathbf{M}_{t}=\sqrt{\frac{\mathbf{D}_{t}}{1-\beta^{t}}}+\epsilon_{stability}.\] Here, \(\max(\cdot,\cdot)\) is the element-wise maximum, \(\epsilon_{stability}\) is a stability constant and \(\beta\) is a hyperparameter used in computing the running average \(\mathbf{a}_{t}\) and is typically set between 0.99 and 0.9999. Because this mass term is still time- and path-dependent, \(\mathbf{\theta}_{t}\) can not, in general, be expected to converge exactly to the posterior distribution during this phase. However, because \(\mathbf{M}_{t}\) is not based on a running average of squared gradients, like most adaptive step size methods are, but instead on the maximum of such a running average, it typically changes very little during the later stages of the optimization. As a result, the process will already become fairly close in distribution to the Bayesian posterior during this stage of the optimization. Furthermore, because \(\mathbf{M}_{t}\) already remains almost constant after a while, we can keep it entirely constant after a certain amount of steps without causing instabilities, at which point the process \(\mathbf{\theta}_{t}\) becomes a regular SGHMC process which is known to converge to the Bayesian posterior for sufficiently small step sizes [23]. Because deep learning datasets are usually very large, evaluating \(\nabla_{\mathbf{\theta}}u(\mathbf{\theta})\) exactly is typically very time-consuming. Practical implementations instead estimate \(\nabla_{\mathbf{\theta}}u(\mathbf{\theta})\) on a smaller, randomly sampled subset \(\hat{D}\subset D\) via \[\nabla_{\mathbf{\theta}}u(\mathbf{\theta})=\mathbf{\epsilon}(\mathbf{\theta})+\nabla_{\mathbf{ \theta}}\hat{u}(\mathbf{\theta})\] \[:=\mathbf{\epsilon}(\mathbf{\theta})+\nabla_{\mathbf{\theta}}\left(-\ln p(\mathbf{\theta})- \frac{|D|}{|\hat{D}|}\sum_{(\mathbf{x},\mathbf{y})\in D}\ln p(\mathbf{y}|\mathbf{x},\mathbf{\theta })\right).\] The resulting algorithm is summarized in Algorithm 1. Here \(\mathbf{\epsilon}(\mathbf{\theta})\) is the error in the estimation of \(\nabla_{\mathbf{\theta}}u(\mathbf{\theta})\) with \(\mathbb{E}\left[\mathbf{\epsilon}(\mathbf{\theta})\right]=\mathbf{0}\). ``` for\(t=1\)to\(T\)do Sample minibatch \(\hat{D}\) Evaluate \(\nabla_{\mathbf{\theta}_{t}}\hat{u}(\mathbf{\theta}_{t})\) = \(\nabla_{\mathbf{\theta}_{t}}\left(-\ln p(\mathbf{\theta}_{t})-\frac{|D|}{|\hat{D}|} \sum_{(\mathbf{x},\mathbf{y})\in\hat{D}}\ln p(\mathbf{y}|\mathbf{x},\mathbf{\theta}_{t})\right)\) if\(t\leq t_{max}\)then \(\mathbf{a}_{t}=(1-\beta)\frac{1}{|D|^{2}}\left(\nabla_{\mathbf{\theta}_{t}}\hat{u}(\mathbf{ \theta}_{t})\right)\left(\nabla_{\mathbf{\theta}_{t}}\hat{u}(\mathbf{\theta}_{t}) \right)+\beta\mathbf{a}_{t-1}\) \(\mathbf{D}_{t}=\max(\mathbf{D}_{t-1},\mathbf{a}_{t})\) \(\mathbf{M}_{t}=\sqrt{\frac{\mathbf{D}_{t}}{1-\beta^{t}}}+\epsilon_{stability}\) else \(\mathbf{M}_{t}=\mathbf{M}_{t_{max}}\) endif \(\Delta\mathbf{v}_{t}=-\frac{\alpha}{|D|}\nabla_{\mathbf{\theta}_{t}}\hat{u}(\mathbf{\theta} _{t})-\alpha\mathbf{v}_{t-1}+\alpha\sqrt{\frac{2\mathbf{M}_{t}}{|D|\gamma}}\mathbf{N}_{t} \left(0,I\right)\) \(\Delta\mathbf{\theta}_{t}=\gamma\mathbf{M}_{t}^{-1}\mathbf{v}_{t}\) endfor ``` **Algorithm 1** The Stochastic Optimization Algorithm The resulting algorithm is summarized in Algorithm 1. Here \(\mathbf{\epsilon}(\mathbf{\theta})\) is the error in the estimation of \(\nabla_{\mathbf{\theta}}u(\mathbf{\theta})\) with \(\mathbb{E}\left[\mathbf{\epsilon}(\mathbf{\theta})\right]=\mathbf{0}\). As long as \(\frac{|\mathbf{\epsilon}(\mathbf{\theta})|}{|D|}<<\sqrt{\frac{2\mathbf{M}_{t}}{\gamma|D|}}\) it is clear that this additional noise does not have a large effect on the dynamic as the Gaussian noise term will dominate. ``` for\(t=1\)to\(T\)do Sample minibatch \(\hat{D}\) Evaluate \(\nabla_{\mathbf{\theta}_{t}}\hat{u}(\mathbf{\theta}_{t})\) = \(\nabla_{\mathbf{\theta}_{t}}\left(-\ln p(\mathbf{\theta}_{t})-\frac{|D|}{|\hat{D}|} \sum_{(\mathbf{x},\mathbf{y})\in\hat{D}}\ln p(\mathbf{y}|\mathbf{x},\mathbf{\theta}_{t})\right)\) if\(t\leq t_{max}\)then \(\mathbf{a}_{t}=(1-\beta)\frac{1}{|D|^{2}}\left(\nabla_{\mathbf{\theta}_{t}}\hat{u}(\mathbf{\theta}_{t}) \right)\left(\nabla_{\mathbf{\theta}_{t}}\hat{u}(\mathbf{\theta}_{t})\right)+\beta\mathbf{a }_{t-1}\) \(\mathbf{D}_{t}=\max(\mathbf{D}_{t-1},\mathbf{a}_{t})\) \(\mathbf{M}_{t}=\sqrt{\frac{\mathbf{D}_{t}}{1-\beta^{t}}}+\epsilon_{stability}\) else \(\mathbf{M}_{t}=\mathbf{M}_{t_{max}}\) endif \(\Delta\mathbf{v}_{t}=-\frac{\alpha}{|D|}\nabla_{\mathbf{\theta}_{t}}\hat{u}(\mathbf{\theta}_ {t})-\alpha\mathbf{v}_{t-1}+\alpha\sqrt{\frac{2\mathbf{M}_{t}}{|D|\gamma}}\mathbf{N}_{t} \left(0,I\right)\) \(\Delta\mathbf{\theta}_{t}=\gamma\mathbf{M}_{t}^{-1}\mathbf{v}_{t}\) endfor ``` **Algorithm 2** The Stochastic Optimization Algorithm The can always be achieved by choosing an appropriate batch size and step size \(\gamma\). However, the additional noise will become significant for large learning rates and small batch sizes. In fact, even if we do not add the Gaussian noise to this process and subsequently just use the resulting AMS-Grad optimization, the injected noise at the commonly used large step sizes and small batch sizes will cause the optimization process to become a stochastic process which imitates the proposed algorithm to a degree, only with a noise term \(\frac{|\mathbf{w}(\mathbf{\theta})|}{|D|}\) that is not grounded on any theoretical foundation. ## 4 Empirical Evaluation ### The Benchmarks To assess our model's accuracy and predicted uncertainty we utilize two different datasets. To analyze our model's performance with varying amounts of Monte Carlo samples and under domain shift, we used a dataset consisting of PEDOT polymers, which are conducting polymers, which due to their chemical stability and tuneable properties [26] have been used for a wide range of applications including sensors [27], supercapacitors [28], battery electrodes [29], bioelectronics, solar cells, electrochromic displays, electrochemical transistors [30], and spintronics [31]. The dataset consists of polymers of lengths 8, 12 and 16, where only the shorter chains were used for training (see appendix B for details). The total training set contained only 100 configurations, 50 of length 8 polymers and 50 of length 12 polymers. Equivalently a small validation set of size 30 was constructed. The second dataset used is the MD17 dataset [32] consisting of long molecular dynamics trajectories of several small organic molecules calculated in DFT. Because this dataset had some numerical errors, a revised version RMD17 has recently been computed at higher accuracy [33] which we will utilize to evaluate our model's performance. Because dropout is the most common Bayesian method used for interatomic force modeling, we will compare our model's performance to a dropout-based version of the proposed stochastic model on this dataset (see appendix A.4 for details). For each compound, we used 1000 randomly sampled configurations during training and the rest for testing. Of the 1000 configurations sampled, 30 were reserved as a small validation set, and the remaining ones comprised the actual training set. The same samples were used as training, validation and test sets for our proposed model and the dropout-based model. ### Evaluation Metrics To measure prediction accuracy, we evaluate both the Mean Average Error in the Forces (MAE-F) and Energies (MAE-E) as well as the Root Mean Square Errors (RMSE-F, RMSE-E). In the evaluation, we use the expectation value under the estimated posterior density as a point prediction. I.e. \(\mathbf{F}_{pred}(\mathbf{x})=\frac{1}{k}\sum_{i=1}^{k}\mathbf{\mu}_{\mathbf{F}}(\mathbf{x},\mathbf{ \theta}_{i})\) and \(E_{pred}(\mathbf{x})=\frac{1}{k}\sum_{i=1}^{k}\mu_{E}(\mathbf{x},\mathbf{\theta}_{i})\). One metric used to evaluate and compare the predicted uncertainties is the Mean Log Likelihood (MLL). Since in the most common applications, the main task of the uncertainty measure is outlier detection, we further evaluate the ROC AUC scores for detecting force components with an error larger than 1 kcal/(mol\(\cdot\)A) on the basis of the variance of the predicted distribution of those force components. Because of the relatively small size of the PEDOT dataset, we only evaluate the outlier detection on the much larger RMD17 datasets. Lastly, to evaluate if the proposed model is properly calibrated we utilize the Expected Calibration Er Figure 4: Receiver Operating Characteristic curves for uncertainty-based detection of force components with a prediction error of at least 1 kcal/(mol\(\cdot\)Å) using k=8 Monte Carlo samples on the RMD17 datasets. ror (ECE) [34] as well as a visual inspection of the predicted and observed error densities of the force components (Figures 4 and 5) (see appendix A.5 for details). To calculate an ECE, the predictions \(y_{i}\) are divided into \(m\) bins of equal width. The ECE is then calculated as \[ECE=\sum_{i=1}^{m}f_{i}\left|f_{i}-e_{i}\right|\] where \(f_{i}\) is the fraction of observed samples that fall into bin \(i\) and \(e_{i}\) is the predicted probability of a sample falling into bin \(i\). Because the ECE is highly dependent on the width of the bins, we divide the ECE by the bin width \(\delta\) to obtain a Normalized Expectation Calibration Error (NECE): \[NECE=\sum_{i=1}^{m}\frac{f_{i}}{\delta}\left|f_{i}-e_{i}\right|\] which is an estimate of \[\mathbb{E}_{\rho(y)}\left[\left|\rho(y)-\rho_{predicted}(y)\right|\right].\] ### Results **Results on the PEDOT Datasets** As can be seen in Table 2, the model achieves high accuracy in the force prediction on all three test sets with a decreasing accuracy for increasing chain lengths. A slight improvement in the accuracy is observed when going from one to eight Monte Carlo samples. The model has a much larger error in the auxiliary task of energy predictions when compared to the force predictions. This is not surprising though, as the PEDOT molecules are fairly large and have correspondingly large energy scales. Additionally, the PEDOT training set contains much fewer energy labels than force labels. Further, it can be seen from Table 3, that a single Monte Carlo sample does not yield good uncertainty estimates for the forces which vastly improves when using eight Monte Carlo samples. A similar trend is not evident for the uncertainty quantification of the energy predictions. Even though no polymer chains of length 16 were included in the training set, we find that the model still achieves high accuracy and a good quantification of the uncertainty in the force predictions (Table 3) in the case of k=8 Monte Carlo samples and again much poorer uncertainty quantification for a single Monte Carlo sample. A complete histogram of predicted and actual force components can be found in appendix C. We observe some overconfidence even in the k=8 case (Figure 6). **Influence of the Number of Monte Carlo Samples** As can be seen in Table 3, both the calibration as Figure 5: Observed and predicted error densities of the force components in kcal/(mol.Å) with k=8 Monte Carlo samples on the RMD17 datasets. Figure 6: Observed and predicted error densities of the force components in kcal/(mol.Å) with k=8 Monte Carlo samples on the length 16 PEDOT dataset. well as the MLL significantly improve with increasing sample size for the forces. Because these samples are generated from a single Markov chain, this demonstrates an efficient traversal of the parameter space by the proposed sampling algorithm. Further, it appears that the improvements in MLLs diminish exponentially with increasing sample size. No similar trend can be found for the auxiliary task of energy predictions. Overall we find \(k=8\) Monte Carlo samples to be a good tradeoff between quality of uncertainty quantification and computational complexity. **Results on the RMD17 Datasets** Using eight Monte Carlo samples for both models, the proposed model has comparable accuracy to the dropout model on many of the easier RMD17 datasets but significantly outperforms it on the aspirin and malonaldehyde datasets (Table 4). The achieved accuracies are very consistent with the original NequIP model on these datasets [7] (See appendix D for the results of a single Monte Carlo sample and the NequIP model on this dataset). Further, it consistently outperforms the dropout model in terms of mean log-likelihoods for both the forces and the energies. The only exception to this being the mean log-likelihoods of the uracil energies where both models achieve the same result. A very large difference in the performance of the models is found in the outlier detection task where the proposed model consistently achieves ROC AUC scores much closer to the optimal score of 1 (Table 5). The benzene dataset was not included in this comparison because there were no instances of force prediction errors of the necessary scale for the proposed model. A complete plot of the receiver operating characteristic curves is given in Figure 4. As can be seen there, our proposed model is much more reliable at detecting outliers. Lastly, as is evident from Table 6 and Figure 5 the resulting model is not accurately calibrated in the case of 8 Monte Carlo samples and has a tendency for overconfidenc \begin{table} \begin{tabular}{c c|c c c c|c c c} \hline \hline \multirow{2}{*}{Chain Length} & \multicolumn{5}{c|}{Proposed Model (k=1)} & \multicolumn{5}{c}{Proposed Model (k=8)} \\ & & MAE & RMSE & NICE & MIL & MAE & RMSE & NICE & Mul \\ \hline \multirow{4}{*}{16} & Energy & 15.86 & 32.22 & 0.009 & -4.57 & 14.31 & 22.87 & 0.006 & -4.33 \\ & Forces & 0.222 & 0.385 & 0.649 & -1.79 & 0.210 & 0.371 & 0.313 & -0.20 \\ & Energy & 5.40 & 6.79 & 0.023 & -3.70 & 5.11 & 6.24 & 0.022 & -3.68 \\ & Forces & 0.184 & 0.276 & 0.652 & -0.87 & 0.169 & 0.254 & 0.317 & 0.14 \\ & Energy & 4.15 & 5.27 & 0.044 & -3.59 & 5.37 & 6.54 & 0.045 & -3.65 \\ 8 & forces & 0.151 & 0.221 & 0.619 & -0.284 & 0.139 & 0.203 & 0.215 & 0.44 \\ \hline \hline \end{tabular} \end{table} Table 2: Results on the PEDOT datasets. Force in kcal/(mol\(\cdot\)Å), energy in kcal/mol. \begin{table} \begin{tabular}{c c|c c c|c c} \hline \hline \multirow{2}{*}{ \begin{tabular}{c} Number of Samples k \\ \end{tabular} } & \multicolumn{5}{c}{Proposed Model} \\ & & MAE & RMSE & NICE & MILL \\ \hline \multirow{4}{*}{1} & Energy & 15.86 & 23.22 & 0.009 & -4.57 \\ & Forces & 0.222 & 0.385 & 0.649 & -1.79 \\ & Energy & 15.16 & 23.00 & 0.008 & -4.44 \\ & Forces & 0.219 & 0.381 & 0.473 & -0.87 \\ & Energy & 14.36 & 22.88 & 0.007 & -4.34 \\ & Forces & 0.216 & 0.378 & 0.376 & -0.44 \\ & Energy & 14.31 & 22.87 & 0.006 & -4.33 \\ & Forces & 0.210 & 0.371 & 0.313 & -0.20 \\ 16 & Energy & 14.56 & 22.86 & 0.007 & -4.38 \\ & Forces & 0.201 & 0.356 & 0.254 & 0.00 \\ \hline \hline \end{tabular} \end{table} Table 3: Influence of the MC sample size on the length 16 PEDOT dataset. Force in kcal/(mol\(\cdot\)Å), energy in kcal/mol. \begin{table} \begin{tabular}{c c|c c|c c c} \hline \hline \multirow{2}{*}{ \begin{tabular}{c} Molecule \\ \end{tabular} } & \multicolumn{5}{c|}{Dropout} & \multicolumn{2}{c}{Proposed Model} \\ & & MAE & RMSE & MILL & MAE & RMSE & NICE \\ \hline \multirow{4}{*}{Aspirin} & Energy & 0.072 & 0.096 & 0.88 & 0.045 & 0.067 & 1.41 \\ & Forces & 0.215 & 0.340 & -1.85 & 0.144 & 0.229 & 0.22 \\ \cline{2-6} & Energy & 0.012 & 0.021 & 2.61 & 0.010 & 0.017 & 2.99 \\ & Forces & 0.078 & 0.147 & 0.74 & 0.064 & 0.115 & 1.03 \\ & Energy & 0.012 & 0.020 & 2.63 & 0.013 & 0.020 & 2.63 \\ & Forces & 0.082 & 0.141 & 0.71 & 0.085 & 0.138 & 0.83 \\ & Energy & 0.021 & 0.038 & 1.82 & 0.016 & 0.027 & 2.51 \\ & Forces & 0.145 & 0.259 & 0.18 & 0.099 & 0.170 & 0.49 \\ \hline \multirow{4}{*}{Salicylic acid} & Energy & 0.022 & 0.042 & 1.87 & 0.023 & 0.213 \\ & Forces & 0.105 & 0.199 & 0.14 & 0.109 & 0.132 & 0.63 \\ \cline{1-1} & Energy & 0.009 & 0.018 & 2.55 & 0.009 & 0.012 & 2.74 \\ \cline{1-1} & Forces & 0.044 & 0.060 & 1.319 & 0.044 & 0.060 & 1.63 \\ \cline{1-1} & Energy & 0.011 & 0.015 & 2.63 & 0.010 & 0.014 & 2.79 \\ \cline{1-1} & Forces & 0.029 & 0.084 & 1.11 & 0.051 & 0.082 & 1.43 \\ \cline{1-1} & Benzene & Energy & 0.005 & 0.006 & 3.20 & 0.004 & 0.005 & 3.53 \\ \cline{1-1} & Forces & 0.020 & 0.032 & -1.50 & 0.010 & 0.016 & 3.06 \\ \hline \hline \end{tabular} \end{table} Table 4: Mean results on the RMD17 dataset using \(k=8\) Monte Carlo samples. Force in kcal/(mol\(\cdot\)Å), energy in kcal/mol. \begin{table} \begin{tabular}{c|c|c} \hline \hline Molecule & Dropout & Proposed Model \\ & & Model \\ Aspirin & 0.800 & 0.952 \\ Ethanol & 0.897 & 0.993 \\ Uracil & 0.888 & 0.986 \\ Malonaldehyde & 0.824 & 0.983 \\ Salicylic acid & 0.809 & 0.977 \\ Naphthalene & 0.902 & 0.995 \\ Toluene & 0.894 & 0.995 \\ \hline \hline \end{tabular} \end{table} Table 5: ROC AUC scores for uncertainty-based detection of force components with a prediction error of at least 1 kcal/(mol\(\cdot\)Å) using k=8 Monte Carlo samples on the RMD17 datasets. ## 5 Conclusion and Outlook As the results demonstrate, the proposed Bayesian neural network model achieves state-of-the-art accuracy while also achieving good uncertainty quantification. The proposed sampling algorithm appears to converge to the posterior distribution in a reasonable amount of time and maintains a fairly swift traversal through the parameter space afterward. Most importantly, the resulting model can reliably detect outliers while sampling parameters from the same Markov chain. This opens up new possibilities for Bayesian active learning procedures for learning interatomic forces. Further, it could enable the principled incorporation of existing physics-guided approximate interatomic force fields via the Bayesian prior distribution. This might potentially further improve both the data efficiency and generalizability of the model. While the proposed model already achieves good results, some improvements could still be made. While convergence to the posterior distribution becomes feasible with the proposed algorithm, in practice we find that it still takes about twice as many GPU hours to reach convergence when compared to the non-Bayesian optimization procedure described in [7]. However, while it was useful for demonstrative purposes of the convergence properties of the proposed sampler, faster convergence can most likely be achieved by simply reducing the injected gradient noise and the batch size during the initial phases of the optimization. Nevertheless, even without these measures, the generation of interatomic forces for the training set at _ab initio_ accuracy will likely be the computational bottleneck in most applications. Further, the stochastic model could potentially still be improved by adequate incorporation of covariances between atoms and also between force components. However, both of these covariances are challenging to include. For covariance between force components, the main challenge is to maintain rotation equivariance of the predicted density. For the incorporation of interatomic covariances, a dense covariance matrix will very quickly become impractical for larger molecules, as the evaluation of the log-likelihoods becomes a computational bottleneck. While a sparse covariance matrix might be adequate due to the mostly local nature of interatomic forces, a way to parameterize sparse covariance matrices would be needed, which is not trivial and which we could not find in the existing literature. Lastly, we found that the predicted uncertainties are not always properly calibrated and have a tendency for over-confidence. This might be a result of sampling from the same Markov chain, where the models can never be completely independently sampled from each other. This can lead to a reduced predictive variance between the sampled models and hence increased confidence. Here it might be beneficial to utilize two or more parallel chains to reduce the sample interdependency and explore the posterior distribution more efficiently or to recalibrate the uncertainties on a validation set. ## 6 Acknowledgement This paper is funded by dtec.bw - Digitalization and Technology Research Center of the Bundeswehr which we gratefully acknowledge [project CoupleIT!]
2305.18823
Speaker anonymization using orthogonal Householder neural network
Speaker anonymization aims to conceal a speaker's identity while preserving content information in speech. Current mainstream neural-network speaker anonymization systems disentangle speech into prosody-related, content, and speaker representations. The speaker representation is then anonymized by a selection-based speaker anonymizer that uses a mean vector over a set of randomly selected speaker vectors from an external pool of English speakers. However, the resulting anonymized vectors are subject to severe privacy leakage against powerful attackers, reduction in speaker diversity, and language mismatch problems for unseen-language speaker anonymization. To generate diverse, language-neutral speaker vectors, this paper proposes an anonymizer based on an orthogonal Householder neural network (OHNN). Specifically, the OHNN acts like a rotation to transform the original speaker vectors into anonymized speaker vectors, which are constrained to follow the distribution over the original speaker vector space. A basic classification loss is introduced to ensure that anonymized speaker vectors from different speakers have unique speaker identities. To further protect speaker identities, an improved classification loss and similarity loss are used to push original-anonymized sample pairs away from each other. Experiments on VoicePrivacy Challenge datasets in English and the \textit{AISHELL-3} dataset in Mandarin demonstrate the proposed anonymizer's effectiveness.
Xiaoxiao Miao, Xin Wang, Erica Cooper, Junichi Yamagishi, Natalia Tomashenko
2023-05-30T08:16:10Z
http://arxiv.org/abs/2305.18823v2
# Language-independent speaker anonymization using orthogonal Householder neural network ###### Abstract Speaker anonymization aims to conceal a speaker's identity while preserving content information in speech. Current mainstream neural-network speaker anonymization systems disentangle speech into prosody-related, content, and speaker representations. The speaker representation is then anonymized by a selection-based speaker anonymizer that uses a mean vector over a set of randomly selected speaker vectors from an external pool of English speakers. However, the resulting anonymized vectors are subject to severe privacy leakage against powerful attackers, reduction in speaker diversity, and language mismatch problems for unseen language speaker anonymization. To generate diverse, language-neutral speaker vectors, this paper proposes an anonymizer based on an orthogonal Householder neural network (OHNN). Specifically, the OHNN acts like a rotation to transform the original speaker vectors into anonymized speaker vectors, which are constrained to follow the distribution over the original speaker vector space. A basic classification loss is introduced to ensure that anonymized speaker vectors from different speakers have unique speaker identities. To further protect speaker identities, an improved classification loss and similarity loss are used to push original-anonymized sample pairs away from each other. Experiments on VoicePrivacy Challenge datasets in English and the _AISHELL-3_ dataset in Mandarin demonstrate the proposed anonymizer's effectiveness. Speaker anonymization, selection-based anonymizer, orthogonal Householder neural network anonymizer, weighted additive angular softmax. ## I Introduction Speech technology enables machines to recognize, analyze, and understand human speech, which facilitates human-machine communication and offers great convenience in our daily lives. Despite its prominent advantages, it suffers from voice privacy leakage, which intrudes on or tampers with a speaker's private information. For instance, by using advanced speaker [1, 2], dialect [3, 4], pathological condition [5, 6], or other types of speech attribute recognition systems, attributes such as a speaker's identity, geographical origin, and health status can easily be captured from speech recordings. Moreover, advanced speech synthesis techniques enable resynthesis, cloning, or conversion of a speaker's identity information to access personal voice-controlled devices [7, 8, 9]. In this paper, we are especially interested in speaker anonymization, which is a user-centric voice privacy solution to conceal a speaker's identity without degrading intelligibility and naturalness [10, 11, 12]. This task was standardized by the VoicePrivacy Challenge (VPC) committee [11, 12, 13], which held challenges in 2020 and 2022, to advance the development of voice privacy preservation techniques. Several approaches to protect speaker privacy are based on digital signal processing (DSP) methods [11, 12, 14, 15, 16, 17, 18], which modify instantaneous speech characteristics such as the pitch, spectral envelope, and time scaling. State-of-the-art anonymization approaches have borrowed ideas from neural speech conversion and synthesis, mainly focusing on disentangled latent representation learning [19, 20, 21, 22, 23, 24, 25] via two hypotheses. The first is that speech can be explicitly decomposed into content, speaker identity, and prosodic (intonation, stress, and rhythm) representations. Here, the speaker identity is a statistical time-invariant representation throughout an utterance, whereas content and prosodic information vary over time. The second hypothesis is that a speaker's identity representation carries most of his or her private information. Thus, generated speech using original content, prosodic, and anonymized speaker representations can suppress the original identity information (privacy) while maintaining intelligibility and naturalness (utility). A general framework for disentanglement-based speaker anonymization involves the following components. _Fine-grained disentangled representation extraction from original speech._ Here, extraction entails three aspects: (i) Content feature extraction. Typically, low-dimensional phonetic bottleneck features are extracted from an intermediate layer of a language-specific automatic speech recognition neural acoustic model (ASR AM) [26, 27]. This type of content encoder requires a large amount of transcribed English training data to obtain accurate linguistic representations, making it impossible to use for a different language. Nevertheless, content encoders based on self-supervised learning (SSL) and trained on unlabeled data can provide general content representations regardless of the language, enabling anonymization of speech data from any language. (ii) Prosody-related feature extraction to obtain the fundamental frequency, i.e., F0. (iii) Speaker embedding extraction. A speaker vector is extracted either from an automatic speaker verification (ASV) system based on a time-delay neural network (TDNN) [28], or from a more effective ASV based on emphasized channel attention, propagation and aggregation in TDNN (ECAPA-TDNN) [29]. _Speaker representation anonymization_: The core idea of a speaker vector anonymizer is to hide original speaker information while preserving the diversity among different speakers. A widely used selection-based speaker anonymizer [30, 23] replaces an original speaker vector with the mean vector (pseudo-speaker vector) of a set of randomly selected speaker vectors from an external pool of English speakers. _Anonymized speech synthesis_: An anonymized speaker vector with the original fundamental frequency and content features is passed to a speech waveform generation model to synthesize high-quality anonymized speech. The speech synthesis model can be a traditional text-to-speech pipeline model--a speech synthesis acoustic model (SS AM) and a neural source filter- (NSF-) based vocoder [31]--or a unified HiFi-GAN [32]. Despite confirmation of this approach's effectiveness [11, 12, 33], there remains much room for improvement for different attack scenarios and unseen language anonymization. Previous works [11, 12, 33, 23] have suggested that the most significant performance bottleneck for the current mainstream approach is the selection-based speaker anonymizer, whose performance significantly depends on the distribution of the external pool and how pseudo-speakers are selected from the pool. (i) For English speaker anonymization [11, 12, 13], the performance of speaker verifiability has gradually decreased against more powerful attackers. Additionally, voice distinctiveness is significantly degraded by anonymization. (ii) For unseen language (e.g., Mandarin) speaker anonymization, pseudo-speaker representations are generated from an external English speaker vector pool, and the resulting language mismatch increases the character error rate (CER) [33, 34]. Following this pipeline of disentanglement-based anonymization, with special consideration of the selection-based approach's problems, we propose a novel speaker anonymization system (SAS) based on an orthogonal Householder neural network (OHNN). As shown in the lower part of Fig. 1, the OHNN-based anonymizer generates distinctive anonymized speaker vectors that can protect privacy under all attack scenarios and can successfully be adapted to unseen-language speaker anonymization without severe language mismatch. Specifically, original speaker vectors are rotated to anonymized ones by an OHNN, which is a linear transformation with orthogonality. This module ensures that the anonymized speaker vectors follow the distribution over the original speaker vector space. To prevent anonymized speakers from overlapping with any other speakers, a basic classification loss, namely, additive angular margin softmax (AAM) is used to ensure that the anonymized speaker vectors from different speakers have unique speaker identities. To further protect speaker identities, an improved classification loss, weighted AAM (w-AAM), and the cosine similarity loss are used to push original-anonymized sample pairs away from each other. The main contributions of this work are as follows: * We propose an OHNN-based anonymizer that does not require an external pool of speaker vectors but instead transforms original speaker vectors to anonymized ones with carefully designed training constraints. We show empirically that these anonymized speaker vectors are diverse and language-neutral. * We visualize the cosine similarities between pairs of speaker vectors extracted from the generated speech of users and different attackers, as obtained with the commonly used selection-based anonymizer and our OHNN-based anonymizer. The results show that our proposed method effectively reduces the privacy leakage against different attackers and improves the diversity of anonymized speakers. * We conduct experiments on VPC English datasets and the _AISHELL-3_ Mandarin datasets. The results show that the proposed model can be successfully adapted for different languages, as it achieved either the best or near-best performance published to date under all attack scenarios in terms of privacy and utility metrics. ## II Related Work In this section, we introduce the VPC's official design, which provides the setting for this study, including definitions of specific goals, attack models, and objective evaluation metrics. We also overview existing speaker anonymization approaches and their limitations. ### _The VoicePrivacy Challenges_ The VPC formulates the speaker anonymization task as a game between users and attackers, as shown in Fig. 2. A user publishes anonymized data, called _test trials_, after applying an SAS to his or her original private speech. These anonymized data are expected to conceal the speaker's identity from different attackers while keeping other characteristics unchanged to maintain intelligibility and naturalness; this Fig. 1: Architecture of an SSL-based language-independent SAS, with selection- and OHNN-based anonymizers. facilitates downstream tasks to be achieved, such as human communication, model training, and so on. #### Ii-B1 Attack Models and Objective Evaluation Metrics Privacy metricTo assess the ability to protect a speaker's identity in different scenarios, the ASV performance in terms of the equal error rate (EER) is computed as the primary privacy metric by using language-matched ASV evaluation models. This metric is calculated under the four attack models shown in the lower left of Fig. 2. The attackers are assumed to have access to a few original or anonymized utterances for each speaker, called _enrollment_ utterances, and to have different levels of knowledge about the SAS: * _Unprotected_: No anonymization is applied, and attackers verify the original test trials against the original enrollment data by using an ASV system trained on the original dataset, denoted \(ASV_{\text{eval}}\). * _Ignorant_: Attackers are unaware of the anonymization strategy used for the test trial utterances; instead, they use the original enrollment data and \(ASV_{\text{eval}}\) to infer a speaker's identity. * _Lazy-informed_: Attackers use a similar SAS without accurate parameters to anonymize their enrollment data, and they use \(ASV_{\text{eval}}\) to detect a speaker's identity. * _Semi-informed_: The only difference from _Lazy-informed_ is that the attackers use \(ASV_{\text{eval}}^{\text{anom}}\), a more powerful version trained on anonymized speech, to reduce the mismatch between the original and anonymized speech and infer the speaker's identity. Primary utility metricTo assess how well speech content is preserved in anonymized speech, the ASR performance in terms of the word error rate (WER) is computed as a primary utility metric by using language-matched ASR evaluation models. As illustrated in the lower right of Fig. 2, two ASR models are trained in the same way to decode the anonymized data: \(ASR_{\text{eval}}\), trained on the original data, and \(ASR_{\text{eval}}^{\text{anom}}\), trained on the anonymized data. This enables exploration of whether speech content can be maintained better by simply retraining with similarly anonymized data. Secondary utility metricTo assess and visualize the preservation of voice distinctiveness, the gain of voice distinctiveness metric, \(\text{G}_{\text{VD}}\)[35, 36], is computed. Precisely, \(M=(M(i,j))_{1\leq i\leq N,1\leq j\leq N}\) is a voice similarity matrix for \(N\) speakers, where the similarity value \(M(i,j)\) for speakers \(i\) and \(j\) is formulated as follows: \[M(i,j)=\text{sigmoid}\left(\frac{1}{n_{i}n_{j}}\sum_{\begin{subarray}{c}1 \leq k\leq n_{i}\text{ and }1\leq l\leq n_{j}\\ k\neq l\,i\,i=j\end{subarray}}\text{LLR}(x_{k}^{(i)},x_{l}^{(j)})\right), \tag{1}\] Here, \(n_{i}\) and \(n_{j}\) are the numbers of utterances for each speaker; and \(\text{LLR}(x_{k}^{(i)},x_{l}^{(j)})\) is the log-likelihood ratio obtained by comparing the \(k\)-th utterance of the \(i\)-th speaker with the \(l\)-th utterance of the \(j\)-th speaker. These LLR scores are computed by probabilistic linear discriminant analysis (PLDA) of the \(ASV_{\text{eval}}\) model trained on the original data. Three matrices are constructed from the original (o) and anonymized (a) data: \(M_{\text{oo}}\) from the original data, \(M_{\text{oa}}\) from the original and anonymized data, and \(M_{\text{aa}}\) from the anonymized data. The diagonal dominance \(D_{\text{diag}}(M)\) is computed as the absolute difference between the mean values of diagonal and off-diagonal elements: \[D_{\text{diag}}(M)=\Bigg{|}\sum_{1\leq i\leq N}\frac{M(i,i)}{N}-\sum_{ \begin{subarray}{c}1\leq j\leq N\text{ and }1\leq k\leq N \\ j\neq k\end{subarray}}\frac{M(j,k)}{N(N-1)}\Bigg{|}. \tag{2}\] Next, \(G_{\text{VD}}\)[35] is defined as the diagonal dominance ratio of the two matrices: \[G_{\text{VD}}=10\log_{10}\frac{D_{\text{diag}}(M_{\text{aa}})}{D_{\text{diag }}(M_{\text{oa}})}, \tag{3}\] Fig. 2: Speaker anonymization task. A user anonymizes original speech to hide his or her identity before publication, and attackers use biometric (ASV) technology and knowledge of the anonymization method to re-identify the original speaker’s identity. Here, a gain of \(G_{\text{VD}}=0\) dB indicates that voice distinctiveness is preserved on average after anonymization, while a gain above or below 0 dB corresponds respectively to an average increase or decrease in voice distinctiveness. An ideal anonymization system should achieve high EERs (close to 50%) in the _Ignorant_, _Lazy-informed_, and _Semi-informed_ scenarios to protect the speaker's information. In addition, the WER should be as low as for the original speech, and \(G_{\text{VD}}\) should be close to 0 dB to preserve voice distinctiveness. ### _Existing Speaker Anonymization Approaches_ #### Ii-B1 Digital Signal Processing (DSP) Methods A simple approach [14] that does not require training data is to change speaker attributes with distortion of the spectral envelope by using McAdams coefficients [37] to randomly shift the positions of formant frequencies. Widening of formant peaks [15] further distorts the spectral envelope. Data-driven formant modification can also be applied by using the formant statistics of desired speakers [16] or time-scale algorithms [18]. Phonetically controllable anonymization [17] modifies a speaker's vocal tract and voice source features, with a focus on F0 trajectories. Although these methods perceptually manipulate the speech signal, previous works have indicated that powerful attackers can effortlessly recover speaker identities [11, 12, 38]. #### Ii-B2 Disentangled Representation Methods A typical approach based on disentangled representation learning, called x-vector based anonymization, is used as the primary baseline in the VPC [10, 11, 12, 13]. It extracts speaker representations and linguistic features by using a pretrained TDNN-based ASV system [28] and ASR AM based on a factorized time-delay neural network (TDNN-F), respectively. Then, to hide the original speaker's information, a selection-based speaker anonymizer [30] replaces the original x-vector with the mean vector of a set of randomly selected speaker vectors from an external pool of English speakers. Specifically, given a centroid of source speaker vectors from one speaker, the cosine distance is used to find the 200 farthest centroids in an external speaker vector pool, and 100 of those are randomly selected and averaged to obtain an anonymized speaker vector [30]. Finally, an SS AM generates mel-filterbank features from the anonymized pseudo x-vector, F0, and linguistic features, and an NSF-based waveform generator to synthesizes anonymized speech. Because this disentanglement-based method is more effective at protecting speaker identities than the DSP-based methods discussed in Section II-B1 [38, 12], most speaker anonymization studies have followed a similar framework. Improvements mainly come from two sources: _Improved speech disentanglement_: Some works [39, 40, 41] have argued that the disentangled linguistic information extracted from the language-specific ASR AM and F0 still contain speaker information. Accordingly, they modify the F0 and linguistic information to remove the residual speaker identity. _Improved speaker vector anonymization_: Other researchers have modified the original x-vector in ways that increase the privacy protection ability. Perero-Codosero _et al._[42] transformed an original x-vector to an anonymized one by using an autoencoder with an adversarial training strategy to suppress speaker, gender, and accent information. This requires labels for the speaker identity, gender, and nationality. Turner _et al._[43] sampled anonymized x-vectors from a Gaussian mixture model in a space reduced by principal component analysis (PCA) over an external pool of speakers, which preserves the distributional properties of the original x-vectors. More recently, Meyer _et al._[24] used a generative adversarial network to generate artificial speaker embeddings of a vector pool. The anonymization stage requires manual search to find vectors that are dissimilar to the anonymized one. Chen _et al._[44] did the original speaker identity by adding adversarial noise to the original speaker vectors while distorting the speech. In addition to their own limitations, each of these approaches requires large amounts of transcribed English training data to train the ASR AM model, which prevents direct use for unseen language speaker anonymization. By contrast, the SSL-based, language-independent SAS [33] shown in Fig. 1--comprising a HuBERT-based soft content encoder [45], ECAPA-TDNN speaker encoder [29], F0 extractor and HiFi-GAN decoder [32]--can anonymize speech from any language without relying on text labels or other language-specific resources. However, it suffers from a remaining limitation of selection-based anonymizers according to previous results [11, 12, 13, 33, 34]: the distribution of the external speaker pool significantly affects anonymized speakers, and the averaging of vectors from the speaker pool reduces voice distinctiveness. ## III Proposed OHNN-Based Anonymizer To mitigate the problems with existing approaches, we propose the OHNN-based anonymizer shown in Fig. 3. Hence, this section formulates speaker anonymization as a constrained optimization problem, describes a general form of the proposed anonymizer, and explains the implementation details. ### _Problem Formulation_ The training set \(\{(\mathbf{x}_{i}^{o},y_{i}^{o})\}_{i=1}^{M}\) comprises \(M\) speaker vector \(\mathbf{x}_{i}^{o}\) and the corresponding speaker label \(y_{i}^{o}\). The speaker vector \(\mathbf{x}_{i}^{o}\in\mathbb{R}^{d}\) is a \(d\)-dimensional segment-level speaker embedding obtained from an ECAPA-TDNN pretrained on the original Fig. 3: Framework for an OHNN-based anonymizer. The \(\mathbf{x}_{o}\) are original speaker representations extracted from a pretrained ECAPA-TDNN, which then pass through a transfer module \(f(\cdot)\) to produce the corresponding anonymized speaker representations \(\mathbf{x}_{a}\). The \(\mathbf{x}_{o}\) and \(\mathbf{x}_{a}\) are trained as different speakers. After training, \(\mathbf{x}_{a}\) is used as a pseudo-speaker vector to synthesize speech. audio waveform. \(\mathbf{x}_{i}^{o}\) follows an unknown distribution \(\mathbf{x}_{i}^{o}\sim p_{\mathbf{x}^{o}}\). Anonymized speaker vectors \(\mathbf{x}_{i}^{a}\in\mathbb{R}^{d}\) are obtained by transforming \(\mathbf{x}_{i}^{o}\) with a function \(f_{\Theta}:\mathbb{R}^{d}\rightarrow\mathbb{R}^{d}\), written as follows: \[\mathbf{x}^{a}=f_{\Theta}(\mathbf{x}^{o}). \tag{4}\] Accordingly, the anonymized speaker vectors follow another distribution \(\mathbf{x}_{i}^{a}\sim p_{\mathbf{x}^{o}}\) or \(\mathbf{x}_{i}^{a}\sim p_{f_{\Theta}(\mathbf{x}^{o})}\). An ideal speaker anonymization method should meet at least three constraints: * Speaker privacy protection: \(\mathbf{x}_{i}^{o}\) and \(\mathbf{x}_{i}^{a}\) are dissimilar to hide the original speaker identity. * Speaker diversity: \(\mathbf{x}_{i}^{a}\) has a unique speaker identity \(y_{i}^{a}\) to maintain the diversity of anonymized speech across different speakers. * Distribution similarity: \(\mathbf{x}_{i}^{a}\sim p_{\mathbf{x}^{o}}\) satisfies the same distribution as \(\mathbf{x}_{i}^{o}\) to maintain the naturalness of the original speech. The above constraints can be formulated as an optimization problem: \[(\Theta,\Psi)^{*} =\arg\min_{\Theta,\Psi}\mathbb{E}_{\{\mathbf{x}^{o},\mathbf{y}^{ o}\}\in D}\Big{[}\lambda\mathcal{L}_{s}\big{(}\mathbf{x}^{o},f_{\Theta}( \mathbf{x}^{o})\big{)} \tag{5}\] \[\quad+\mathcal{L}_{c}\big{(}y^{o},g_{\Psi}(\mathbf{x}^{o});y^{a}, g_{\Psi}(f_{\Theta}(\mathbf{x}^{o}))\big{)}\Big{]},\] \[\quad\text{s.t.}\ \mathcal{D}\big{(}p_{\mathbf{x}^{o}},p_{f_{ \Theta}(\mathbf{x}^{o})}\big{)}<\epsilon, \tag{6}\] where \(\lambda\) is a hyperparameter to balance the multi-objective function. \(\mathcal{L}_{s}\) is a similarity metric to optimize \(\Theta\) by minimizing the similarity of the original-anonymized pair, thus ensuring that the anonymized speaker vectors are dissimilar to the original ones to protect speaker privacy. Next, \(g_{\Psi}(\cdot)\) denotes the classifier layer, and \(\mathcal{L}_{c}\) is its classification loss function to optimize \(\Theta\) and \(\Psi\) by minimizing the discrepancy between the sets of desired outputs, \(y^{o},y^{a}\), and predicted outputs, \(g_{\Psi}(\mathbf{x}^{o}),g_{\Psi}(\mathbf{x}^{a})\). The outputs may be defined for a multi-speaker classification task, in which the original and corresponding anonymized speaker vectors are intentionally treated as different target speaker classes. This means that all speaker vectors after anonymization are treated as different classes, as well as different classes from the original speakers to maintain speaker diversity. Finally, \(\mathcal{D}\big{(}p_{\mathbf{x}^{o}},p_{f_{\Theta}(\mathbf{x}^{o})}\big{)}\) is the divergence between distributions of \(\mathbf{x}\) included in a training database before and after anonymization. This term ensures similarity between the distributions of the anonymized and original speaker vectors, with some tolerance \(\epsilon\). The Kullback-Leibler divergence (KLD) or other types of divergence are applicable. ### _General Form of Proposed Anonymizer_ Direct solution of Eqs. (5) and (6) for an arbitrarily designed DNN-based \(f_{\Theta}\) is difficult. Here, we propose an anonymizer that, with a few assumptions, always satisfies the constraint in Eq. (6) regardless of the value of \(\Theta\). In such a case, \(\Theta\) and \(\Psi\) can be optimized via Eq. (5) and a conventional gradient descent method. Let \(\mathbf{\mu}_{\mathbf{x}^{o}}\in\mathbb{R}^{d}\) and \(\mathbf{\Sigma}_{\mathbf{x}^{o}}\in\mathbb{R}^{d\times d}\) be the mean and covariance matrix of \(p_{\mathbf{x}^{o}}\), respectively. Our proposed anonymizer \(f_{\Theta}(\cdot)\) can be written as follows: \[\mathbf{x}^{a}=f_{\Theta}(\mathbf{x}^{o})=\mathbf{L}_{\mathbf{x}^{o}}^{-1} \mathbf{W}\mathbf{L}_{\mathbf{x}^{o}}(\mathbf{x}^{o}-\mathbf{\mu}_{\mathbf{x}^{o} })+\mathbf{\mu}_{\mathbf{x}^{o}}, \tag{7}\] where \(\mathbf{L}_{\mathbf{x}^{o}}\) is a whitening matrix1 that satisfies \(\mathbf{L}_{\mathbf{x}^{o}}^{-1}\mathbf{L}_{\mathbf{x}^{o}}^{-1}=\mathbf{\Sigma}_{ \mathbf{x}^{o}}\), and \(\mathbf{W}\in\mathbb{R}^{d\times d}\) is an orthogonal matrix that satisfies \(\mathbf{W}\mathbf{W}^{\top}=\mathbf{W}^{\top}\mathbf{W}=\mathbf{I}\). While \(\mathbf{\mu}_{\mathbf{x}^{o}}\) and \(\mathbf{L}_{\mathbf{x}^{o}}\) are determined by the data distribution, the values of \(\mathbf{W}\) are learned via Eq. 5. Footnote 1: \(\mathbf{L}_{\mathbf{x}^{o}}\) is a whitening matrix. It can be derived from \(\mathbf{\Sigma}_{\mathbf{x}^{o}}\) by a matrix decomposition method used in, e.g., PCA or Cholesky whitening [46]. Before introducing the parameterization and optimization of \(\mathbf{W}\), we show that the proposed anonymizer satisfies \(\mathcal{D}\big{(}p_{\mathbf{x}^{o}},p_{f_{\Theta}(\mathbf{x}^{o})}\big{)}=0\) when \(p_{\mathbf{x}^{o}}\) is a Gaussian distribution \(\mathcal{N}(\mathbf{\mu}_{\mathbf{x}^{o}},\ \mathbf{\Sigma}_{\mathbf{x}^{o}})\). Equation (7) can be decomposed into three steps: * Centering and whitening: \(\tilde{\mathbf{x}}^{o}=\mathbf{L}_{\mathbf{x}^{o}}(\mathbf{x}^{o}-\mathbf{\mu}_{ \mathbf{x}^{o}})\), * Rotation: \(\tilde{\mathbf{x}}^{a}=\mathbf{W}\tilde{\mathbf{x}}^{a}\), * De-whitening and de-centering: \(\mathbf{x}^{a}=\mathbf{L}_{\mathbf{x}^{o}}^{-1}\tilde{\mathbf{x}}^{a}+\mathbf{\mu} _{\mathbf{x}^{o}}\). The centered and whitened speaker vector \(\tilde{\mathbf{x}}^{o}\) obviously follows a normal distribution \(\tilde{\mathbf{x}}^{o}\sim\mathcal{N}(\mathbf{0},\mathbf{I})\). As \(\mathbf{W}\) is an orthogonal matrix, \(\tilde{\mathbf{x}}^{a}\) also follows a normal distribution \(\mathcal{N}(\mathbf{W}\mathbf{0},\mathbf{W}\mathbf{W}^{\top})=\mathcal{N}( \mathbf{0},\mathbf{I})\). Through the affine transformation in the last step, we know that \(\mathbf{x}^{a}\sim\mathcal{N}(\mathbf{\mu}_{\mathbf{x}^{o}},\mathbf{L}_{\mathbf{x}^{o} }^{-1}\mathbf{L}_{\mathbf{x}^{o}}^{-1})=\mathcal{N}(\mathbf{\mu}_{\mathbf{x}^{o}}, \mathbf{\Sigma}_{\mathbf{x}^{o}})\). Hence, the defined anonymizer does not change the distribution, i.e., \(\mathcal{D}\big{(}p_{\mathbf{x}^{o}},p_{f_{\Theta}(\mathbf{x}^{o})}\big{)}=0\). The above explanation also reveals the core idea of our proposed anonymizer: while it does not change the overall distribution, each speaker vector is rotated through an orthogonal transformation. The anonymized \(\mathbf{x}^{a}\) is guaranteed to be different from the original \(\mathbf{x}^{o}\) as long as \(\mathbf{W}\neq\mathbf{I}\). While an infinite number of orthogonal matrices can be applied for rotation, the optimal \(\mathbf{W}\) with respect to the criterion in Eq. (5) must be estimated through an optimization process. In real applications, \(\mathbf{\mu}_{\mathbf{x}^{o}}\) and \(\mathbf{\Sigma}_{\mathbf{x}^{o}}\) of the test set data are unknown. They can be estimated by collecting multiple samples from the test domain if it is possible. Otherwise, we can either use the statistics from the training set or make some simplifications. Through preliminary experiments, we found an effective, simplified form: \[\mathbf{x}^{a}=f_{\Theta}(\mathbf{x}^{o})=\mathbf{W}(\mathbf{x}^{o}-\mathbf{\mu}_{ \mathbf{x}^{o}}^{\text{train}})+\mathbf{\mu}_{\mathbf{x}^{o}}^{\text{train}}, \tag{8}\] where \(\mathbf{\mu}_{\mathbf{x}^{o}}^{\text{train}}\) is the mean of the speaker vectors in the training set, and \(\mathbf{\Sigma}_{\mathbf{x}^{o}}\) is assumed to be an identity matrix. ### _Rotation Matrix Using Householder Reflection_ We now need a specific way to parameterize \(\mathbf{W}\) through gradient descent to guarantee that the learned \(\mathbf{W}\) is orthogonal. While many methods can be used, we found that one based on a Householder reflection [47] is efficient for DNNs. Without loss of generality, assume that \(\mathbf{W}\) is a product of multiple orthogonal matrices: \[\mathbf{W}=\mathbf{W}_{1}\mathbf{W}_{l}...\mathbf{W}_{L}, \tag{9}\] where each matrix \(\mathbf{W}_{l}\in\mathbb{R}^{d\times d}\) is given by \[\mathbf{W}_{l}=\mathbf{H}_{qi}\,\mathbf{H}_{qi-1}\,...\,\mathbf{H}_{1},\ \ q_{l}\leq d, \tag{10}\] Here, each sub-matrix \(\mathbf{H}_{qi}\) is constructed with a Householder reflection [47] given a non-zero vector \(\mathbf{v}_{qi}\in\mathbb{R}^{d}\) as follows: \[\mathbf{H}_{qi}=\mathbf{I}-\frac{2}{\mathbf{v}_{qi}^{\top}\mathbf{v}_{q_{l}}} \mathbf{v}_{qi}\mathbf{v}_{qi}^{\top}. \tag{11}\] The resulting \(\mathbf{H}\) is known to be an orthogonal matrix for any non-zero vector \(\mathbf{v}_{qi}\), i.e., \(\mathbf{H}^{\top}\mathbf{H}=\mathbf{H}\mathbf{H}^{\top}=\mathbf{I}\) and \(\mathbf{H}\neq\mathbf{I},\forall\mathbf{v}_{qi}\neq\mathbf{0}\). Accordingly, \(\mathbf{W}_{l}\) and \(\mathbf{W}\) are orthogonal and thus guaranteed not to be the identity matrix. Equations (9-11) allow us to parameterize \(\mathbf{W}\) as \(\{\cdots,\mathbf{v}_{qi},\cdots\}\). We further propose two implementations, which differ in how they compute \(\mathbf{v}\): 1. _Random orthogonal Householder (ROH) reflection_: \(\mathbf{v}\) is treated as a learnable free parameter, i.e., \(\Theta=\{\cdots,\mathbf{v}_{qi},\cdots\}\), and each \(\mathbf{v}\) is randomly initialized and optimized using Eq. 5. The anonymization process is illustrated in Fig. 4(a). 2. _Learnable orthogonal Householder (LOH) reflection_: Each \(\mathbf{v}\) is transformed from a small NN given the input \(\mathbf{x}^{o}\). In such a case, \(\Theta\) is the set of the trainable weights in a set of small NNs. Fig. 4(b) illustrates an implementation in which each DNN has a single 1D convolution layer with 192 output channels and a kernel size of \(3\). While both implementations ensure that the transformation matrix \(\mathbf{W}\) is orthogonal, the first approach assumes a global transformation for all the input speaker vectors. In contrast, the latter approach assumes that the transformation matrix varies according to the input. ### _Loss Functions_ Before delving into the details of the loss functions, we describe how to build batch data for an OHNN-based anonymizer. Let \(N\) be the batch size and \(C\) be the number of original speakers. Each mini-batch comprises \(N/2\) original samples: \([\mathbf{x}^{o},y^{o}]=\{(\mathbf{x}^{o}_{i},y^{o}_{i})\}_{i=1}^{N/2}\), where \(y^{o}_{i}\in[1,C]\) and \(N/2\) corresponding anonymized samples. \([\mathbf{x}^{a},y^{a}]=\{(\mathbf{x}^{a}_{i},y^{o}_{i}+C)\}_{i=(N/2)+1}^{N}\). Therefore, the number of speakers is \(2C\) during the training of an OHNN-based anonymizer. We now explain the loss functions for learning the best values of \(\Theta\) and \(\Psi\) as defined in Eq. (5). For the classification loss \(\mathcal{L}_{c}\), we first consider the widely used AAM softmax loss [48, 49]: \[\mathcal{L}_{c}=\mathcal{L}_{\text{AAM-softmax}}=-\frac{1}{N}\sum_{i=1}^{N} \log\frac{e^{\|\mathbf{w}_{qi}\|\cdot\|\mathbf{x}_{i}\|\cdot\cos(\theta_{ji},i +m_{1})}}{Z}, \tag{12}\] where \(Z=e^{|\mathbf{w}_{qi}|\cdot\|\mathbf{x}_{i}\|\cos(\theta_{ji},i)}+\sum_{j\neq i \neq i}^{2C}e^{\|\mathbf{w}_{j}\|\cdot\|\mathbf{x}_{i}\|(\theta_{j,i})}\). \(\mathbf{w}_{j}\) is the \(j\)-th column of the weight in the fully-connected layer before the softmax layer, where \(\mathbf{w}\in\mathbb{R}^{d\times 2C}\); and \(\theta_{y_{i},i}\) is the angle between \(\mathbf{x}_{i}\) and the target class's weight vector \(\mathbf{w}_{y_{i}}\). After fixing the weight \(||\mathbf{w}_{y_{i}}||=1\) by \(\ell_{2}\)-normalization and rescaling \(||\mathbf{x}_{i}||\) to \(s\) to ensure that the gradient is not too small during training, we can write Eq. 12 as \[\mathcal{L}_{c}=\mathcal{L}_{\text{AAM-softmax}}=-\frac{1}{N}\sum_{i=1}^{N} \log\frac{e^{s(\cos(\theta_{ji},i+m_{1}))}}{Z}, \tag{13}\] where \(Z=e^{s(\cos(\theta_{ji},i+m_{1}))}+\sum_{j=1,j\neq i}^{2C}e^{s(\cos(\theta_{j,i}))}\). By applying the effective AAM softmax loss, we add an extra margin penalty \(m_{2}\) to explicitly improve the discrepancy for original-anonymized (or anonymized-original) pair samples. The approach is called weighted additive angular margin (w-AAM) softmax. Let \(i\in[1,N]\) be the index of the original (or anonymized) sample in a mini-batch based on this batch data construction method. The corresponding anonymized (or original) sample is indexed by \((i+N/2)\%N\), where \(\%\) denotes the modulo operation. Then, the proposed w-AAM loss function can be written as follows: \[\mathcal{L}_{c}=\mathcal{L}_{\text{w-AAM}}=-\frac{1}{N}\sum_{i=1}^{N}\log \frac{e^{s(\cos(\theta_{ji},i+m_{1}))}}{Z}, \tag{14}\] where the factor \(Z\) is now defined as: \[\begin{split} Z=& e^{s(\cos(\theta_{ji},i+m_{1}))}+e^ {s(\cos(\theta_{y(i+N/2)\%N,i}-m_{2}))}\\ &+\sum_{j=1,j\neq i,j\neq(i+N/2)\%N}^{2C}e^{s(\cos(\theta_{j,i} ))}.\end{split} \tag{15}\] In our experiments, we set \(m_{1}=m_{2}=0.2\), \(s=30\) and compared the performance with settings of \(\mathcal{L}_{c}=\mathcal{L}_{\text{AAM}}\) and \(\mathcal{L}_{c}=\mathcal{L}_{\text{w-AAM}}\). For the similarity metric \(\mathcal{L}_{s}\), we choose the cosine similarity2 given by \(\mathcal{L}_{s}(\mathbf{x}^{o}_{i},\mathbf{x}^{a}_{i})=\max(0,\cos(\mathbf{x} ^{o}_{i},\mathbf{x}^{a}_{i})-margin)\), we set \(margin=0\). Footnote 2: [https://pytorch.org/docs/stable/generated/torch.nn.CosineEmbeddingLoss.html](https://pytorch.org/docs/stable/generated/torch.nn.CosineEmbeddingLoss.html) ## IV Evaluation To evaluate the effectiveness of the SSL-based SAS using the proposed OHNN-based anonymizer under all the attack scenarios for English speaker anonymization, we followed the VPC evaluation plan [11, 12, 13] described in Section II. Then, we conducted anonymization experiments on Mandarin data to show that the proposed OHNN-based Fig. 4: Two types of OHNN-based anonymizers. anonymizer, which removes the requirement of an English speaker pool, can reduce the language mismatch encoded in anonymized speaker representations. As a result, better speech content preservation is achieved for unseen-language speaker anonymization. ### _Speaker Anonymization Dataset and Experimental Setup_ #### Iv-A1 Dataset The SSL-based SAS was built using the following VPC standard datasets [11]: an ECAPA-TDNN speaker encoder trained on the _VoxCeleb-2_[50]; a HuBERT-based soft content encoder finetuned from a pretrained HuBERT Base model3 on _LibriTTS-train-clean-100_[51] to capture content representations; and a HiFi-GAN model trained on _LibriTTS-train-clean-100_[51]. Footnote 3: [https://github.com/pytorch/fairseq/tree/main/examples/hubert](https://github.com/pytorch/fairseq/tree/main/examples/hubert) Unlike the selection-based anonymizer, which relies on an additional multi-speaker English dataset (_LibriTTS-train-other-500_) containing data from 1,160 speakers, the OHNN-based anonymizer's reuse a multi-speaker multi-language dataset (_VoxCeleb-2_), that is used to train the ECAPA-TDNN of the SSL-based SAS [33]. This large-scale dataset contains over 1 million utterances by 5,994 speakers of 145 different nationalities. English speaker anonymization was evaluated on the official VPC development and test sets [11, 12, 13]. These two sets contain English utterances by several female and male speakers from the _LibriSpeech_ and _VCTK_[52] corpora. For the _Ignorant_ and _Lazy-informed_ conditions, we used the language-matched \(ASV_{\text{eval}}\) system provided by the VPC [11, 12, 13]. It was trained on the original _LibriSpeech-train-clean-360_ English dataset. For the _Semi-informed_ condition, we trained \(ASV_{\text{eval}}^{\text{anom}}\) system in the same way as \(ASV_{\text{eval}}\), but with anonymized speech data. Likewise, \(ASR_{\text{eval}}\) and \(ASR_{\text{eval}}^{\text{anom}}\) were trained with the same original and anonymized speech data, respectively. The same anonymization systems used for English speaker were directly adopted for Mandarin speaker anonymization without training or fine-tuning on Mandarin data. The evaluation for Mandarin was conducted on a test set sampled from a 20-hour, multi-speaker Mandarin corpus called _AISHELL-3_[53]. The test set contains 4,267 utterances by 44 speakers. We split the utterances into test trial (88 utterances) and enrollment (4,179 utterances) subsets, which were used to produce 10,120 enrollment-test pairs for ASV evaluation, including 2,200 same-speaker and 7,920 different-speaker pairs. The ASV evaluation model \(ASV_{\text{eval}}^{\text{mand}}\) was an ECAPA-TDNN trained on the Mandarin datasets called _CN-Celeb-1 & 2_[54, 55]. The ASR evaluation model \(ASR_{\text{eval}}^{\text{mand}}\) was a publicly available ASR Transformer [56] trained on a 150-hour Mandarin ASR dataset, _AISHELL-1_[57]. #### Iv-A2 Experimental Setup Table I lists notations for the different speaker anonymization approaches that we examined. **B1.a**, **B1.b**, and **B2** are the baseline systems from VPC 2022 [13]. **S-Select** denotes the SSL-based SAS using a selection-based anonymizer. **S-ROH** denotes a system obtained by replacing the selection-based anonymizer of **S-Select** with a random OH (ROH) anonymizer and keeping other components unchanged. Likewise, **S-LOH** indicates the use of a learnable OH (LOH) anonymizer. Noted that, hereafter, **S-ROH*** and **S-LOH*** refer to models trained with the w-AAM and cosine similarity losses. For **S-Select**, the YAAPT algorithm [58] is used to extract the F0. The ECAPA-TDNN with 512 channels in the convolution frame layers [29] provides 192-dimensional speaker identity representations. The HuBERT-based soft content encoder [45] takes the CNN encoder and the first sixth transformer layers of the pretrained HuBERT base model as a backbone. It downsamples a raw audio signal into a 768-dimensional continuous representation, which is then mapped to a 200-dimensional vector by one projection layer to predict discrete speech units. These speech units are obtained by discretizing the intermediate 768-dimensional representations via _k_-means clustering4[59, 60]. The training procedures are detailed in [33]. For the selection-based anonymizer, attackers had different random seeds from users when randomly choosing 100 speaker vectors from the 200 farthest ones; thus, the attackers had different pseudo-speaker vectors. Footnote 4: [https://github.com/pytorch/fairseq/tree/main/examples/textless_nlp/gslm/speech2unit](https://github.com/pytorch/fairseq/tree/main/examples/textless_nlp/gslm/speech2unit) The OHNN-based anonymizer accepts 192-dimensional speaker representations extracted from a pretrained ECAPA-TDNN, which was the same here as the ECAPA-TDNN of the SSL-based SAS. We followed the VPC evaluation plan, in which attackers in the _Lazy-informed_ and _Semi-informed_ scenarios have partial knowledge of the speaker anonymizer. They are assumed to know the training dataset, structure, loss functions, and other training parameters of the user's OHNN Fig. 5: Visualization of original and anonymized speaker vectors generated by the **S-Select** and **S-LOH*** anonymizers. based anonymizer, except for the training seed to initialize the training weights. Specifically, the training seeds were 50 and 1986 for users and attackers, respectively5. Using knowledge of the OHNN-based anonymizer, an attacker trains a new anonymizer to anonymize speech. All the OHNN-based anonymizers were trained with a cyclical learning rate [61], which varied between 1e-8 and 1e-3, and the Adam optimizer [62] by using the SpeechBrain [56] toolkit based on PyTorch [63]. The number of iterations of one cycle was set to 130k. We fixed \(d=192\), \(L=12\) for both the ROH and LOH anonymizers, but we use \(q_{l}=192\) and \(q_{l}=50\) for the ROH and LOH training, respectively. The hyperparameter \(\lambda\) in Eq. 5 was set to 20 6. Footnote 5: The training seeds can be any values as long as they are different for users and attackers. Footnote 6: Source code and audio samples are available at [https://github.com/ni-yamagishilab/SSL-SAS](https://github.com/ni-yamagishilab/SSL-SAS) ### _Speaker Anonymization Experiments in English_ For the English experiments, first, we explored the difference between selection- and OHNN-based anonymizers by comparing the performance of **S-Select** and **S-LOH***. Then, we investigated different configurations for the OHNN-based anonymizer, including the losses and whether to explicitly use speaker information to optimize the Householder transformation. Finally, we compared SSL-based speaker anonymization using an OHNN-based anonymizer with other approaches, including the disentanglement- and DSP-based approaches. #### Iv-B1 Comparison of Selection- and OHNN-Based Anonymizers In the first experiments, we visualized the original and anonymized speech generated by **S-Select** and **S-LOH***** in terms of speaker embeddings, the cosine similarity of the speech pairs, and voice distinctiveness. **Original and anonymized speaker embeddings**: To show the difference between the **S-Select** and **S-LOH*** anonymizers, we first applied t-distributed stochastic neighbor embedding (t-SNE) [64] to visualize the original and anonymized embeddings. The results are shown in Fig. 5. The speaker embeddings were extracted from 50 speakers in the _VoxCeleb-2_ training set, which are shown in different colors, and 10 utterances were randomly selected from each speaker. Clearly, the anonymized speaker vectors generated by **S-Select** were heavily dependent on the distribution of an external pool, whereas **S-LOH***** generated distinctive anonymized speaker vectors that followed the distribution of the original speaker vector space. **Cosine similarity distribution on speech pairs**: Fig. 6 plots the cosine similarities between pairs of speaker vectors extracted from generated speech for all the test sets of _LibriSpeech_ and _VCTK_ on speech pairs provided by [12]. Depending on the attack condition, the speech can be original or anonymized generated by **S-Select** or **S-LOH*****. For the _Unprotected_ condition, shown on the left side of Fig. 6, the positive cosine similarity distributions (green) are close to 1, and the negative distributions (yellow) are close to 0, which indicates that the speaker vectors of the original speech were highly discriminative. To protect speaker privacy, an ideal SAS should push the positive score distributions toward the negative ones regardless of the attacker type. On the right side of Fig. 6, the top part shows the score distributions for three attacker conditions with **S-Select**. There are much bigger overlaps of the positive and negative distributions for the _Ignorant_ condition than for the _Unprotected_ Fig. 6: Cosine similarities between pairs of the speaker vectors extracted from the generated speech of users and different attackers. Positive: paired utterances from the same speaker. Negative: paired utterances from different speakers. Fig. 7: Voice similarity matrices for **S-Select** and **S-LOH***** on the female speakers in the LibriSpeech-dev and VCTK-dev datasets. The global matrix \(M\) for each system comprises three submatrices \(M_{\text{o}}\), \(M_{\text{oa}}\), and \(M_{\text{na}}\) defined in Section II-A1 via \(M=\begin{pmatrix}q_{\text{oa}}&\text{MnO}\\ M_{\text{oa}}&M_{\text{na}}\end{pmatrix}\). condition, which means that **S-Select** achieved reasonable speaker privacy performance under the _Ignorant_ condition. Unfortunately, the overlaps are smaller for the _Lazy-informed_ and _Semi-informed_ conditions. This reveals the reason for the significant speaker privacy leakage under more powerful attack conditions. Moreover, most of the cosine similarity scores are very close to 1, which may pose a risk of reducing the diversity of the anonymized speakers. The bottom right of Fig. 6 shows the score distributions for three attacker conditions with **S-LOH***. The overlaps of the positive and negative distributions are well magnified under all the attack scenarios. This verifies the effectiveness of our OHNN-based anonymizer in ensuring that the attackers cannot gain significant speaker privacy information from users. Furthermore, most of the cosine similarity scores are far from 1, indicating the diversity of the anonymized speakers. **Comparison of gain of voice distinctiveness (\(G_{\text{VD}}\))**: Fig. 7 shows voice similarity matrices obtained for **S-Select** and **S-LOH***. The upper-left submatrix of each matrix \(M\) is \(M_{\text{oo}}\), and the distinct diagonal reflects the high voice distinctiveness within the original speech. The upper-right (or lower-left) submatrix \(M_{\text{oa}}\) reflects the voice similarity between the original and the anonymized speech, such that the diagonal disappears when they differ. The lower-right submatrix \(M_{\text{aa}}\) reflects the voice similarity within the anonymized speech, where a dominant diagonal appears if the anonymized speakers remain distinguishable [35]. There is a very weak dominant diagonal in \(M_{\text{aa}}\) for **S-Select**, indicating that voice distinctiveness was lost among the anonymized speakers. In contrast, the matrices for **S-LOH*** exhibit distinct diagonals in \(M_{\text{aa}}\), indicating that voice distinctiveness was preserved after anonymization. In general, the **S-LOH*** anonymizer met the three constraints described in Section III-A: good privacy protection, voice distinctiveness, and naturalness of the speaker vector space from the above analysis and visualization. #### Iv-A2 Effects of Various Components for Proposed OHNN-Based Anonymizer The proposed OHNN-based anonymizer has two novel components: the loss functions and the Householder transformations. Table II summarizes the average EERs and WERs 7 under all attack scenarios with the selection-based anonymizer and two OHNN-based anonymizers with different losses. Footnote 7: The EER weights and detailed results for each subset are given in Appendix A. Due to limited space, other results are moved to the appendix of the paper on Arxiv. **Effect of the different losses**: For the proposed OHNN-based anonymizer, w-AAM+cos performed better than AAM+cos in terms of the EER under most attacker conditions. This was because the introduced margin of w-AAM expands the inter-class variance of original-anonymized pairs, thus increasing the dissimilarity. **Effect of different Householder transformations**: Clearly, the LOH anonymizers generally achieved better EERs than the ROH did. This result supports the view that, instead of using a global transformation for ROH, the LOH is more flexible because it learns from the speaker embeddings and thus brings more discriminative information. As for the WERs, those computed by \(ASR_{\text{eval}}^{\text{anom}}\) were consistently lower than those of \(ASR_{\text{eval}}\) for all systems. Although there was no obvious improvement in the WERs decoded by \(ASR_{\text{eval}}\) for the OHNN-based anonymizers, the WERs decoded by \(ASR_{\text{eval}}^{\text{anom}}\) were lower than those of the selection-based anonymizer. This implies that such utility degradation due to OHNN-based anonymizers can easily be offset by training ASR evaluation models on similar anonymized data. Meanwhile, all the OHNN-based anonymizers achieved similar WERs with \(ASR_{\text{eval}}\) or \(ASR_{\text{eval}}^{\text{anom}}\), which confirms that the orthogonality of ROH and LOH did not change the distributions of the original and anonymized speaker vectors. Furthermore, as expected, the OHNN-based anonymizers with different configurations yielded substantially higher \(G_{\text{VD}}\) values than the selection-based anonymizer did. Overall, the results in Table II confirm the findings described in Section IV-B1. #### Iv-A3 Comparison of Various SASs Using Different Anonymizers **Primary privacy and utility evaluation**: Table III lists the average EER and WER results for various SASs under all scenarios. To anonymize the speaker representations, **B1.a**, **B1.b**, and **S-Select** used the selection-based anonymizer, while **S-ROH*** and **S-LOH*** used the OHNN-based anonymizer. First, we examine the results with the selection-based anonymizer. The first observation is that **S-Select**, which follows the VPC's **B1.a** and **B1.b** by using the selection-based anonymizer, could protect speaker privacy information almost as well as **B1.a** and **B1.b** could under the _Ignorant_ and _Lazy-informed_ conditions with \(ASV_{\text{eval}}\). At the same time, **S-Select better preserved speech content information with \(ASR_{\text{eval}}\). This result is consistent with the findings in [33]. The second observation is that, as with **B1.a** and **B1.b**[13], the EERs for **S-Select** decreased from around 30% under the _Lazy-informed_ condition with \(ASR_{\text{eval}}\) to around 9% under the _Semi-informed_ condition with \(ASR_{\text{eval}}^{\text{anon}}\), indicating severe speaker privacy leakage. Next, we examine the results with the proposed OHNN-based anonymizer integrated into different configurations. First, **S-ROH*** and **S-LOH*** could protect speaker information almost as well as the VPC baselines (**B1.a** and **B1.b**) could when facing the _Ignorant_ attacker. Moreover, for the _Lazy-informed_ and _Semi-informed_ attackers, it comfortably outperformed all the baseline systems, achieving over 40% EER. Second, among all the methods, **S-ROH*** and **S-LOH*** preserved speech content the best with \(ASR_{\text{eval}}^{\text{anon}}\), achieving even lower WERs than for original speech on average. **Secondary utility evaluation**: The bottom of Table III lists the results for the average gain of voice distinctiveness, \(\text{G}_{\text{VD}}\). They indicate that our proposed **S-ROH*** and **S-LOH***** achieved much better preservation of voice distinctiveness than the SASs using the selection-based anonymizer. ### _Speaker Anonymization Experiments in Mandarin_ Table IV lists the EERs and CERs for the Mandarin test dataset. The trends for the selection-based anonymizers and OHNN-based anonymizers with different losses were remarkably similar to those observed for English. The proposed OHNN-based anonymizers increased the ASV EER to around 33% under the _Ignorant_ scenario and over 34% under the _Lazy-informed_ scenario, suggesting that speaker information was well-protected. Meanwhile, the CER on the anonymized speech decreased to less than 18% with the OHNN-based anonymizers, suggesting improved utility. This was expected, because we previously demonstrated [34] that the increased CER (18.92%) for the baseline **S-Select** is due to language mismatch with pseudo-speaker vectors obtained from an English speaker pool. This mismatch can be mitigated by using OHNN-based anonymizers trained on large-scale, multi-speaker, and multi-language data. ## V Conclusions This paper has proposed a novel OHNN-based speaker anonymization approach that rotates original speaker vectors into anonymized ones with a distribution following the original speaker vector space. To guarantee good privacy protection and voice distinctiveness, AAM/w-AAM and cosine similarity loss functions were introduced to ensure distinctive anonymized speaker vectors. Experiments on English VPC datasets demonstrated that the proposed model protects speaker privacy while maintaining speech content: it achieved either the best or near-best performance published to date in terms of privacy and utility metrics under all attack scenarios. Comparison of the cosine similarities between pairs of speaker vectors extracted from the generated speech with a commonly used selection-based anonymizer and the OHNN-based anonymizer further verified that our proposed method can effectively reduce privacy leakage when facing different attackers, while improving the diversity of anonymized speakers. Experiments on the Mandarin _AISHELL-3_ datasets additionally confirmed that our OHNN-based anonymizer reduces language mismatch and can be successfully adopted for unseen language anonymization tasks.
2306.01822
ErfReLU: Adaptive Activation Function for Deep Neural Network
Recent research has found that the activation function (AF) selected for adding non-linearity into the output can have a big impact on how effectively deep learning networks perform. Developing activation functions that can adapt simultaneously with learning is a need of time. Researchers recently started developing activation functions that can be trained throughout the learning process, known as trainable, or adaptive activation functions (AAF). Research on AAF that enhance the outcomes is still in its early stages. In this paper, a novel activation function 'ErfReLU' has been developed based on the erf function and ReLU. This function exploits the ReLU and the error function (erf) to its advantage. State of art activation functions like Sigmoid, ReLU, Tanh, and their properties have been briefly explained. Adaptive activation functions like Tanhsoft1, Tanhsoft2, Tanhsoft3, TanhLU, SAAF, ErfAct, Pserf, Smish, and Serf have also been described. Lastly, performance analysis of 9 trainable activation functions along with the proposed one namely Tanhsoft1, Tanhsoft2, Tanhsoft3, TanhLU, SAAF, ErfAct, Pserf, Smish, and Serf has been shown by applying these activation functions in MobileNet, VGG16, and ResNet models on CIFAR-10, MNIST, and FMNIST benchmark datasets.
Ashish Rajanand, Pradeep Singh
2023-06-02T13:41:47Z
http://arxiv.org/abs/2306.01822v1
# ErfReLU: Adaptive Activation Function for Deep Neural Network ###### Abstract Recent research has found that the activation function (AF) selected for adding non-linearity into the output can have a big impact on how effectively deep learning networks perform. Developing activation functions that can adapt simultaneously with learning is a need of time. Researchers recently started developing activation functions that can be trained throughout the learning process, known as trainable, or adaptive activation functions (AAF). Research on AAF that enhance the outcomes is still in its early stages. In this paper, a novel activation function 'ErfReLU' has been developed based on the erf function and ReLU. This function exploits the ReLU and the error function (erf) to its advantage. State of art activation functions like Sigmoid, ReLU, Tanh, and their properties have been briefly explained. Adaptive activation functions like Tanhsoft1, Tanhsoft2, Tanhsoft3, TanhLU, SAAF, ErfAct, Pserf, Smish, and Serf have also been described. Lastly, performance analysis of 9 trainable activation functions along with the proposed one namely Tanhsoft1, Tanhsoft2, Tanhsoft3, TanhLU, SAAF, ErfAct, Pserf, Smish, and Serf has been shown by applying these activation functions in MobileNet, VGG16, and ResNet models on CIFAR-10, MNIST, and FMNIST benchmark datasets. Activation function. Deep learning. Image Classification. + Footnote †: Corresponding author: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email Email: Email: Email: Email: Email: Email: Email: Email: Email: Email Email: Email: Email: Email: Email: Email: Email: Email: Email: Email Email: Email: Email: Email Email: Email: Email: Email: Email: Email: Email: Email: Email: Email Email: Email: Email: Email Email: Email: Email: Email: Email: Email: Email Email: Email: Email: Email: Email: Email: Email: Email Email: Email: Email Email: Email: Email: Emailmail: Email Email: Email: Email Email: Email: Email: Email: Email: Email: Email: Email: Email Email: Email: Email Email: Email: Email: Email Email: Email Email: Email: Email: Email Email: Email: Email: Email Email: Email Email: Email Email: Email: Email Email: Email: Email Email: Email Email: Email: Email Email: Email: Email: Email: Email Email: Email: Email Email: Email: Email: Email Email: Email: Email: Email: Email: Email Email: Email: Email: Email: Email: Email: Email: Email: Email Email: Email: Email: Email: Email: Email: Email: Email: Email: Email Email: Email: Email: Email: Email: Email: Email Email: Email: Email Email: Email: Email: Email: Email: Email Email: Email: Email Email: Email: Email: Email: Email Email: Email: Email Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email Email: Email: Email Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: Email: E: Email: Email: E settings(Alkhouly et al., 2021). For example, see Eq. 1 and Fig. 1. \[sigmoid=\frac{1}{(1+e^{-x})}\quad f^{\prime}(x)=\frac{1}{(1+e^{-x})^{2}} \tag{1}\] \[tanh(x)=\frac{(e^{2x}-1)}{(e^{2x}+1)}\quad f^{\prime}(x)=1-tanh^{2}(x) \tag{2}\] The hyperbolic tangent activation function is a scaled version of the sigmoid function. It also has the same S shape (Fig. 2). It is continuous between -1 and +1. This also suffers from a gradient vanishing problem. In contrast to tanh(x), a neural network with arctanh(x) has more severe gradient changes, allowing it to converge more quickly during network training(Sivri et al., 2022). Tanh is defined as Eq.2. For high positive and small negative values, the Tanh activation function will reach saturation and stop responding to modest changes in the input data. Therefore, the weight won't update and the gradient will simply fade, making DNN unable to finish its training (Lau and Lim, 2019). ### ReLU The ReLU (Maniatopoulos and Mitianoudis, 2021), a quicker AF for learning the complex NN, has emerged as the most useful and popular feature. In comparison to the Sigmoid and Tanh AF, it offers greater deep learning performance. The ReLU retains the characteristics of linear models that make gradient-descent methods an easy way to optimize them because it is a nearly complete representation of the linear function. The ReLU AF executes a threshold operation for each input element, where the value is zero for negative arguments and the variable itself for positive arguments. The Equation for ReLU is given as Eq. 3. \[ReLU=max(0,x)\quad\quad f^{\prime}(x)=max(0,1) \tag{3}\] Due to its simplicity and reduced training time, the or non-differentiability at zero, which emerges when a significant negative bias is learned and causes the neuron's output to always be zero regardless of the input (Hao et al., 2020). ### Leaky ReLU LReLU was one of the first rectified-based activation functions built on ReLU. The LReLU function was an attempt to solve the aforesaid ReLU's possible issues. Leaky rectifier activation function enables the small unit of negative value to produce a modest gradient. However, LReLU operates almost equally similar to normal rectifiers. It has a minor effect on network performance. \[LReLU=\begin{cases}x&if~{}x>0\\ \alpha x&if~{}x\leq 0\end{cases}\quad f^{\prime}(x)=\begin{cases}1&if~{}x>0\\ \alpha&if~{}x\leq 0\end{cases} \tag{4}\] It cannot be utilized for complicated Classification because of its linearity. For certain of the use cases, it performs worse than Sigmoid and Tanh(Maniatopoulos and Mitianoudis, 2021). ### Exponential linear unit (ELU) The ELU, which was first described by the Clevert et al.(Clevert et al., 2015), is an activation function that preserves identity for inputs that are positive but takes non-zero values for arguments that are negative. It is given as Eq. 5. Where \(\alpha\) is a hyper-parameter, which defined the value for negative inputs(Kilicarslan and Celik, 2021). \[ELU=\begin{cases}x&if~{}x\geq 0\\ \alpha(e^{x}-1)&if~{}x<0\end{cases}\quad f^{\prime}(x)=\begin{cases}1&if~{}x \geq 0\\ \alpha e^{x}&if~{}x<0\end{cases} \tag{5}\] ### Silu The output of the sigmoid function is multiplied with its input in the sigmoid-weighted linear unit (SiLU)(Elfwing et al., 2018) AF as in the output range of (-0.5, \(\infty\)). It is defined as Eq.6. For large input, SiLU works as ReLU AF. \[SiLU(x)=x\times Sigmoid(x)\quad f^{\prime}(x)=\frac{1+e^{-x}(x+1)}{(1+e^{-x})^ {2}} \tag{6}\] Zheng et al(Zheng and Wang, 2020) present an AF using inverse hyperbolic tangent similar to Mish, called PATS. It is continuous non-monotonic. They used a parameter to fix the slope in the positive region by updating the parameter. It makes the deep networks more flexible and significantly lowers the risk of overfitting. \[f(x)=xarctan\big{(}k\pi s(x)\big{)} \tag{7}\] Where variables s(x) is the sigmoid activation function and k is a constant that brings out from the uniform distribution of the range. ### Swish It is the combination of the input function with sigmoid AF. Some of the characteristics of the Swish function are smoothness, non-monotonicity, and bounding below and unbounded above (Dasgupta et al., 2021). \[Swish=sigmoid(x)*x=\frac{X}{(1+e^{-(\beta x)})} \tag{8}\] \[f^{\prime}(x)=\frac{1+e^{-(\beta x)}(x+1)}{(1+e^{-(\beta x)})^{2}} \tag{9}\] It is given as Eq. 8 and also written like Swish(x) = x o(x). As the value of \(\beta\) increases toward infinity, it behaves like ReLU AF(Ramachandran et al., 2017). ### E-swish A SiLU variant is presented by multiplying the SiLU function by a multiplicative coefficient \(\beta\). The \(\beta\) parameter needs to tune because E-Swish doesn't have any trainable parameters. The parameter is determined through a search strategy(Alcaide, 2018). E-swish is defined by Eq.10. \[E-swish(x)=\alpha xsig(x)\quad f^{\prime}(x)=a\,\frac{1+e^{(-\beta x)}(x+1)}{ (1+e^{(-\beta x)})^{2}} \tag{10}\] Where hyperparameter \(\beta\) (1\(<\)\(-\)\(\beta\)\(<\)\(-\)2) is pre-initialize or learnable. It is also unbounded like ReLU. ### Linearly Scaled Hyperbolic Tangent (LiSHT) Linearly Scaled Hyperbolic Tangent (LiSHT) is combined by multiplying the attribute of ReLU and Tanh activation(Roy et al., 2018). Non-monotonicity and not being bound are properties of the LiSHT activation function. It is used to tackle the dying ReLU phenomena. \[LiSHT(x)=xtanh(x)\quad f^{\prime(x)}=x(1-tanh^{2}(x)+tanh\,(x)) \tag{11}\] ### Mish Similar to swish Mish AF is also non-monotonic. Identity function, Tanh, and SoftPlus are compounds to make Mish AF. It is based on self-gate property. It resolved the dying ReLU problem by preserving negative value. It doesn't saturate near non-zero values. It provides non-singularity in weight updating due to being continuously differentiable(Misra, 2019). \[Mish=xtanh\big{(}softplus(x)\big{)} \tag{12}\] \[f^{\prime}(x)=tanh\big{(}ln(1+e^{x})\big{)}+sec^{2}h\big{(}ln(1+e^{x})\big{)} \frac{x}{1+e^{-x}} \tag{13}\] ## 3 Adaptive activation functions (AAF) An adaptive activation function integrated using all the AF, whose shapes are acquired during training based on dataset complexity. A classic AF is converted in the adaptive activation function by changing or by adding simple constraints on the network parameters, which update weights. KiseFak et al.(KiseFak et al., 2021) are described a parameterized version of a fixed standard function whose parameter values are learned from data. All adaptive activation functions include a set of trainable parameters that allows AF to adjust shape extremely close to a precisely known function such as ReLU, Sigmoid, and Tanh. In other words, a neural network architecture equipped with AAF behaves similarly to activation functions. For instance, partial derivatives of these new parameters are required to train all the network parameters, including the trainable activation functions. A gradient descent method based on back-propagation is used to update the parameters of AAF. The automatic discovery of parametric activation functions by the PANGAEA, is a genetic parameter tuning method (Bingham and Mikkulainen, 2022). ### TanhSoft It is a zero-centric, non-monotonic, continuous, and trainable activation function. Biswas et al. have proposed three different tahnsoft AAF based on hyper-parameter (Biswas et al., 2021). These are defined as \[tanhSoft1=tanh(ax)*Softplus(x) \tag{14}\] \[f^{\prime}(x)=tanh(ax)\left[accept(ax)ln(1+e^{x})+\frac{1}{1+e^{-x}}\right] \tag{15}\] \[tanhSoft2=xtanh(\beta e^{xx}) \tag{16}\] \[f^{\prime}(x)=xsec^{2}h\big{(}ae^{(\beta x)}\big{)}ae^{(\beta x)}+tanh(\beta e ^{xx}) \tag{17}\] \[tanhSoft3=ln\big{(}1+e^{x}tanh(\delta x)\big{)} \tag{18}\] \[f^{\prime(x)}=\frac{1+\delta coth(\delta x)}{1+coth(\delta x)e^{-x}} \tag{19}\] Here, \(a\), \(\beta\), \(\gamma\), and \(\delta\) is hyper-parameter. It is used for controlling the slope of the curve on both the positive and negative axis. TanhSoft with seven baseline activation functions Relu, Leaky ReLU, ELU, Swish, softplus, GeLU, and Mish. TanhSoft outperforms all these activations in different application areas such as object detection, image classification, Machine Translation, and Semantic segmentation. ### SiNN-Sigmoidal Linear Unit (SinLU) Paul et al. proposed a SiLU-based activation function that removes the wiggle by multiplying a sinusoidal function is (x + sink). SinLU (Paul et al., 2022) AAF is given in Eq.20. \[SinLU(x)=(x+axis\beta x).\alpha(x) \tag{20}\] \[f^{\prime}(x)=\ \ \ \frac{e^{-x}(x+axis\beta x)}{(1+e^{-x})^{2}}+\frac{1+ \beta acos\beta x}{1+e^{-x}} \tag{21}\] Here, \(\alpha\) and \(\beta\) are trainable parameters. The parameter \(\alpha\) is used to get different shape with amplitude from the rectifier linear unit family and \(\beta\) defined the frequency of the sin function. It is also monotonic and differentiable. It affects the self-gated property of SinLU, so AF works differently from other activation functions. Value of the hyper-parameter of this AAF obtained by the grid search method. They compared SinLU activation with basic activation functions like ReLU, GELU. SinLU outperforms other activation on the MNIST dataset using single-layer feed-forward networks. This AAF is computational expensive, and it can be trapped in the local minimum, making learning extremely difficult(Alkhouly et al., 2021). ### TanhLU New alternatives of Tanh is proposed by integrating Tanh into a linear unit, called TanhLU(Shen et al., 2022), which is motivated by the scaled tanh characteristic and the positive unboundedness of the ReLU. TanhLU is defined as Eq.21. \[f(x)=atanh(yx)+\beta x\quad f^{\prime}(x)=\alpha ysech^{2}(yx)+\beta \tag{22}\] Here \(\alpha\), \(\beta\), and \(\gamma\) are the trainable parameters. Shen et al. showed that enlarging the value of the parameter will give a better-weighted gradient. However, if value of \(\beta\) is less than 0.5, it convergences quickly. ### SAAF (Shape Auto-tuning Activation Function) It is non-monotonic and bounded AF. It can gather negative data to enhance generalization ability which prevents and corrects the output distribution from being scattered in the non-negative region. SAAF (Zhou et al., 2021) is given as \[SAAF=\frac{x}{\frac{x}{\alpha}+e^{\frac{-x}{\beta}}0<\frac{\beta}{\alpha}<1 \tag{22}\] \[f^{\prime}(x)=\frac{\alpha^{2}(x+\beta)\ e^{\frac{x}{\beta}}}{\beta\left(xe^{ \frac{-x}{\beta}}+\alpha\right)^{2}} \tag{23}\] It is less saturated compared to the sigmoid and ReLU AF. A saturated region is one with a modest derivative that reduces variation and information propagation to the next layer. Activations are considered normalized if their mean and variance across samples are within prescribed intervals. SAAF provides zero-means property for convergence and decreases the gradient vanishing issue. It can adaptively adjust the output to a normalized distribution using two trainable parameters \(\alpha\) and \(\beta\). Serf (Nag & Bhattacharyya, 2021) is inspired by the self-gating property of Swish and Mish, which multiply the output of a non-linear function of an input with the same non-modulated input. Self-gating has an advantage over traditional gating because it only needs a single two-scalar input as opposed to many two-scalar inputs. Serf has properties such as being boundless above, bound beneath, smooth, non-monotonic, and differentiable at every point. Additionally, a limited domain of negative weights are preserved. The serf being unbounded made an effort to get around the saturation issue. Serf mitigates the aforementioned issue in addition to enhancing expressivity and gradient flow by retaining a small portion of negative information. It is a continuous differential AAF. \[Serf=xerf\left(ln(1+e^{x})\right) \tag{24}\] \[f^{\prime}(x)=erf\left(ln(1+e^{x})\right)+\frac{2xe^{x-ln^{2}(e^{x}+1)}}{\sqrt {\pi}(e^{x}+1)} \tag{25}\] ### ErfAct and Pserf ErfAct and Pserf (Biswas et al., 2022) are non-monotonic, continuous, and trainable AF, based on the Gaussian error function. Biswas et al. presented two AAF, by combining the erf function and parametric softplus. It is approximately smooth as ReLU, and outperforms the ReLU AF. Here, Pserf is a parametric version of the Serf Activation function. ErfAct and Pserf are represented by Eq. 26 and Eq. 28 respectively. \[ErfAct=xerf\left(ae^{\beta x}\right) \tag{26}\] \[f^{\prime}(x)=\ erf\left(ae^{\beta x}\right)+\frac{2\beta axe^{\beta x-a^{2}e^ {\beta x}}}{\sqrt{\pi}} \tag{27}\] \[Pserf=xerf\left(\gamma ln\left(1+e^{\beta x}\right)\right) \tag{28}\] \[f^{\prime}(x)=erf\left(\gamma ln\left(1+e^{\delta x}\right)\right)\ \ +\frac{2 yxe^{\delta-\gamma^{3}ln^{2}(1+e^{\delta x})}}{\sqrt{\pi}(1+e^{\delta x})} \tag{29}\] ### Smish An adaptive activation function called Smish inherits the non-monotonic properties of the logisl function. Sigmoid(x) is used to reduce the range of values. The logarithm operation is applied to obtain a smooth curve and a flat trend. Smish then multiplies its Tanh operation by x. It has no upper bound and ranges from (-0.25 to \(\alpha\)). For the larger negative values, it works like the ReLU activation function(Wang et al., 2022). \[f(x)=x\cdot P(x) \tag{30}\] \[f^{\prime}(x)=\text{P}(x)+\frac{xe^{x}sech^{2}\left(ln(1+sigmoid(x))\right)}{2 e^{2x}+3e^{x}+1} \tag{31}\] \[where\quad P(x)=tanh\left[ln(1+sigmoid(x))\right] \tag{32}\] ### IpLU IpLU (Wu et al., 2021) is a parametric version of the softsign function. Unlike Tanh, softsign has polynomial convergence, whereas the Tanh function has exponential convergence. It is used in the negative region and a parameter \(\alpha\) is used to get smaller slop. The Linear function is used to avoid exploding gradient problems. It is zero centric, monotonic and its derivative is also zero centric. \[f(x)=\begin{cases}x&ifx\geq 0\\ \frac{x}{1+|x|^{\alpha}}&ifx<0\end{cases} \tag{33}\] \[f^{\prime}(x)=\begin{cases}1&ifx\geq 0\\ \frac{1+|x|^{\alpha}+x^{2}\alpha|x|^{(\alpha-2)}}{(1+|x|^{\alpha})^{2}}&ifx<0 \end{cases} \tag{34}\] ## 4 Proposed Activation function After extensive literature survey, we obtained that most of the AAFs are reducing the effect of Dying ReLU phenomena at negative values(Zhou et al., 2021)(Shen et al., 2022)(Nag & Bhattacharyya, 2021)(Wang et al., 2022). ReLU activation, in which the negative part is not being considered. We came up with an activation function, which not only solved the dying ReLU by applying the function at the negative side (x<0) but also removes the negative saturation of sigmoid. It is achieved by piecewise combination of Erf and ReLU functions, called ErfReLU. The use of the erf function is inspired by the ErfAct activation function Eq.19. Proposed ErfReLU is a monotonic, zero-centered activation function. Erf is a trainable AF which is an approximation of ReLU with having negative size of ReLU. Biswas et al. (Biswas et al., 2022) have used of & Pserf with \(\alpha\),\(\beta\),\(\gamma\), and \(\delta\) as their parameter that controls the slop of the curve. The proposed AAF only uses one parameter. The Erf function is the gauss error function. It is bound below, which is represented in Eq.35. \[erf(x)=\frac{2}{\sqrt{\pi}}{\int_{0}^{x}}e^{-t^{2}}\ dt \tag{35}\] The derivative of the above function is given as \[erf^{\prime}(x)=\frac{2}{\sqrt{\pi}}e^{-x^{2}} \tag{36}\] ErfReLU is defined as \[f(x)=\begin{cases}x&if\ x\geq 0\\ \alpha\operatorname{erf}(x)&if\ x<0\end{cases} \tag{37}\] The derivative of ErfReLU is defined as Eq.23. \[f^{\prime}(x)=\begin{cases}1&\text{if }x\geq 0\\ \frac{a2e^{-x^{2}}}{\sqrt{\pi}}&\text{if }x<0\end{cases} \tag{38}\] Here \(\alpha\) is a parameter, used to control the slope of the function. The graph of ErfReLU and its derivative is shown in fig.10. It is continuous and above unbounded but bounded below AAF. The positive region of the ErfReLU function works as the ReLU activation function. It preserves a small amount of negative information to prevent the occurrence of the Dying ReLU phenomena and achieves the better accuracy with only one trainable parameter. ### Properties of the Proposed Function * Smoothness: The Gaussian error function and ReLU are differentiable everywhere, so ErfReLU is also differentiable, which makes it a smooth function. * Non-linearity: The Gaussian error function is a non-linear function, which introduces non-linearities into the network that helps to learn more complex functions and relationships between the input and output. * Saturation: The Gaussian error function can become saturated for large input values, meaning that the output of the function approaches a constant value as the input becomes very large. However, ReLU is not saturated for large input(Nag & Bhattacharyya, 2021). This exploits the benefits of both Erf and ReLU to proposed ErfReLU to learn complex functions * Boundedness: ErfReLU is lower bound as it is using the erf function. There is upper boundedness in the ErfReLU, due to owing the properties of the ReLU AF(Shen et al., 2022). ## 5 Experiments and Results In this section, we describe the experiments performed on the above-defined adaptive activation functions on diverse datasets using different deep learning models. We compared our suggested activations to 9 prominent trainable and state of art activation functions on deep learning application areas such as image classification and machine translation. The experimental data shows that ErfReLU has significant improvement over other AAF and traditional activations in the deep learning problem. We examine the performance by simply switching the activation functions while maintaining all other network and training parameter constants. In the adaptive activation function, the value of the parameter is depending upon input dataset, it used for updating the activation function and its shape. MobileNetV1, ResNet18, VGG16 and machine translation seq2seq model are used in performance analysis for AAFs. The experiments are performed using the PyTorch framework over a desktop system (Nvidia Quardo Rtx 5000 GPU had 128 GB RAM) consisting of 16 GB GPU. ### Image Classification We first evaluate our proposed activation functions on diverse image classification dataset such as the MNIST, FMNIST, and CIFAR10. We conduct comparative studies on two types of representative architectures, a large model (like VGG and ResNet) and a lightweight model (MobileNet), maintaining all parameter constants. MobileNet V1 is a lightweight version of the traditional convolutional layers called "depthwise separable convolution" to reduces the number of parameters, memory consumption, and computation. The ResNet 18 architecture consists of 18 layers, including convolutional layers, batch normalization layers, and rectified linear unit (ReLU) activation layers. The residual connections help to preserve the gradients flowing through the network, allowing the network to learn effectively even when it has many layers. The architecture of VGG16 is composed of a series of convolutional layers, followed by max-pooling layers, and several fully connected layers. We used the Cross Entropy Loss function for error calculation and classification of images. Adam optimizer is used with a learning rate of 0.001. We train the model for 100 epochs with batch size 128. Transformation is applied on the image with the size of 32 and 4-pixel zero-padding. #### 5.1.1 Cifar-10 CIFAR-10 is a dataset of size 60,000 32x32 colour images in 10 classes, with 6,000 images per class. There are 50,000 training images and 10,000 test images. The classes are airplane, automobile, bird, cat, deer, dog, frog, horse, ship, and truck. Table 1 provides the classification accuracy of different models on the defined adaptive activation function. Our proposed activation function shows significant improvement over other adaptive activation based on several observations on MobileNet and ResNet. ErfReLU trounces all other AAFs. It achieves highest accuracy of 92.78% and 94.04% over Mobilenet and Resnet models, respectively. Only on VGG16 model, ErfAct achieved greater accuracy than ErfReLU. Table 2 provides the categorization outcomes for CIFAR10 as determined by the activation functions ReLU, Swish, Mish, LiSHT and ErfReLU. The ErfReLU outperforms the other defined the state-of-the-art activation function over Mobilenet and Resnet models. It also shows significant improvement over Swish, LiSHT, activation functions on VGG16 model, however ReLU has better performance. \begin{table} \begin{tabular}{c c c c c c} \hline & \multicolumn{2}{c}{**Activati**} & \multicolumn{1}{c}{**Parameter**} & \multicolumn{1}{c}{**MobileN**} & \multicolumn{1}{c}{**ResN**} & \multicolumn{1}{c}{**VGG**} \\ **S/** & **on** & **er** & **et** & **et** & **16** \\ **N.** & **function** & & & & \\ \hline **1** & \begin{tabular}{c} Tanhsoft \\ 1 \\ \end{tabular} & \begin{tabular}{c} \(\alpha\): 0.87 \\ \(\beta\): 0.75, \\ \(\gamma\): 0.75 \\ \end{tabular} & 92.24 & 93.67 & 92.58 \\ **2** & \begin{tabular}{c} Tanhsoft \\ 2 \\ \end{tabular} & \begin{tabular}{c} \(\beta\): 0.75, \\ \(\gamma\): 0.75 \\ \end{tabular} & 92.39 & 93.44 & 92.87 \\ **3** & \begin{tabular}{c} Tanhsoft \\ 3 \\ \end{tabular} & \begin{tabular}{c} \(\alpha\): 0.85 \\ \(\alpha\): 1, \(\beta\): \\ \end{tabular} & 92.45 & 93.43 & 92.57 \\ **4** & TanhLU & 0.5, & 90.86 & 90.35 & 89.84 \\ & & \begin{tabular}{c} \(\gamma\)=2 \\ \end{tabular} & 91.64 & 90.58 & 86.28 \\ **5** & SAAF & \begin{tabular}{c} \(\alpha\): 0.75, \\ \(\beta\): 0.75 \\ \end{tabular} & 92.52 & 93.82 & 93.24 \\ **7** & \begin{tabular}{c} Pserf \\ \end{tabular} & \begin{tabular}{c} \(\alpha\): 1.25, \\ \(\beta\): 0.85 \\ \end{tabular} & 92.67 & 93.84 & 92.76 \\ \hline \end{tabular} \end{table} Table 1: Comparison of testing accuracy of different adaptive activation functions on the CIFAR10 dataset. Figure 10: Proposed ErfReLU activation function and its derivative. #### 5.1.2 Mnist The MNIST (Biswas et al., 2022) dataset of handwritten digits contains 70K images (60k for training and 10k for testing purposes), and each image size is a 32*32-pixel grayscale image. Table 3 shows the comparative result of AAF with proposed. It can be seen in table 4, the ErfReLU shows significant improvement over the state-of-the-art activation function. #### 5.1.3 Fmnist The FMNIST(Biswas et al., 2022) dataset consists of 70,000 handwritten digit images, with 60,000 images allocated for training and 10,000 for testing. Each image is a 32*32-pixel grayscale image. As presented in Table 5, the ErfReLU activation function outperforms the other activation functions when used with Mobilenet and Resnet models. However, in VGG16, the Smish adaptive activation function displays better performance compared to other adaptive activation functions. Moreover, Table 6 demonstrates that the ErfReLU activation function demonstrates a significant improvement over the state-of-the-art activation function. ### _Machine Translation_ Machine translation is a type of technology that automatically translates text from one language to another. It is used in a variety of application areas such as website localization, document translation, and chatbots. The validation of AAF's effectiveness in machine translation has been carried out through English-to-German translation experiments, utilizing the standard Multi30k dataset for training and testing. This dataset comprises 29k sentences for training, as well as 1k each for validation and testing purposes. A Long Short-Term Memory (LSTM) auto-encoder network \begin{table} \begin{tabular}{l l l l l} \hline \hline \multicolumn{2}{c}{**FMNIS T**} & \multicolumn{2}{c}{**Activatio n function**} & \multicolumn{2}{c}{**MobileNe**} & \multirow{2}{*}{ResNet} & \multicolumn{1}{c}{**VGG16**} \\ \cline{1-1} \multicolumn{1}{c}{**T**} & \multicolumn{1}{c}{**n**} & & & \multicolumn{1}{c}{**n**} & \multicolumn{1}{c}{**n**} \\ \hline 1. & ReLU & 92.59 & 93.73 & 93.7 \\ 2. & Swish & 92.74 & 93.42 & 92.8 \\ 3. & Mish & 92.55 & 93.56 & 93.1 \\ 4. & LiSHT & 90.59 & 92.38 & 93.2 \\ 5. & **ErfReLU** & **92.78** & **93.72** & **93.3** \\ \hline \hline \end{tabular} \end{table} Table 6: The testing accuracy of various state-of-the-art activation functions are compared on the FMNIST dataset. \begin{table} \begin{tabular}{l l l l l l} \hline \hline \multicolumn{2}{c}{**ACtivati**} & \multicolumn{2}{c}{**Activa**} & \multicolumn{2}{c}{**MobileNe**} & \multirow{2}{*}{**ResNet**} & \multicolumn{1}{c}{**VGG1**} \\ \multicolumn{2}{c}{**0**} & & \multicolumn{1}{c}{**n function**} & & & \multicolumn{1}{c}{**n**} \\ \hline 1. & \multicolumn{2}{c}{ReLU} & \multicolumn{1}{c}{90.13} & 93.63 & 93.9 \\ 2. & \multicolumn{2}{c}{Swish} & \multicolumn{1}{c}{90.84} & 93.64 & 92.8 \\ 3. & \multicolumn{2}{c}{Mish} & \multicolumn{1}{c}{90.78} & 93.43 & 93.1 \\ 4. & \multicolumn{2}{c}{LiSHT} & \multicolumn{1}{c}{85.92} & 90.15 & 86.5 \\ 5. & \multicolumn{2}{c}{**ErfReLU**} & \multicolumn{1}{c}{**92.78**} & \multicolumn{1}{c}{**94.04**} & 93 \\ \hline \hline \end{tabular} \end{table} Table 2: Comparison of testing accuracy of our proposed AAF with different state of art activation functions over CIFAR10 dataset. \begin{table} \begin{tabular}{l l l l l l} \hline \hline \multicolumn{2}{c}{**MNIST**} & \multicolumn{2}{c}{**Activatio n function**} & \multicolumn{2}{c}{**MobileNe**} & \multirow{2}{*}{**ResNet**} & \multicolumn{1}{c}{**VGG16**} \\ \multicolumn{2}{c}{1} & \multicolumn{2}{c}{ReLU} & \multicolumn{1}{c}{98.92} & 99.01 & 99.4 \\ 2. & \multicolumn{2}{c}{Swish} & \multicolumn{1}{c}{99.05} & 99.09 & 99.6 \\ 3. & \multicolumn{2}{c}{Mish} & \multicolumn{1}{c}{90.78} & 93.64 & 92.8 \\ 3. & \multicolumn{2}{c}{Mish} & \multicolumn{1}{c}{90.78} & 93.43 & 93.1 \\ 4. & \multicolumn{2}{c}{LiSHT} & \multicolumn{1}{c}{85.92} & 90.15 & 86.5 \\ 5. & \multicolumn{2}{c}{**ErfReLU**} & \multicolumn{1}{c}{**92.78**} & \multicolumn{1}{c}{**94.04**} & 93 \\ \hline \hline \end{tabular} \end{table} Table 5: Comparison of testing accuracy of different adaptive activation functions on the FMNIST dataset. \begin{table} \begin{tabular}{l l l l l l} \hline \multicolumn{2}{c}{**CIFER1**} & \multicolumn{2}{c}{**Activa**} & \multicolumn{2}{c}{**MobileNe**} & \multirow{2}{*}{**ResNet**} & \multicolumn{1}{c}{**VGG1**} \\ **0** & & \multicolumn{1}{c}{**n function**} & & & \multicolumn{1}{c}{**6**} \\ \hline 1. & \multicolumn{2}{c}{ReLU} & \multicolumn{1}{c}{90.13} & 93.63 & 93.9 \\ 2. & \multicolumn{2}{c}{Swish} & \multicolumn{1}{c}{90.84} & 93.64 & 92.8 \\ 3. & \multicolumn{2}{c}{Mish} & \multicolumn{1}{c}{90.78} & 93.43 & 93.1 \\ 4. & \multicolumn{2}{c}{LiSHT} & \multicolumn{1}{c}{85.92} & 90.15 & 86.5 \\ 5. & \multicolumn{2}{c}{**ErfReLU**} & \multicolumn{1}{c}{**92.78**} & \multicolumn{1}{c}{**94.04**} & 93 \\ \hline \hline \end{tabular} \end{table} Table 3: Comparison of testing accuracy of different AAF on the MNIST dataset. \begin{table} \begin{tabular}{l l l l l l} \hline \multicolumn{2}{c}{**CIFER10**} & \multicolumn{2}{c}{**Activa n function**} & \multicolumn{2}{c}{**MobileNe**} & \multirow{2}{*}{**ResNet**} & \multicolumn{1}{c}{**VGG1**} \\ **0** & & \multicolumn{1}{c}{**n function**} & & & \multicolumn{1}{c}{**6**} \\ \hline 1. & \multicolumn{2}{c}{ReLU} & \multicolumn{1}{c}{90.13} & 93.63 & 93.9 \\ 2. & \multicolumn{2}{c}{Swish} & \multicolumn{1}{c}{90.84} & 93.64 & 92.8 \\ 3. & \multicolumn{2}{c}{Mish} & \multicolumn{1}{c}{90.78} & 93.43 & 93.1 \\ 4. & \multicolumn{2}{c}{LiSHT} & \multicolumn{1}{c}{85.92} & 90.15 & 86.5 \\ 5. & \multicolumn{2}{c}{**ErfReLU**} & \multicolumn{1}{c}{**92.78**} & \multicolumn{1}{c}{**94.04**} & 93 \\ \hline \hline \end{tabular} \end{table} Table 2: Comparison of testing accuracy of our proposed AAF with different state of art activation functions over CIFAR10 dataset. is utilized as the benchmark Seq2Seq model for English-to-German translation. The encoder and decoder have an embedding size of 300, and both are equipped with a dropout factor of 0.5.The language translation model was trained for 25 epochs using a learning rate of 0.001 and a batch size of 256, while utilizing the Adam optimizer for cross-entropy loss training(Dubey et al., 2022). The network's performance on the dataset was evaluated using the BiLingual Evaluation Understudy (BLEU) score measure. Table 7 illustrates the BLEU score achieved by the adaptive activation function. When compared to other adaptive activation functions, the ErfReLU activation function displayed a notable improvement in performance. Nevertheless, the SAAF activation function exhibited superior performance compared to other activation functions. ## 6 Conclusion In this paper, adaptive activation functions that have been explored, the function that focuses on the ones that can be trained, are studied. These activation function attempts to avoid issues that arise during the training and optimization processes, such as learning saturation, exploding vanishing gradients, and dying problems. The control parameters are used in adaptive AFs to alter the efficiency of nonlinear transformations. We proposed an activation function, called ErfReLU, which combines the attribute of ReLU and Erf gives better convergence than state of art AF such as ReLU and other adaptive activation functions. An experimental analysis of nine adaptive AFs is performed, which can be used in many different areas of Deep learning. The CIFAR10, MNIST, and FMNIST dataset is used to evaluate the effectiveness of the adaptive AFs with MobileNet, ResNet, and Vgg16. Machine translation is performed on a multi3k dataset on an LSTM-based autoencoder. In general, the adaptive AFs show better convergence as they can adapt the data faster by learning the parameter from the data. ErfReLU has shown better convergence in all nine adaptive activation functions, although in some cases, Pserf showed better convergence. ## Declaration of Competing Interest The authors declare that they have no known competing financial interests or personal relationships that could have appeared to influence the work reported in this paper.
2306.06195
Risk stratification of malignant melanoma using neural networks
In order to improve the detection and classification of malignant melanoma, this paper describes an image-based method that can achieve AUROC values of up to 0.78 without additional clinical information. Furthermore, the importance of the domain gap between two different image sources is considered, as it is important to create usability independent of hardware components such as the high-resolution scanner used. Since for the application of machine learning methods, alterations of scanner-specific properties such as brightness, contrast or sharpness can have strong (negative) effects on the quality of the prediction methods, two ways to overcome this domain gap are discussed in this paper.
Julian Burghoff, Leonhard Ackermann, Younes Salahdine, Veronika Bram, Katharina Wunderlich, Julius Balkenhol, Thomas Dirschka, Hanno Gottschalk
2023-05-15T20:59:44Z
http://arxiv.org/abs/2306.06195v1
# Risk stratification of malignant melanoma using neural networks ###### Abstract In order to improve the detection and classification of malignant melanoma, this paper describes an image-based method that can achieve AUROC values of up to 0.78 without additional clinical information. Furthermore, the importance of the domain gap between two different image sources is considered, as it is important to create usability independent of hardware components such as the high-resolution scanner used. Since for the application of machine learning methods, alterations of scanner-specific properties such as brightness, contrast or sharpness can have strong (negative) effects on the quality of the prediction methods, two ways to overcome this domain gap are discussed in this paper. neural nets, survival analysis, maligne melanom, domain gap ## 1 Introduction Clinical and pathological staging of melanoma patients only relies on tumor size (Breslow thickness), ulceration and lymph node involvement [1]. However, the patient group with the thinnest melanomas in Tumor Stage T1 and with the most favorable prognosis resulted the most melanoma deaths in absolute numbers [2]. Additionally, patients from T3b onwards can be now offered potent adjuvant therapy [3, 4]. To identify patients with small tumors but high risk of relapse or to spare patients in advanced disease but with low mortality or recurrence risk, there is a current need for biomarkers and better prognostication [5]. The use of digitalized histological images like H&E scans, that help pathologists to better interpret the information provided by the tissue sample under the microscope, has been widely tried to use for improving diagnosis and prognosis in many tumors [6]. 3D high-resolution volumetric imaging of tissue architecture from large tissue and molecular structures at nanometer resolution are new techniques for improving early cancer detection, personalized risk assessment and potentially identifying the best treatment strategies [7]. Deep learning has been shown to read out additional information of these stains. These models have shown to deliver independent prognostic information[8, 9] and could also predict the results of molecular biomarkers [10]. In melanoma, CNN networks were shown to reach a concordance level above 80% for diagnosis compared to human pathologists[11], could outperform histopathologists in classification[12], and the result of the sentinel lymph node status [13]. Prognostication and predicting the risk of tumor recurrence could be shown for combining digital analysis with the detection of tumor-infiltrating lymphocytes by achieving a negative predicting value (NPV) of about 85% [14]. Another CNN approach for predicting disease specific survival in melanoma resulted in mixed results achieving area under the curve (AUROC) values of 90% and 88% but only NPVs of 95% and 65%, respectively, in two validation cohorts [15]. Such problems of the domain gap often arises in image recognition [16], i.e. a method that has been optimised on a data set from a certain source, but on data from a different source it provides unsatisfactory results. To address this problem, we first standardise the predictions for each dataset or data source, which already improves the accuracy. In a second approach, we add an additional regularisation term directly to the neural network so that the results are in the same range. This also improves the accuracy of the predictions. The following parts of this paper are structured as follows: First, in section 2 we give a description of the data in terms of its clinical and technical structure. Section 3 provides an overview of methods that have been used in similar work and how our method is designed and built on these. Then, in section 4, we present and classify the results of our experiments. Finally, section 5 discusses the results and considers how future work might build on them. ## 2 Description of Data In this paper we consider two main sets of data: * _Dataset A_: This dataset contains 767 images of 176 patients of the American Joint Committee on Cancer (AJCC) set stages IA to IIID from four different locations in Bern (Switzerland), Bochum, Bonn and Kiel, Germany. All images have been recorded with the H&E colouring and were created by the same scanner Hamatasu NanoZoomer S210, NDP Version 2.4. In order to obtain a data set of the highest possible quality, the data were first manually checked by medical experts and a total of 23 data points were removed from the data set, e.g. due to broken slides. This clean-up took place before we split the data into training, validation and test data: The patients are assigned to train (104 patients), test (36 patients) and validation (36 patients) what results in 591 train-, 74 validation- and 102 test images. The split was chosen so that the distribution of high/low risk patients in each subset (training, validation, test) corresponds to the distribution of the full dataset A, see also table 1, under the constraint that multiple images of one patient remain in the same subset. * _Dataset B_: The second dataset contains 242 images of 242 patients with AJCC stages IIA to IIC from the Central Malignant Melanoma Registry (CMMR) in Tubingen, Germany, where the H&E-colored images have partly different coloring than the images of _Dataset A_, probably caused by another scanner type Hamatasu Nanozoomer 2.0 HAT, NDP Version 2.5 and the scans are mostly disturbed by a marker pen on the slide. To see how our algorithm performs on images with a domain gap _dataset B_ is only used as a separate test dataset. ### Clinical Description The images used represent hematoxylin-eosin (HE) stained melanoma sections. HE is a staining technique from histology that is used to better predict the disease prognosis of a melanoma patient, among other things, the mitosis rate can be determined (S3 Leitlmie Melanom). Overall survival of dataset A (86%) is similar to dataset B (88%). However, the MSS time for dataset B with a median of 41 month was considerably lower compared to 70/ 73 months of dataset A. Relapse free survival differed as well with around 78% and 69% for dataset A and dataset B, respectively. ### Technical Description Both datasets contain a total of 1009 images of different sizes (up to a resolution of \(158720\times 115456\) pixels) and various format ratios. Therefore, the images have to be pre-processed as neural nets on commercially available hardware are not yet able to handle images of this size at the time of writing. See section 3.2 for more information on the pre-processing task. The total size of the dataset is 570,3 GB in.ndpi file format. For every patient \(i\), we have at least one image \(x_{i}\) and the information \(\delta_{i}=1\), indicating the death of the patient at time \(T_{i}\). If the patient survived the observation period of this study, we set \(\delta_{i}=0\) and \(T_{i}\) is the time the patient has been observed. ## 3 Materials and Methods ### Related Work There exists abundant work on using deep neural networks for the interpretation of medical images. In this section, we focus on works with the scope of AI based prediction of survival for patients with a melanoma diagnosis. In prior research on this topic [15] the authors use a two stage pipeline to predict risk on the basis of primary melanoma tumor images. Within this pipeline, they first use a segmentation to classify detect and crop tumor areas in the image. These small but detailed crops of \(500\times 5000\)px are then fed to a network of convolutional, recurrent and fully connected layers in order to predict the risk. [17] describes the approach to use a multivariable classifier that contains, besides clinical data, a score of a deep neural net, in order to predict the immunotherapy response of patients with advanced melanoma. Also here, clinical data is used for the model and a separation of segmentation and response classifier takes place. The authors of [12] describe an experiment where a trained ResNet50 model outperforms 11 pathologists in classifying labeled histopathological images what shows that neural nets in general have high potential to improve correct melanoma diagnoses. Similar to our approach, the authors of [18] used a VGG-based neural network architecture to detect cutaneous melanoma, although they use a binary classification for dead/alive patients instead of a survival analysis method. They evaluated their method a dataset provided by The Cancer Imaging Archive of 53 patients with a given survival status. In [19] the authors on the one hand locate molecular biomarkers in immunohistochemistry images using convolutional neural networks which can help enabling new cancer screenings. On the other hand they also classify the found biomarkers along their type. However, there are not only machine learning approaches to melanoma classification based on H&E scans, but also based on topics such as dermoscopic image data [20] where the authors use a quiet small 5-layers CNN to classify the images to the corresponding tumor stage with applying the Adam optimizer on the Similarity Measure for Text Processing as loss function. This work is also based on [21] where the authors predict the melanomas thickness using a pretrained VGG-19 model on \(400\times 400\)px preprocessed dermoscopic images. In [22] the authors also use deep convolutional neural networks in combination with survival analysis in order to find good predictions on pathological images - here in context of lung cancer. They annotated the regions of interest of the images with help of pathologists and sampled small random high resolution crops of these regions to use in the networks whereas we used down-sampled low resolution images in our approach. In contrast to this, in our work we extract information directly from the original image data using a VGG16-like neural network, so we don't use an additional pre-segmentation, which might be error prone by itself. In this way we also avoid labeling of the regions of interest by humans annotators, which is a time consuming process and requires highly trained annotators. ### Preprocessing the Data When pre-processed, the images are reduced from their original format by a factor of 64 in dataset A and 128 in dataset B in each dimension. The resulting image is centred in a 2500 by 2000 pixel frame which is filled with white color outside the image. Images of patients with multiple images are seen as independent information in the training data. ### Methods #### 3.3.1 Cox's Proportional Hazards Model Survival analysis is about predicting the probability of absence of an event (e.g. the death of a patient) until time \(t\) using the parameters \(\beta\) of a suitable model [23]. One of the most widely used methods is Cox's Proportional Hazards Model, which predicts the hazard function \(h(t|x)\) on the basis of an input vector \(x\), see e.g., [15, 22] or [24] : \[h(t|x)=h_{0}(t)\cdot\exp(\beta^{T}x)\Leftrightarrow\log\frac{h(t|x)}{h_{0}(t) }=\beta^{T}x \tag{1}\] The baseline hazard function \(h_{0}(t)\) indicates how large the hazard rate would be without the influence of other parameters (like \(\beta\)) and is therefore only dependent on the time \(t\), which means that for our case it is eliminated from the calculation of the loss function and therefore does not need to be calculated [24]. To estimate the parameters \(\beta\) of the linear model the negative log partial likelihood function can be minimized: \[l(\beta)=-\sum_{i=1}^{n}\delta_{i}(\beta^{T}x_{i}-\log\sum_{j\in R_{i}}\exp( \beta^{T}x_{j})) \tag{2}\] where \(\delta\) is the delta-function which determines whether the data is censored or not, \(n\) the total number of data points and \(R_{i}=\{j|y_{j}\geq y_{i}\}\) is the risk set which describes the data-subset of patients which do not had an event before timestamp \(y_{i}\) of the \(i\)-th event. An adaption of linear models to non-linear models like (deep) neural nets was introduced by [25] in 1995 and applications can be found for example in [22] or [24]. The risk function \(\beta^{T}x\) is replaced by the output of the neural net \(\hat{h}_{\theta}(x)\) and we achieve the following loss function for each mini batch \(B\): \[\mathcal{L}(\theta)\coloneqq-\sum_{i\in B}\delta_{i}\left(\hat{h}_{\theta}(x_ {i})-\log\sum_{j\in R_{i}}e^{\hat{h}_{\theta}(x_{j})}\right) \tag{3}\] #### 3.3.2 Neural Net Architecture and Training Convolutional neural networks (CNN) represent the state of the art in image recognition. As neural network model, we use a modified version of a VGG16 net [26] in our experiments. Figure 1 gives an overview of the network architecture. Each convolutional layer has kernel sizes of \(3\times 3\) and each pooling layer is a maximum pooling with pooling size \(2\times 2\). As mentioned in section 3.1, we use the loss function supplied in [24] which implements a variant of the Cox's Proportional Hazards Model. In order to achieve a higher generalisability and reducing the domain gap between dataset A and dataset B, we expanded our loss function in 3 by a regularization term: \[\mathcal{L}(\theta)\coloneqq-\sum_{i\in B}\delta_{i}(\hat{h}_{ \theta}(x_{i})-\log\sum_{j\in R_{i}}e^{\hat{h}_{\theta}(x_{j})})\\ +\lambda(\frac{1}{|B|}(\sum_{j\in B}\hat{h}_{\theta}(x_{j}))^{2} \tag{4}\] where \(\lambda\) is the chosen regularization strength. See sec 4.1 for further information why we use this additional regularization term. \begin{table} \begin{tabular}{|c|c c c|c|} \hline Characteristic & \multicolumn{3}{c|}{Dataset A} & \multicolumn{1}{c|}{Dataset B} \\ & Training & Validation & Test & Test \\ \hline N(Scans) & 313 & 36 & 38 & 242 \\ N(Patients) & 104 & 36 & 36 & 242 \\ \hline Alive / Censored & 89 (86\%) & 31 (86\%) & 31 (86\%) & 212 (88\%) \\ Dead / Event & 15 (14\%) & 5 (14\%) & 5 (14\%) & 30 (12\%) \\ MSS time (months) Mean & 70.12 & 80.03 & 78.37 & 50 \\ MSS time (months) Median & 70 & 73 & 73 & 41 \\ \hline Relapse Free Survival Recurrence & 21 (20\%) & 8 (22\%) & 7 (19\%) & 75 (31\%) \\ Relapse Free Survival Non-recurrence & 83 (80\%) & 28 (78\%) & 29 (81\%) & 167 (69\%) \\ RFS time Mean & 67 & 76.67 & 75 & 42 \\ RFS time Median & 70 & 68 & 73 & 30 \\ \hline \end{tabular} \end{table} TABLE 1: Important features of our datasets. In training, we employ the Adam optimizer over \(50\) epochs with a learning rate of \(\alpha=0.001\) and a batch size of \(5\). For the implementation we used Openslide (version 1.1.2) [27] for importing the images, the GitHub repository of Sebp[24] and Tensorflow (version 2.6.1) [28] along with Keras (version 2.6.0) [29]. For the calculations, we used a workstation with a Dual Intel Xeon Gold 6248R 3.0GHz and three Nvidia Quadro RTX 8000 graphic units with 48GB VRAM each, whereas the different GPUs are only used for different trainings. #### 3.3.3 Concordance Index For validation purposes of our methods we use Harrel's concordance index (CI) [30]. The CI is defined as the ratio between correctly ordered pairs and all possible rankable pairs [31]: \[CI=\frac{\#\text{concordant pairs}}{\#\text{comparable pairs}} \tag{5}\] A pair of observations \(i,j\) with its survival times fulfill \(T_{i}>T_{j}\), is concordant if \(\hat{h}_{\theta}(x_{j})>\hat{h}_{\theta}(x_{i})\). Also a pair \(i,j\) is not comparable if the smaller survival time is censored (i.e. \(T_{i}>T_{j}\wedge\Delta_{j}=0\)). Otherwise this pair is comparable. Thus, \[CI=\frac{\sum_{i,j}\mathds{1}(T_{i}>T_{j})\cdot\mathds{1}(\hat{h}_{\theta}( x_{j})>\hat{h}_{\theta}(x_{i}))\cdot\Delta_{j}}{\sum_{i,j}\mathds{1}(T_{i}>T_ {j})\cdot\Delta_{j}} \tag{6}\] The CI estimates the probability of concordance \(P(\hat{h}_{\theta}(x_{j})>\hat{h}_{\theta}(x_{i})|T_{i}>T_{j})\) for two independent observations/predictions. It can also be interpreted as a measure of the area under a time-dependent receiver operator curve [32][31],[33]. A value of \(CI=1\) means that all observations are correctly sequenced, \(CI=0.5\) means that the method applied is no better than guessing. #### 3.3.4 Area Under the Receiver Operating Characteristic In the evaluation of the results our methods generate an important measurement value is the area under the receiver operating characteristic (AUROC)[34]. For a data point with \(a=P(F_{p})\) the probability of the data point being a false positive prediction and \(b-1=P(T_{p})\) the negative probability of the data point being a true positive prediction in a dataset \(D\), [35] defines the AUROC as follows: \[\mathrm{AUROC}=\sum_{i\in D}\{(1-b_{i}\cdot\Delta a)+\frac{1}{2}[\Delta(1-b) \cdot\Delta a]\}\] with \[\Delta(1-b)=(1-b_{i})-(1-b_{i-1})\] and \[\Delta a=a_{i}-a_{i-1}\] ## 4 Results An overview of all the concordance indices and AUROC values of our experiments is provided in table 2. ### Results of model without regularization In our first set of experiments, we use the loss function supplied in equation (3). Although we achieve an AUROC value of \(61.5\%\) on the test subset of dataset A and also an AUROC value of \(63.5\%\) on the separated dataset B. We observe that the domains in which our predictions \(\hat{h}_{\theta}(x_{i})\) lay differ significantly from dataset A to dataset B. This results in a bad overall AUROC value of \(54.4\%\) if one mixes these predictions naivly together as it would be a complete dataset from only one datasource before evaluating the whole set. One potential reason is that the net learns features that are relevant for the task, but it also is sensitive to further properties of the image like the pixel's brightness (or in general the pixel's color distribuition). While such image features do not encode meaningful medical information, they can still disturb the outcome of the network, especially if the Figure 1: Design of used neural network. Orange are convolutional layers, red are pooling layers and purple indices dense layers. hazards predicted on the second data set are in a different numerical range as compared with the original training data. This in particular happens by deviation from the neutral direction \(\hat{h}_{\theta}(x_{j})\to\hat{h}_{\theta}(x_{j})+z\) which merely leads to a redefinition of the baseline hazard function \(h_{0}(t)\) but is not sensed in the Cox loss function. So one can imagine the predicitons \(\hat{h}_{\theta}(x_{i})\) shifted away from the total diagonal like schematically shown in figure 2. In our case, dataset B has a slightly other color scheme (mainly because of the use of another scanner - see section 2) and so our predictions evaluating the model trained on dataset A on this dataset leads to a significant drop in performance. A first approach to reduce the sensitivity towards different hazards is to re-center the predicted hazards. We thus standardise (we subtract the mean and divide the result by the standard deviation) the predictions of each dataset and merge them afterwards. We display the resulting improvement in the rightbest column of each approach in table 2. The downside of this approach is that you need to have already a certain set of of images for each source of images/scanner that is used to predict survival probabilities. ### Results of model with regularization To interdict shifting of hazard functions altogether, we add a L2-regularization-term, see equation (4), to shift all predictions \(\hat{h}_{\theta}(x_{i})\) in the same domain range. This does not only lead to a higher AUROC value in evaluation on the mixed data set (\(60.1\%\) instead of \(54.4\%\)), but we can improve even more if combining the regularization with the above-mentioned normalization process (\(64.2\%\) instead of \(61.4\%\)) Besides, we also achieved a significantly higher ROC value on the testdata of dataset A throughout this regularization technique. Unfortunately the overall generalizability on the isolated dataset B suffered (\(57.8\%\) instead of \(63.5\%\)) from that approach. ## 5 Discussion and Outlook We have shown that it is possible to make survival predictions based on simplified image information using Cox's Proportional Hazard Models on neural networks and that our domain adaptation techniques succeed in merging the predictions into one range. Compared to [18] where the authors achieved an AUROC value of 76.9% our approach with regularization slightly outperforms it with an AUROC value of 79.5%. In future work, we will have a more detailed evaluation and we have a closer look on levels of significance and correlations to clinical variables like the Breslow depth or genetic information and demographic variables such as age or gender to evaluate and improve the clinical utility of our predictions.
2306.10091
Acoustic Identification of Ae. aegypti Mosquitoes using Smartphone Apps and Residual Convolutional Neural Networks
In this paper, we advocate in favor of smartphone apps as low-cost, easy-to-deploy solution for raising awareness among the population on the proliferation of Aedes aegypti mosquitoes. Nevertheless, devising such a smartphone app is challenging, for many reasons, including the required maturity level of techniques for identifying mosquitoes based on features that can be captured using smartphone resources. In this paper, we identify a set of (non-exhaustive) requirements that smartphone apps must meet to become an effective tooling in the fight against Ae. aegypti, and advance the state-of-the-art with (i) a residual convolutional neural network for classifying Ae. aegypti mosquitoes from their wingbeat sound, (ii) a methodology for reducing the influence of background noise in the classification process, and (iii) a dataset for benchmarking solutions for detecting Ae. aegypti mosquitoes from wingbeat sound recordings. From the analysis of accuracy and recall, we provide evidence that convolutional neural networks have potential as a cornerstone for tracking mosquito apps for smartphones.
Kayuã Oleques Paim, Ricardo Rohweder, Mariana Recamonde-Mendoza, Rodrigo Brandão Mansilha1, Weverton Cordeiro
2023-06-16T13:41:01Z
http://arxiv.org/abs/2306.10091v1
# Acoustic Identification of _Ae. aegypti_ Mosquitoes using Smartphone Apps and ###### Abstract In this paper, we advocate in favor of smartphone apps as low-cost, easy-to-deploy solution for raising awareness among the population on the proliferation of _Aedes aegypti_ mosquitoes. Nevertheless, devising such a smartphone app is challenging, for many reasons, including the required maturity level of techniques for identifying mosquitoes based on features that can be captured using smartphone resources. In this paper, we identify a set of (non-exhaustive) requirements that smartphone apps must meet to become an effective tooling in the fight against _Ae. aegypti_, and advance the state-of-the-art with (i) a residual convolutional neural network for classifying _Ae. aegypti_ mosquitoes from their wingbeat sound, (ii) a methodology for reducing the influence of background noise in the classification process, and (iii) a dataset for benchmarking solutions for detecting _Ae. aegypti_ mosquitoes from wingbeat sound recordings. From the analysis of accuracy and recall, we provide evidence that convolutional neural networks have potential as a cornerstone for tracking mosquito apps for smartphones. Introduction Mosquito-borne diseases remain one of the most significant health problems worldwide, with estimates of 700 million people contracting these illnesses annually and more than one million killed per year (Qureshi, 2018). In economic terms, these diseases generate severe losses to the global economy, estimated in billions of dollars each year (Bradshaw, Leroy, Bellard, Roiz, Albert, Fournier, Barbet-Massin, Salles, Simard and Courchamp, 2016; Diagne, Leroy, Vaissiere, Gozlan, Roiz, Jaric, Salles, Bradshaw and Courchamp, 2021; Ahmed, Hudgins, Cuthbert, Kourantidou, Diagne, Haubrock, Leung, Liu, Leroy, Petrovskii et al., 2022). Among these mosquitoes, we highlight _Aedes aegypti_, which can transmit diseases like Dengue, Zika, Chikungunya, and Yellow Fever. Fighting the spread of mosquito-borne diseases requires tackling the proliferation of their vector populations. Existing techniques to this end, such as source reduction (Forsyth, Mutuku, Kibe, Mwashee, Bongo, Egemba, Ardoin and LaBeaud, 2020) and mosquito traps (Leandro, de Castro, Lopes, Delai, Villela and De-Freitas, 2022), can be considered locally efficient. However, the adoption of such techniques faces substantial challenges - whether social, technical, or economic - to scale in the large. One could mitigate these challenges by monitoring the spread of mosquito populations and their proliferation rates. On one hand, information on mosquito prevalence in a given region may help guide public investment toward areas with higher proliferation. On the other hand, monitoring can also optimize the adoption of expensive techniques like spreading transgenic sterile mosquitoes (Waltz et al., 2021). In summary, carrying out comprehensive and accurate monitoring of mosquito proliferation on spatial and temporal scales is vital to controlling (and even eradicating) mosquitoes in a given region. Nevertheless, monitoring mosquito proliferation is also challenging, regardless of the sensing technology used (computer vision, audio recognition, etc.) (Fernandes, Cordeiro and Recamonde-Mendoza, 2021a). Solutions based on special purpose devices like mosquito traps often have a non-negligible Total Cost of Acquisition (TCA) and Total Cost of Ownership (TCO) (Townson, Nathan, Zaim, Guillet, Manga, Bos and Kindhauser, 2005). To reduce these costs, complementary monitoring methods based on crowd-sourcing, using widely available general-purpose devices (such as smartphones), are desirable (Mukundarajan, Hol, Castillo, Newby and Prakash, 2017; Fernandes et al., 2021a). In our previous work (Fernandes et al., 2021a), we advocated in favor of using smartphone apps for monitoring _Ae. aegypti_ proliferation through crowd-sourcing and advanced the state-of-the-art by proposing convolutional neural networks (CNNs) architectures for the classification of audio of mosquito wingbeat recorded with smartphone apps. In particular, we explored three distinct CNN architectures - binary, multiclass, and ensemble of binary architectures - and used them to identify a mosquito wingbeat sound in audio captured from smartphone microphones. In that work, we provided evidence that one can obtain better precision and accuracy in acoustic-based mosquito identification using the proposed architectures without resorting to additional metadata (e.g., geospatial data). From our continued experience in mosquito audio classification using those architectures and recorded using off-the-shelf smartphones, in this paper we conjecture that an effective smartphone app for acoustic mosquito identification (mosquito tracking app) must meet the following (non-exhaustive) set of requirements: 1. The mosquito tracking app must run effectively and efficiently on popular off-the-shelf smartphones; 2. The neural network running in the app must be robust to a wide range of background noise; and * The neural network must be resilient to bogus noise deliberately generated to induce false positives. In this paper, we address requirements R1 and R2 by making three contributions. First, we propose a residual CNN architecture to enable effective and efficient mosquito wingbeat classification through audio analysis in off-the-shelf, popular smartphones. Our architecture performs mosquito classification from spectograms of audio segments, using a set of residual and classification blocks to reduce the computing overhead (and, therefore, smartphone battery use) and dropout block to avoid overfitting. The resulting architecture is thus more efficient than existing architectures, also delivering higher precision and accuracy in mosquito classification, thereby addressing requirement R1. As a second contribution of this paper, we present an original dataset of mosquito wingbeat audio recordings that the research community can use as a benchmark for evaluation of machine learning models for mosquito audio classification. Finally, our third contribution in this paper is a training strategy for reducing the influence of environmental noise on mosquito wingbeat classification, thereby addressing Requirement R2. We also discuss strategies related to noise reduction and noise supression, thereby providing research directions for tackling Requirement R3. The results of an evaluation made with mosquito wingbeat recordings (including the novel recording dataset and existing ones) provide evidence of the effectiveness, efficiency, and robustness of the proposed architecture in contrast to existing ones. The proposed neural network is 18.5% smaller in terms of the number of parameters, which is the main computational efficiency factor of the neural network heuristic. The neural network combined with a novel training technique can generate results equivalent to or superior to the state-of-the-art in accuracy, precision, recall, and F1. In addition, implementing a functional prototype provides evidence of the feasibility of running our architecture on a Asus Zenfone Max M3 Qualcomm Snapdragon 430 64-bit Octa core 4G RAM Android 8.1 and a Motorola Moto E6 Play Cortex-A53 1.5 GHz Quad Core 2 GB RAM Android 9.0 smartphones. The remainder of this paper is organized as follows. In Section 2 we review technical background and related work. In Section 3 we detail the methodological processes carried out in our study, especially the method for obtaining the recording datasets. In Section 4 we present our neural network architecture and training method to enable mosquito classification in popular, off-the-shelf smartphones. In Section 5, we evaluate and present a proof-of-concept smartphone app. We then close the paper in Section 6 with concluding remarks and directions for future research. ## 2 Background and Related Work Strategies for automated mosquito identification based on wingbeat frequency analysis have been studied since 1945 (Kahn, Celestin, Offenhauser et al., 1945). For instance, work involving the use of audio recordings captured by acoustic devices for the identification of West African mosquito species date as early as 1947 (Kanh M. C., 1949). Nevertheless, the difficulty of collecting audio data with the available technology at the time left researchers capable of obtaining mosquito wingbeat recordings in controlled environments (e.g., laboratory) only (Chen, Why, Batista, Mafra-Neto and Keogh, 2014), which in turn influenced the quality of the classification models' results. To avoid such audio technology limitations, researchers have investigated alternatives like photosensors, trap optimization, and computational vision for mosquito classification (Li, Zhou, Shen and Yao, 2005; Potamitis, Rigakis and Fysarakis, 2015; Silva, Souza, Ellis, Keogh and Batista, 2015; Ouyang, Yang, Jiang and Lin, 2015; Potamitis and Rigakis, 2016; Kim, DeBriere, Cherukumalli, White and Burkett-Cadena, 2021). For example, Li et al. (2005) used photosensors' based dataset to classify five species of mosquitoes, including _Ae. aegypti_, in a controlled environment and obtained an accuracy of 72.67% using artificial neural networks. More recently, Ouyang et al. (2015) used infrared sensors to record and classify three different mosquito species at a sampling rate of 5,000Hz, and achieved an accuracy of up to 85.4% with a machine learning classifier (Gaussian mixture model trained using the expectation-maximization algorithm, EM-GMM). Similarly, some studies have explored the potential of using photosensors in passive mosquito traps (Silva, De Souza, Batista, Keogh and Ellis, 2013; Chen et al., 2014; Potamitis and Rigakis, 2016). Several studies have also proposed ways to improve mosquito recording using acoustic and visual stimuli (Johnson and Ritchie, 2016; Balestrino, Iyaloo, Elahee, Bheecarry, Campedelli, Carrieri and Bellini, 2016; Pantoja-Sanchez, Vargas, Ruiz-Lopez, Rua-Uribe, Velez, Kline and Bernal, 2019; Staunton, Crawford, Liu, Townsend, Han, Desnoyer, Howell, Xiang, Burkot, Snoad et al., 2020). Johnson and Ritchie (2016) investigated how to use male flight tones to attract female mosquitoes and thus improve their recording using non-mechanical passive Gravid Aedes Traps (GAT). In the same direction, Rohde, Staunton, Zeak, Beebe, Snoad, Bondarenco, Liddington, Anderson, Xiang, Mankin et al. (2019) used low-cost microcontrollers to generate frequency tones close to that emitted by female _Ae. aegypti_ mosquitoes for use in water-resistant and low-cost GAT traps. Balestrino et al. (2016) followed a similar approach and identified that _Aedes albopictus_ mosquitoes are more responsive to acoustic stimulation up to 4 days of age and that the black color of the trap positively influences capture. In the same direction, Villarreal, Winokur and Harrington (2017) analyzed the variation in mosquito wing flapping according to the environmental condition. They identified that the fundamental female frequency highly depends on the ambient temperature, increasing 8-13 Hz with each \({}^{\circ}\)C gain. Cator, Arthur, Harrington and Hoy (2009) further found that _Ae. aegypti_ mosquitoes change their wingbeat pitch to match during mating. In another direction, various authors used computer vision for mosquito recognition and tracking tasks (Motta, Santos, Winkler, Machado, Pereira, Cavalcanti, Fonseca, Kirchner and Badaro, 2019; Amiruddin and Abdul Kadir, 2020; Akter, Hossain, Ahmed and Andersson, 2021; Rakhmatulin, 2021; Adhane, Dehshibi and Masip, 2022). For instance, Motta et al. (2019) implemented a computational model based on a convolutional neural network (CNN) to extract features from mosquito images to identify adult mosquitoes of the species _Ae. aegypti_, _Aedes albopictus_, and mosquitoes of the genus _Culex_. More recently, with the advancement of technology and the quality of audio capture devices, the research community has again focused on traps based on acoustic sensors. Vasconcelos, Nunes, Ribeiro, Prandi and Rogers (2019) proposed using this type of sensor in GAT traps to capture the sound of flapping wings produced by mosquitoes in flight for automatic identification. However, trap-based approaches remain expensive for monitoring large areas requiring thousands of devices for adequate coverage. Conversely, devices with capture and processing capabilities, such as smartphones, have become ubiquitous in recent years. Mukundarajan et al. (2017) demonstrated that smartphones could be powerful tools for recording mosquito wingbeats, even those with the most basic functionalities. In a prior work, we investigated neural networks to recognize smartphone-recorded mosquito audio (Fernandes, Cordeiro and Recamonde-Mendoza, 2021). We used Mel scale-based audio spectrograms and a convolutional neural network to classify 22 mosquito species, including _Ae. aegypti_. In that work, we achieved an accuracy of 94.5% and 78.12% for multiclass classification considering the species individually and for a binary classification considering two groups: _Ae. aegypti_ vs other species. In the same direction, investigations using deep neural networks tried to improve classification results (Kiskin, Zilli, Li, Sinka, Willis and Roberts, 2020; Wei, Hossain and Ahmed, 2022). For example, Wei et al. (2022) used convolutional networks interspersed with self-attention layers to classify a sample set of mosquito audio samples. In another direction, attempts to obtain computationally lighter models were also explored (Yin, Haddawy, Nirandmongkol, Kongthaworn, Chaisumritchoke, Supratak, Sa-ngamuang and Sriwichai, 2021; Alar and Fernandez, 2021b; Toledo, Gonzalez, Nakano, Robles, Hernandez, Perez, Lanz and Cime, 2021; Alar and Fernandez, 2021a; Su Yin, Haddawy, Ziemer, Wetjen, Supratak, Chiamsakul, Siritanakorn, Chantanalertvilai, Sriwichai and Sa-ngamuang, 2022). Su Yin et al. (2022) proposed a technique involving audio sample rate reduction and lighter classification algorithms. In order to achieve smartphone apps capable of mosquito classification in the wild, we must address many practical challenges related to audio classification in non-controlled environments using off-the-shelf, popular smartphone hardware. Among these challenges is the amount of ambient noise, which can significantly affect the classification of sound events (Choi, Atif, Lee, Park and Chung, 2018) and the limited battery capabilities of the mobile device (Zhao, Xie, Wang, Cheng, Guo, Hu and Chen, 2022a). Some proposals were made to reduce ambient noise and mitigate the impact of noise on the classifier. Regarding audio enhancement, Salih (2017) used low-pass filters to reduce noise interference in audio quality. Regarding the classifier's quality, Yin, Liu, Zhang, Lin, Wang, Tejedor, Zheng and Li (2015) proposed the addition of random noise in the audio samples during the training stage to make the classifier more resilient to noise. In this paper, we explore these directions to improve precision and accuracy in mosquito wingbeat classification from audio recordings by means of a lightweight convolutional neural network. ## 3 Materials and Methods In this section, we present the materials and methods used to construct our solution based on deep learning. We start with Subsection 3.1 describing the audio sample collection process and detailing the available data set. In Subsection 3.2, we present the audio processing and feature extraction methods used and discuss aspects related to the characteristics and peculiarities of the processed audios. We describe the proposed neural network topology in Subsection 3.3. Finally, we define an evaluation model in Subsection 3.4. ### Collecting Mosquito Audio Recordings The datasets of raw audio files analyzed in this work can be organized into three sets, as detailed in Table 1: (i) recording samples containing no mosquitoes; (ii) recording samples containing mosquitoes that have been previously investigated; (iii) recording samples containing novel mosquito recordings. The first set helps to qualify the training of neural networks and to avoid bias in the evaluation process. The second set facilitates the comparison of the proposed solution with previous investigations in the field. The third set allows us to advance the state of the art with greater flexibility, as it was conceived, planned, and executed following specific research objectives. The first set (Raw recording set RD1) comprises recording samples from environments without mosquitoes and with different noise sources and intensity levels. These samples make the neural network more resilient to interference caused by environmental noise. They also balance the assessment fairly and thus avoid benefiting biased networks (e.g., a network trained to look for a _needle in a pile of needles_). To achieve these goals, we used the ESC-50 audio set (Piczak, 2015), which is publicly available and has been used in several studies (Gong, Chung and Glass, 2021; Zhao, Hessel, Yu, Lu, Zellers and Choi, 2022b). This set has 2000 audio samples from 40 different noise classes. Each audio sample lasts 5 seconds and has a sampling rate of 44.1kHz. For the second set of recordings (RD2, RD3, and RD4), we adopted the data generated by the Abuzz project (Mukundarajan et al., 2017). This set consists of 1,285 audio files, which include 20 species of mosquitoes. Audios available in this set were recorded using commercially available cell phones. In the original work (Mukundarajan et al., 2017), the authors compared eight smartphone models (eg, iPhone 4S and Xperia Z3 Compact). The authors concluded that all the evaluated devices could record the sound emitted by mosquitoes at a distance of up to 50 mm. Most of the sounds captured were from mosquitoes free-flying in various locations, with varying background noise levels. Laboratory recordings of tethered or caged mosquito populations were also performed for comparison. As a result, for example, authors found a significant increase in the degree of overlapping frequencies in records of populations trapped in the laboratory (with little noise) compared to records of free populations flying in different environments. The third set of audio recording samples (RD5, RD6, RD7, RD8, and RD9) we generated for the purposes of this investigation. We obtained recordings for different genera (e.g., _Aedes_, _Anopheles_), species (e.g., _Ae. aegypti_, _Ae. albopictus_), and sex (i.e., male and female). We performed the mosquito recordings at the insectary of the Federal University of Rio Grande do Sul (UFRGS), Porto Alegre, Brazil, from February 07, 2021 to February 22, 2021, between 08:37 AM and 09:17 PM. Mosquito ages during recording varied between 1 and 12 days. The ambient brightness was maintained at approximately 1,110 lux. The recordings were done using an LG K10 K430TV Octa-core 1.14GHz ARM Cortex-A53 1GB RAM Android 6.0 smartphone. The captured sounds were of free-flying mosquitoes in a cage with sizes between 5 and 10 cubic meters. The method chosen to keep the mosquitoes close to the microphone was using a glass with a shield to prevent further movement of the mosquito. We are publishing those audios so that practitioners can replicate our research, verify our results, and perform further investigation in the field. We combined the raw recording sets as described in Table 2 to create various benchmarking datasets. Our goal was to create a representative set of recordings with increasing complexity. For example, Dataset 1 (D1) is adequate to verify the presence or absence of _Ae. aegypti_, while Dataset 5 (D5) enables us evaluating the presence and classification among different species. Furthermore, Dataset 6 (D6) facilitates comparison with our previous work. ### Processing Audio to Extract Features Sound representation in the time and frequency domains are helpful as learning resources in audio classification (Huzaifah, 2017). Works investigating applications of this type of representation to problems related to machine learning, such as audio recognition and speech synthesis, have also been investigated (Tsompos, Pavlidis and Siozios, 2022; Shen, Pang, Weiss, Schuster, Jaitly, Yang, Chen, Zhang, Wang, Skerrv-Ryan, Saurous, Agiomvrgiannakis and Wu, 2018). For these reasons, \begin{table} \begin{tabular}{l l l l r r r} **Subset** & **ID** & **Species** & **Gender** & \begin{tabular}{c} Number of \\ Mosquitoes \\ \end{tabular} & \begin{tabular}{c} Number of \\ Recordings \\ \end{tabular} & \begin{tabular}{c} Recording Total \\ Length (s) \\ \end{tabular} \\ \hline \begin{tabular}{l l l l r r} No & RD1 & No mosquitoes & NA & 0 & 2,000 & 10,000 \\ \hline \begin{tabular}{l l l l r} Classic dataset & RD2 & _Ae. aegypti_ & F/M & 1 & 22 & 1,736 \\ (Mukundarajan et al., 2017) & RD3 & _Ae. albopictus_ & F/M & 1 & 7 & 966 \\ & RD4 & Non-_Aedes_ & NA & 1 & 871 & 13,237 \\ \hline \begin{tabular}{l l l l l} Novel dataset & RD5 & _Ae. aegypti_ & F & 1 & 192 & 4,607 \\ & RD6 & _Ae. aegypti_ & M & 1 & 345 & 8,279 \\ & RD7 & _Ae. albopictus_ & F & 1 & 19 & 570 \\ & RD8 & _Ae. albopictus_ & M & 1 & 17 & 510 \\ & RD9 & Non-_Aedes_ & NA & 0 & 158 & 4,740 \\ \hline \end{tabular} \end{table} Table 1: Raw audio datasets. NA stands for _Not Available_, F stands for _Female_, and M stands for _Male_. we adopt such representation in our work. Figure 1 illustrates the steps we used to transform audio datasets into features recognizable by neural networks in the time and frequency domains. We organized the process into three main steps: (1) Audio Pre-processing, (2) Audio Segmentation, and (3) Feature Extraction. These steps are detailed in the following paragraphs. **Audio Pre-processing**. This step aims to ensure that all audio files are standardized, with the same frequency and sample rate. For each file (step 1.1), we first apply a low-pass filter (1.2) with a frequency threshold of 4 KHz, corresponding to half of the desired sampling rate. This is due to the Nyquist-Shannon Theorem (Shannon, 1949), which states that to convert an analog signal into a digital signal that is reliable and viable, the sampling rate must be at least twice as high as the frequency of the signal of interest. Then we reduce the sample rate to 8KHz (1.3). This value is the lowest sampling rate present in the complete set of datasets, including the comparison set (D6) proposed in Mukundarajan et al. (2017) and previously used in Fernandes et al. (2021). We used the Audacity software (version 2.3.3 for Linux) to apply both the low pass filter and downsampling. **Audio Segmentation**. This step aims to divide an audio file into several smaller segments with some degree of overlap between them. Overlapping frames is a well know technique adopted to expand the number of samples available for classification and evaluation. As seen in the graphical representation, we generate overlapping frames through a sliding window. More specifically, we assume a given audio file and placeholder that initially points to the beginning of the file and can be \begin{table} \begin{tabular}{l l l r r} & & **Raw** & **Number of positive** & **Number of negative** \\ **ID** & **Description** & **Datasets** & **_Ae. aegypti_** & _Ae. aegypti_ \\ \hline D1 & M _Ae. aegypti_ plus No mosquitoes & \{RD1,RD6\} & 345 & 2,000 \\ D2 & F _Ae. aegypti_ plus No mosquitoes & \{RD1,RD5\} & 192 & 2,000 \\ D3 & F/M _Ae. aegypti_ plus No mosquitoes & \{RD1,RD5,RD6\} & 537 & 2,000 \\ D4 & F/M _Ae. aegypti_ plus Non-_Aedes_ mosquitoes & \{RD5,RD6,RD9\} & 537 & 158 \\ D5 & F/M _Ae. aegypti_ plus No mosquitoes & \{RD1-RD5-RD6-RD9\} & 537 & 2,158 \\ D6 & Original dataset (Mukundarajan et al., 2017) & \{RD2-RD3-RD4\} & 22 & 878 \\ \hline \end{tabular} \end{table} Table 2: Segmented audio datasets. F stands for _Female_ and M stands for _Male_. Figure 1: Steps involved in transforming audio datasets into audio features for neural networks. advanced. First, we copy an audio segment of size up to 1 window size \(W\) seconds (2.1). We then queue up the copied audio segment to be processed in the next step and advance the placeholder of the audio file by slide size \(S=W/2\) seconds. We chose this value for the slide size based on our previous study (Fernandes et al., 2021). Footnote 1: The file may be shorter than desired. **Feature Extraction**. This step aims to transform the audio segments into recognizable features for the neural network in the form of an image, as exemplified in Figure 2. Each segment/spectrogram/feature must be labeled to facilitate supervised training. The label is defined at a later stage as it varies according to the purpose of the study (e.g., to identify the presence of any mosquito or to identify the presence of a male _Ae. aegypti_ mosquito). First (step 3.1), we decompose the audio segment into a spectrogram by applying the Short-Term Fourier Transform (STFT) to extract features. The results obtained from this decomposition form a matrix with dimensions \(m\times n\times 1\). Each element in this matrix refers to a pixel in the spectrogram with the value corresponding to the signal strength in decibels of a given frequency (\(m\)) at a given point in time (\(n\)). The data received from the previous step are complex numbers whose real parts can have values in the range of -80 to 0 dB. Given this, we extract only the real part of the complex numbers and normalize the values to the interval [0,1] using Equation 1 (step 3.2), before generating the images (step 3.3). \[X_{norm}=\frac{x}{80}+1 \tag{1}\] From Figure 2, one can distinguish each of the generated spectrograms visually. For example, recordings containing samples of mosquitoes (Figure 2(a-f)) are characterized by the presence of specific patterns of harmonics distributed over several frequency bands of interest - a phenomenon that does not occur in samples having no mosquitoes (Figure 2(g)). We can also identify differences in harmonic distributions for each mosquito specie. For example, the fundamental frequency of the male _Ae. aegypti_ mosquito (Figure 2(a)) is considerably higher than the male _Ae. albopictus_ (Figure 2(c)). It is also possible to observe differences by analyzing the sex of the mosquito. Female mosquitoes (Figure 2(b,d)) have, in general, a lower frequency of emission and consequently a greater amount of harmonics than male mosquitoes (Figure 2(a,c)). Finally, observe that the methodology proposed in this work (e.g., Figure 2(a)) generates spectrograms with higher quality than the spectrograms generated by the process proposed in our previous work considering the same audio segment as input (Figure 2(h)). In short, with the removal of the Mel scale and other improvements, such as observance of the Shannon-Nyquist theorem, we can identify mosquitoes with closer sound emission ranges. ### Neural Networks Our approach to mosquito wingbeat sound classification relies on convolutional neural networks (CNNs). CNNs are deep learning network architectures used in various tasks, including speech and image recognition. An essential feature of this architecture for this application is its ability to recognize patterns and predict results based on input data. The CNNs are feedforward networks whose core architecture is based on convolutional and pool layers grouped in modules alternately (Rawat and Wang, 2017). Convolutional layers are used to extract features from the image by applying trainable convolutional filters while pooling layers progressively reduce the feature size. Our solution is based on a specific subtype of convolutional neural network based on residual blocks (He, Zhang, Ren and Sun, 2016). Residual CNNs have shown superior performance over traditional ones. We chose this architecture because it presents significantly better classification performance than pure convolutional models maintaining an equivalent number of parameters. ### Model Evaluation We use the datasets \(d\in\{D1,D2,D3,D4,D5\}\) in the evaluation process. For each dataset, we pre-process the respective audio files, generate the spectrograms that serve as input features for the neural networks, and label them according to the question of interest (e.g., is there the presence of _Ae. aegypti_ mosquito?). Then, we divided the results randomly into 10-folds and later used them in stages of training and testing the models following the cross-validation strategy. In the process of comparison with the topology previously proposed by Fernandes, Cordeiro and Recamonde-Mendoza (2021c), we tried to reproduce as much as possible the methodology proposed in that work. This includes using the same dataset, which we call \(D6\), and the same size and resolution of audio segments. The only change made to the methodology was applied to the dimensions of the input features (i.e., audio pre-processing output) to make data with different formats (e.g., size and resolution) compatible with our neural networks. For the quantitative evaluation of the results, we used traditional metrics that allow us to observe the results both from the point of view of hits (True Positives and True Negatives) and mistakes (False Positives and False Negatives). Specifically, we use the following metrics. * _Accuracy_: The proportion of instances in the test set that were correctly predicted, divided by the total number of instances in the test set. While precision is a commonly applied and easy-to-interpret metric, it can become an unreliable measure of model performance for class unbalanced datasets, especially for severe distortions in class distributions. Figure 2: Spectrograms of audio segments obtained from the D5 dataset generated using proposed (a-g) and prior (h) methodologies. * _Precision_: The number of correctly predicted positive instances (i.e., TP) divided by all positive predictions made by the model. Low precision indicates a high number of false positives. * _Recall_: The number of true positives predicted by the model divided by the total number of positive instances in the test set. The recall is also called Sensitivity or True Positive Rate, and a low recall indicates a high number of false negatives. * _F1-measure (F1)_: The harmonic mean between precision and recall, assigning equal weights to false positives and false negatives. ## 4 Proposed Approach Next we describe the proposed solution to the mosquito classification problem through wingbeat recording analysis. We start in Subsection 4.1 by presenting the proposed neural network topology and discussing its characteristics. We then describe in Subsection 4.2 the training process, list the parameters used, and analyze the model predictions through gradient-weighted class activation mapping. ### Topology Figure 3 presents the topology of the proposed neural network architecture. The input is formed by a two-dimensional matrix of real values in the interval \([0,1]\). We chose this configuration due to the format of the spectrograms that form the input features. The output is formed by a vector containing two real values contained in the interval \([0,1]\) that indicate the probability that the sample represents a sample labeled as true (for example, that contains evidence of an _Ae. aegypti_ mosquito2). Footnote 2: As will be seen in the next section, on training, we shaped the training specifically for the detection of mosquitoes of the _Ae. aegypti_ species, but we could adopt this same topology to identify other species by changing only the sample labels. The intermediate layers are formed by a configurable amount of one or more predefined arrays organized in series and, finally, exactly one classification block. In short, more arrays give a more accurate result but with a higher training and execution cost. Each array is formed by a sequence of three blocks: residual block, maxPooling2d, and dropout. We chose this configuration to allow the resource to shrink as it traverses each array, significantly reducing the network's computational cost. The use of a dropout layer is configured with a 20% decay in each arrangement and reduces the possibility of overfitting (Srivastava, Hinton, Krizhevsky, Sutskever and Salakhutdinov, 2014). The _residual block_ comprises two two-dimensional convolutional blocks with different filter sizes, Relu activation function, and step equal to (1,1), and a normalization block configured with epsilon=0.001. This configuration is similar to the one used in residual convolutional neural networks (He, Zhang, Ren and Sun, 2016; Liu, Mao, Wu, Feichtenhofer, Darrell and Xie, 2022). However, we adapted them to reduce the computational cost. Note that there is a connection from the input directly to the output parallel to the sequential flow. The results of the two streams are summed to generate the output values. This configuration, known as residual (He et al., 2016), was used to avoid gradient dissipation, which could reduce the model's effectiveness. The _classification block_ transforms the data processed by the neural network into results that are interpretable by the rest of the classification algorithm and consist of three layers. The idea of this configuration is to allow the results in the form of matrices obtained from the previous layer to be interpreted and returned in the form of an interpretable vector. This structure is commonly found in convolutional neural networks, for example, DenseNet (Huang, Liu, Van Der Maaten and Weinberger, 2017). The first is a layer known as flatten, which transforms the matrices from the previous layer into a vector of values. The subsequent two layers contain fully connected neurons with Relu activation function, with the first layer containing 256 neurons and the second having 2 neurons. ### Training To train the proposed neural network, we label each audio sample in a binary form indicating the presence (true) or absence (false) of _Ae. aegypti_ mosquitoes. In other words, in this study we did not try to classify samples according to sex or other species (e.g., _Ae. albopictus_, _Anopheles ultramiculatus_). For separating the samples and the training and validation set, we used the cross-validation process with 10 folds. In addition, to guarantee the correct balancing of the samples, we defined the probability of selecting a sample proportionally to the quantity of each class (positive or negative). This technique allows for a better balance between classes and helps to avoid possible bias related to sample proportions. Finally, as a loss, we adopt the Binary Crossentropy function as defined in Equation 2. \[\text{Loss}=-\sum_{i=1}^{\text{C}}y_{i}\cdot\log\,\hat{y}_{i} \tag{2}\] To reduce the influence of environmental noise on the results, we added environmental noise samples obtained from the ESC-50 dataset to the non-_Aedes_ mosquito sample set. This is an improvement over our previous work, in which we only considered samples containing mosquitoes (_Ae. aegypti_ vs. non-_Ae. aegypti_) in the training process. Although this strategy makes it possible to differentiate _Ae. aegypti_ mosquitoes from other species with a high level of accuracy, it tends to fail in an experimentation in the wild, where there is an infinite variety of sounds. This phenomenon should occur more frequently as the presence of sounds with frequencies become closer to _Ae. aegypti_ mosquitoes. Another precaution we adopted was to ensure a uniform distribution of samples within each of Figure 3: Proposed Neural Network Topology. the classes in the training set. This is because the number of labels is not uniform in the segmented audio datasets (Table 2). For example, dataset \(D1\) contains 345 positive samples and 495 negative samples. An imbalance can degrade the classifying process. To that end, we added an extra step in the cross-validation process, to establish different probabilities of selecting a sample of a given class based on the proportion of similar samples present in the set. In the development process, we use heatmaps based on Gradient-weighted Class Activation Mapping (Selvaraju, Cogswell, Das, Vedantam, Parikh and Batra, 2017). In this process, we extract the spectrograms of different positive and negative samples for _Ae. aegypti_ mosquitoes and submit them for classification through our pre-trained neural network model. Figure 4 shows activation maps for eight distinct audio samples. The warmer color regions represent areas of greater impact on the class prediction, while the darker areas represent the model's low affinity for the region. From the visual analysis, we can see the high specificity of the model for the patterns present in _Ae. aegypti_ positive samples. In particular, greater activation is observed in regions close to the frequencies of 450Hz and 900Hz for positive samples. We also found a greater affinity of the model for the first two harmonics of the sound of male _Ae. aegypti_ mosquitoes and for the first three harmonics of female _Ae. aegypti_ mosquitoes. We notice proposed solution (Figure 4(a)) shows more detailed maps than our prior solution (Figure 4(h)). ## 5 Experiments and Results We implemented the proposed neural network architecture using Python (v3.7.11). We used Tensorflow (v2.4.1) to implement the topology, Scypy (v1.10.1) and Librosa (v0.10.0) to extract features, and Scikit-learn (v1.1.0) to generate layering 10 -fold cross-validation. In this section, we present an evaluation of our proposal using our proof-of-concept implementation. In Subsection 5.1, we present Figure 4: Grad-CAM class activation map for different examples a parametric sensitivity evaluation of the proposed neural network. In Subsection 5.2, we present an evaluation of the effectiveness of the proposed neural network in comparison with state-of-the-art solutions. In Subsection 5.3, we present a proof of concept demonstrating the feasibility of running the proposed neural network on a low-cost smartphone. ### Parameter Sensitivity Analysis We start by evaluating the impact of model parametric values and input features on the results. Table 3 summarizes the main parameters and respective values considered in the evaluation. As the search space grows exponentially as a function of the number of combinations of parametric values, we adopted two strategies for pruning the branches of possibilities. First, we limit the number of free parameter values to three, for which we try to choose two threshold values, lower and upper, and an intuitively reasonable intermediate value. Second, we used a greedy strategy: we initially arbitrated an intermediate value for each parameter, looking for and fixing the best value for studying the following parameters. We consider the set of kernel filters \(K=[(3,3),(5,5),(7,7)]\) because they are widely used values in the literature. Regarding the impact of the number of blocks, we consider the set \(B=[3,4,5,6]\) as they are values in the range for which the number of parameters and filters of the neural network remains low, which favors performance. As for the frame size, we consider the set \(F=\{50,60,70\}\), as these values are equivalent to time intervals between \(2.5\) and \(5.0\) seconds of recording. For the STFT window size, we evaluated the set of values \(W=\{512,1024,2048\}\) since they are values commonly used for audios with a sampling rate below \(8\)kHz. For the number of filters per block \(P=\{16,32,64\}\) and hop length \(H=\{128,256,512\}\), we tried to verify relatively small values to simplify the processing but generated satisfactory results. Figure 5 presents the result of the evaluation for six parameters: size of filters (\(F\)), number of \begin{table} \begin{tabular}{l l l l} & **Parameter** & **Symbol** & **Values** \\ \hline \multirow{4}{*}{\begin{tabular}{} \end{tabular} } & Dataset & \(D\) & \(\{D1,D2,D3,D4,D5\}\) \\ & Size of Frame & \(F\) & \(\{50,60,70\}\) \\ & Size of STFT Window & \(W\) & \(\{256,512,1024\}\) \\ & Hop Length & \(H\) & \(\{128,256,512\}\) \\ \hline \multirow{4}{*}{\begin{tabular}{} \end{tabular} } & Size of Kernel Filters & \(K\) & \(\{(3,3),(5,5),(7,7)\}\) \\ & Number of Blocks & \(B\) & \(\{3,4,5\}\) \\ & Filters Per Block & \(P\) & \(\{16,32,64\}\) \\ & Sample Rate & & \(8\) KHz \\ & Size Batch & & \(32\) \\ & Feature Type Scale & & Short Time Fourier Transform \\ & Loss Function & & Binary Crossentropy \\ \hline \multirow{4}{*}{ \begin{tabular}{} \end{tabular} } & Cloud & OS: Ubuntu 20.04.3 LTS \\ & & & CPU: Intel Xeon Gold 6330 3.1GHz \\ \cline{1-1} & & & GPU: Nvidia Tesla V100 16GB \\ \cline{1-1} & & & RAM: 32GB \\ \cline{1-1} & Smartphone & & OS: Android v8-10 \\ \cline{1-1} & & & CPU: Cortex-A53 1.5GHz Quad Core \\ \cline{1-1} & & & RAM: 2 GB \\ \hline \end{tabular} \end{table} Table 3: Evaluation settings. blocks (\(B\)), size of the frame (\(F\)), size of the window (\(W\)), number of filters (\(F\)) and Hop length (\(L\)). Each graph presents the impact of three distinct values on each of the four metrics of interest. Each bar shows the mean and standard deviation of 10 repetitions. In this study, we used only the D5 dataset as input, which we consider the most challenging. Figure 5(a) shows the impact of varying the size of the filters (\(K=\{(3.3),(5.5),(7.7))\}\) convolutional on the analyzed metrics. The results suggest that the parameter has a low impact on the overall results and that the filter size \(K=(5,5)\) has a slight advantage over the others. Figure 5(b) shows the impact of varying the number of blocks (\(B=\{3,4,5\}\)) on the metrics and suggests that the number of blocks \(B=4\) presents the best result. Figure 5(c) shows that the impact of varying frame sizes on prediction quality is small. Therefore, we considered the frame size equal to \(F=60\), as it presents a more balanced result between the evaluated metrics and the recording time interval. The sensitivity is also small for the window size of the STFT \(W\), as shown in Figure 5(d)), and for which we adopted the value \(W=1024\). Figure 5(e) shows that the number of blocks per filter \(P\) tends to generate a lower mean and a higher standard deviation impact for value \(P=64\), so we adopted a lower value \(P=32\). Finally, Figure 5(f) shows that the hop length \(H\) tends to generate a lower mean and a higher standard deviation impact for the extreme values and, therefore, we adopted the central value \(H=256\). As a result of this step, we adopted the following configurations for the rest of the evaluations: filter size \(K=(5,5)\), number of blocks \(B=5\), frame size \(F=60\), window size of the STFT \(W=1024\), number of filters per block \(P=32\) and hop length \(H=256\). Figure 5: Neural network sensitivity to values for multiple parameters (Dataset \(=D5\)) ### Efficacy We divided the evaluation of the efficacy of our model into two stages. First, we consider the results predicted by the model for each of the six available datasets. In the second, we compare our model with the current state of the art considering our most challenging scenario (\(D5\)) and the dataset used in the referred work (\(D6\)). Figure 6 shows the results obtained for all six datasets. We display four bars for each dataset: one bar for each metric of interest showing the respective means and standard deviation for 10 executions. It is possible to observe that in all evaluated scenarios, our model obtained a score greater than 80% for each of the considered metrics. Two other important observations concern the degree of complexity of each evaluated dataset. First, datasets D1 and D5 have average scores 9.25% lower than the other datasets. One of the hypotheses for this behavior is that male _Ae. aegypti_ samples present in both datasets are considerably more difficult to be classified than the others. Second, it seems equally challenging to distinguish between different groups of mosquitoes and ambient noise samples. Our main hypothesis for this behavior is the presence of ambient noise in samples positive for mosquitoes. This situation could cause the prediction model not to be able to distinguish between positive samples and negative samples. In particular, this last observation is important because in real application scenarios, for example, within smart mosquito traps, ambient noise could reduce the classifier's efficiency. In Figure 7, we present the confusion matrices obtained for each of the six datasets. The display of records is performed in terms of their current classes and their predicted classes. True labels are arranged in rows, and predicted labels are in columns. Each cell represents the average of samples sorted during the cross-validation process. The presence of higher values on the matrix's diagonal demonstrates the model's predictive capacity, as they add up to represent the total number of hits in the model. It is possible to verify that in all the evaluated scenarios, the values on the diagonal are higher concerning the others - this is a strong indication of the high predictive capacity of the proposed model. As another observation, we did not find evidence of shortcomings in classifying that could indicate a preference for a specific label. Figure 8 presents the results obtained with datasets D5 and D6 for the two neural networks (current and prior). For each dataset, eight bars are presented, representing the performance metrics for each neural network. Like the other plots above, each bar represents the mean and standard deviation obtained through cross-validation after ten runs. Figure 6: Performance of the proposed solution considering multiple datasets (\(D=\{D1,D2,D3,D4,D5,D6\}\)) From Figure 8, we can observe that in both datasets and in all metrics, our current algorithm performed better than the state-of-the-art. In the comparison using the D5 dataset, our algorithm presented an average score of 4.16% higher than the original algorithm. In the comparison using the D6 dataset, our algorithm presented a lower average score, approximately 1%. A final observation is that the D5 dataset appears more challenging than the D6 dataset. ### Proof of Concept: Testing the Residual CNN in a Smartphone App As a proof of concept, we developed an Android-based smartphone app for identifying _Ae. aegypti_ mosquitoes in a semi-controlled environment. From our experiments, the app has shown to meet the necessary performance requirements for popular off-the-shelf smartphones as it does not require substantial processing power and has a minimum OS requirement for Android Oreo 8.1 (as of today, the current version is 13). The app's interface has three components: (i) a frame that displays the spectrogram (STFT) resulting from the decomposition of the recorded audio; (ii) a sound intensity identifier frame; and (iii) a number on a percentage scale identifying the probability that the sample contains signs of an _Ae. aegypti_ mosquito. We wrote the smartphone app in Java (v8.0) and C++ (v11) and built the user interface on top of standard Android libraries. We adopted the following techniques to reduce the model prediction time and save battery. First, we implemented the mathematical operations of the Fourier transform Figure 7: Detailed performance of the proposed solution considering multiple datasets (\(D=\{D1,D2,D3,D4,D5,D6\}\)) in C++ and compiled them for the ARM x64 architecture. We trained the neural network using cloud computing and executed it in the smartphone through the TensorFlow Lite library (v2.1.0), which implements low-level functions. We developed the neural network to have the minimum possible number of parameters to reduce computing and energy costs. In total, the developed model has about 1 million (927,458) trainable parameters. This value is 18.5% smaller than the previous network, which had about 1.2 million (1,137,858) parameters. The value of our current network is also considered low compared to models such as ResNet152 He et al. (2016a), which has approximately 60 million parameters, and DenseNet201 Huang et al. (2017), which has approximately 20 million parameters. We also adopted optimizations related to the model and the interpreter to run the app on popular smartphones. During the training stage, the model underwent a dynamic range quantization process. This technique reduced the model size by 18.5% and reduced the inference time by approximately 2 times, keeping the model's effectiveness virtually unchanged. Regarding the interpreter, we adopted two optimization strategies. First, we used the multiple processing threads option, which reduced the inference time. Second, we used an inference pipeline that performs the feature extraction flow, classification, and results display independently. We ran the app on an Asus Zenfone Max M3 Qualcomm Snapdragon 430 64-bit Octa core 4G RAM Android 8.1 and a Motorola Moto E6 Play Cortex-A53 1.5 GHz Quad Core 2 GB RAM Android 9.0 smartphones, both entry-level models in Brazil at the time of release. The average time for each inference was approximately 320 ms. We consider that in an environment with semi-controlled noise (a biology laboratory without acoustic isolation), the model presented high stability to identify the presence of _Ae. aegypti_ mosquito effectively. This fact is illustrated by Figure 9, which presents a sequence of 8 images3 captured during a laboratory test of the application with _Ae. aegypti_ mosquitoes. The sequence shows: (a) Recording of ambient noise with the prediction of low probability of _Ae. aegypti_ mosquito; (b) Increased ambient noise level with low probability prediction of _Ae. aegypti_ mosquito; (c) Smartphone closes to the cage containing _Ae. aegypti_ mosquitoes; (d) Identification of increased probability of predicted _Ae. aegypti_ mosquito; (e) High probability for predicted _Ae. aegypti_ class; (f) High probability continuity for predicted _Ae. aegypti_ class; (g) Removing the smartphone from the mosquito Figure 8: Comparison with the state-of-the-art (\(D=\{D5,D6\}\)) cage and consequent reduction in the probability; (h) Complete removal of the mosquito cage and sudden reduction of probability for _Ae. aegypti_ mosquitoes. ## 6 Final Considerations Using a device that is universally present in modern society, such as the smartphone, can be an important weapon in tackling the proliferation of _Ae. aegypti_ mosquitoes. However, we need to overcome several practical challenges, including the limitation of existing datasets and computational constraints of devices used by the target audience. In this work, we: (i) present a new dataset, (ii) propose a neural network topology, (iii) develop a training method as steps towards the implementation of monitoring applications of _Ae. aegypti_ mosquitoes on low-cost mobile devices. The results of an evaluation with unpublished and pre-existing real datasets show the advance provided by our proposal towards state-of-the-art. The Figure 9: Sequence of images of a test with mosquitoes carried out in the laboratory proposed neural network is 18.5% smaller in terms of the number of parameters, which is the main computational efficiency factor of the technique. The lean neural network combined with the improved training technique can generate results equivalent to or slightly superior to state-of-the-art in terms of accuracy, precision, recall, and F1 in all considered scenarios. In addition, implementing a functional prototype demonstrates the feasibility of running (without failures and crashes) the proposed solution on popular smartphones. As future work, we envision three main research directions: expanding the study to other devices, expanding the dataset, expanding the comparison with other state-of-the-art works, evaluating the execution in even more limited devices such as IoT, advancing the development of neural networks to update with advances in the area, develop techniques to make the neural network resistant to noise generated deliberately by malicious users attempting to induce false positives. ## Acknowledgements We thank Prof. Dr. Goncalo Nuno Corte Real Ferraz de Oliveira (UFRGS, Brazil) for his contributions to this study. This study was financed in part by the Coordenacao de Aperfeicoamento de Pessoal de Nivel Superior - Brasil (CAPES) - Finance Code 001. We also received funding from Rio Grande do Sul Research Foundation (FAPERGS) (grants 22/2551-0000841-0, 22/2551-0000390-7, and 22/2551-0000603-5) and NVIDIA - Academic Hardware Grant.
2307.13869
Good Lattice Training: Physics-Informed Neural Networks Accelerated by Number Theory
Physics-informed neural networks (PINNs) offer a novel and efficient approach to solving partial differential equations (PDEs). Their success lies in the physics-informed loss, which trains a neural network to satisfy a given PDE at specific points and to approximate the solution. However, the solutions to PDEs are inherently infinite-dimensional, and the distance between the output and the solution is defined by an integral over the domain. Therefore, the physics-informed loss only provides a finite approximation, and selecting appropriate collocation points becomes crucial to suppress the discretization errors, although this aspect has often been overlooked. In this paper, we propose a new technique called good lattice training (GLT) for PINNs, inspired by number theoretic methods for numerical analysis. GLT offers a set of collocation points that are effective even with a small number of points and for multi-dimensional spaces. Our experiments demonstrate that GLT requires 2--20 times fewer collocation points (resulting in lower computational cost) than uniformly random sampling or Latin hypercube sampling, while achieving competitive performance.
Takashi Matsubara, Takaharu Yaguchi
2023-07-26T00:01:21Z
http://arxiv.org/abs/2307.13869v1
# Good Lattice Training: Physics-Informed Neural Networks Accelerated by Number Theory ###### Abstract Physics-informed neural networks (PINNs) offer a novel and efficient approach to solving partial differential equations (PDEs). Their success lies in the physics-informed loss, which trains a neural network to satisfy a given PDE at specific points and to approximate the solution. However, the solutions to PDEs are inherently infinite-dimensional, and the distance between the output and the solution is defined by an integral over the domain. Therefore, the physics-informed loss only provides a finite approximation, and selecting appropriate collocation points becomes crucial to suppress the discretization errors, although this aspect has often been overlooked. In this paper, we propose a new technique called _good lattice training_ (GLT) for PINNs, inspired by number theoretic methods for numerical analysis. GLT offers a set of collocation points that are effective even with a small number of points and for multi-dimensional spaces. Our experiments demonstrate that GLT requires 2-20 times fewer collocation points (resulting in lower computational cost) than uniformly random sampling or Latin hypercube sampling, while achieving competitive performance. ## 1 Introduction Many real-world phenomena can be modeled as partial differential equations (PDEs), and solving PDEs has been a central topic in the field of computational science. The applications include, but are not limited to, weather forecasting, vehicle design [14], economic analysis [2], and computer vision [23]. A PDE is defined as \(\mathcal{N}[u]=0\), where \(\mathcal{N}\) is a (possibly nonlinear) differential operator, \(u:\Omega\rightarrow\mathbb{R}\) is an unknown function, and \(\Omega\subset\mathbb{R}^{s}\) is the domain. For most PDEs that appear in physical simulations, the well-posedness (i.e., the uniqueness of the solution \(u\) and the continuous dependence on the initial and the boundary conditions) has been well studied, and this is typically guaranteed under certain conditions. Various computational methods, such as finite difference, finite volume, and spectral methods, have been explored for solving PDEs [9; 29; 39]. However, the development of computer architecture has become slower, leading to a growing need for computationally efficient alternatives. A promising approach is physics-informed neural networks (PINNs) [33], which train a neural network so that its output \(\tilde{u}\) satisfies the PDE \(\mathcal{N}[\tilde{u}]=0\). Specifically, given a PDE, PINNs train a neural network to minimize the squared error \(\|\mathcal{N}[\tilde{u}](\mathbf{x}_{i})\|^{2}\) at a finite set of collocation points \(\mathbf{x}_{i}\) so that the output \(\tilde{u}\) satisfies the equation \(\mathcal{N}[\tilde{u}](\mathbf{x}_{i})=0\). This objective, known as the physics-informed loss (or PINNs loss), constitutes the core idea of PINNs [42; 43]. However, the solutions \(u\) to PDEs are inherently infinite-dimensional, and the distance involving the output \(\tilde{u}\) or the solution \(u\) must be defined by an integral over the domain \(\Omega\). In this regard, the physics-informed loss is a finite approximation to the squared 2-norm \(|\mathcal{N}[\tilde{u}]|_{2}^{2}=\int_{\Omega}\|\mathcal{N}[\tilde{u}](\mathbf{x}_ {i})\|^{2}\mathrm{d}\mathbf{x}\) on the function space \(L^{2}(\Omega)\) for \(\mathcal{N}[u]\in L^{2}(\Omega)\), and hence the discretization errors should affect the training efficiency. A smaller number \(N\) of collocation points leads to a less accurate approximation and inferior performance, while a larger number \(N\) increases the computational cost [3; 37]. Despite the importance of selecting appropriate collocation points, insufficient emphasis has been placed on this aspect. Raissi et al. [33], Zeng et al. [48], and many other studies employed Latin hypercube sampling (LHS) to determine the collocation points. Alternative approaches include uniformly random sampling [15; 21] and uniformly spaced sampling [44; 45]. These methods are exemplified in Fig. 1. In the field of numerical analysis, the relationship between integral approximation and collocation points has been extensively investigated. Inspired by number theoretic methods for numerical analysis, we propose _good lattice training (GLT)_ for PINNs and their variants. The GLT provides an optimal set of collocation points, as shown in Fig. 1, when the activation functions of the neural networks are smooth enough. Our experiments demonstrate that the proposed GLT requires far fewer collocation points than comparison methods while achieving similar errors, significantly reducing computational cost. The contribution and significance of the proposed GLT are threefold. Computationally Efficient:The proposed GLT offers an optimal set of collocation points to compute a loss function that can be regarded as a finite approximation to an integral over domain, such as the physics-informed loss, if the activation functions of the neural networks are smooth enough. It requires significantly fewer collocation points to achieve accuracy comparable to other methods, or can achieve lower errors with the same computational budget. Applicable to PINNs Variants:As the proposed GLT involves changing only the collocation points, it can be applied to various versions of PINNs without modifying the learning algorithm or objective function. In this study, we investigate a specific variant, the competitive PINN (CPINN) [48], and demonstrate that CPINNs using the proposed GLT achieve superior convergence speed with significantly fewer collocation points than CPINNs using LHS. Theoretically Solid:Number theory provides a theoretical basis for the efficacy of the proposed GLT. This guarantees the general applicability of GLT and enables users to assess its suitability for a given problem setting prior to implementation. ## 2 Related Work Neural Networks for Data-Driven PhysicsNeural networks have emerged as a powerful tool for processing information from data and have achieved significant success in various fields such as image recognition and natural language processing in recent years [12; 41]. They are also employed for black-box system identification, that is, to learn the differential equations that govern the dynamics of a target system and predict its future behavior [4; 5; 46]. By integrating knowledge from analytical mechanics, neural networks can learn the dynamics that adheres to physical laws, such as the conservation of energy, and even uncover these laws from data [8; 10; 28]. Physics-Informed Neural NetworksNeural networks have also gained attention as computational tools for solving differential equations, particularly PDEs [6; 22]. Recently, Raissi et al. [33] introduced an elegant refinement to this approach and named it PINNs. The key concept behind PINNs is the physics-informed loss, also known as PINNs loss [42; 43]. This loss function evaluates the extent to which the output \(\tilde{u}\) of the neural network satisfies a given PDE \(\mathcal{N}[u]=0\) and its associated initial and boundary conditions \(\mathcal{B}[u]=0\). The physics-informed loss can also be integrated into other models like DeepONet [25; 43]. These advancements have been made possible by recent developments in automatic differentiation algorithms, which allow us to automatically compute the partial derivatives of neural networks' outputs [31]. Figure 1: Examples of 144 sampled collocation points. PINNs have already been applied to various PDEs [3; 15; 27], and considerable efforts have been dedicated to improving learning algorithms and objective functions [11; 13; 26; 32; 37; 48]. In these studies, the loss functions based on PDE rather than data, including the original physics-informed loss, are defined by evaluating errors at a finite set of collocation points. As shown in [3; 37], there is a trade-off between the number of collocation points (and hence computational cost) and the accuracy of the solution. Thus, selecting collocation points that efficiently cover the entire domain is essential for achieving better results, although this aspect has often been overlooked. An exceptional instance is found in Mao et al. [27], in which more collocation points were sampled around regions where the solution is discontinuous, efficiently capturing the discontinuity. However, such an approach is not always feasible. ## 3 Method PreliminaryFor simplicity, we consider the cases where the target PDE is defined on an \(s\)-dimensional unit cube \([0,1]^{s}\). Otherwise, the equations should be transformed to such a domain by an appropriate coordinate transformation. Methods for reducing computations on complex regions to those on rectangular regions have been studied in the research field of grid generation for domain decomposition methods. See [18; 40] for example. PINNs employ the PDE that describes the target physical phenomena as loss functions. Specifically, first, the appropriate collocation points \(\{\mathbf{x}_{j}\mid j=1,\ldots,N\}\) are fixed, and then the sum of the residuals of the PDE at these points \[\frac{1}{N}\sum_{j=1}^{N}\|\mathcal{N}[\tilde{u}](\mathbf{x}_{j})\|^{2} \tag{1}\] is minimized. \(\tilde{u}\) is an approximate solution of the equation represented by a neural network. This type of loss function is referred to as a physics-informed loss. Although the sum of such residuals over collocation points is practically minimized, for \(\tilde{u}\) to be the exact solution, this physics-informed loss should be 0 for all \(\mathbf{x}\), not just at collocation points. Therefore, the loss function defined by the following integral must be minimized: \[\int_{[0,1]^{s}}\|\mathcal{N}[\tilde{u}](\mathbf{x})\|^{2}\mathrm{d}\mathbf{x}. \tag{2}\] In other words, the practical minimization of (1) essentially minimizes the approximation of (2) with the expectation that (2) will be small enough and hence \(\tilde{u}\) becomes an accurate approximation to the exact solution. One of the typical methods often used in practice is to set \(\mathbf{x}_{j}\)'s to be uniformly distributed random numbers. PINNs typically target PDEs in multi-dimensional domains, and the loss function is often integrated over a certain multi-dimensional domain. In such multi-dimensional integration, the effect of the curse of dimensionality cannot be ignored. The method of sampling collocation points from the uniform distributions can be interpreted as the Monte Carlo approximation of the value of the integral (2). As is well known, the Monte Carlo method is not affected by the curse of dimensionality and can approximate the integral within an error of \(O(1/\sqrt{N})\)[38]. Therefore, such a choice of collocation points is reasonable for computing the physics-informed loss in multi-dimensional domains. However, if feasible, a method less affected by the curse of dimensionality and more efficient than the Monte Carlo method is desired. In this paper, we propose such a method, which is inspired by number theoretic numerical analysis. Good Lattice Training: Number Theoretic Method for Computing Physics-Informed LossIn this section, we propose the _good lattice training (GLT)_, in which a number theoretic method is used to accelerate the training of PINNs. The proposed method is inspired by the number theoretic numerical analysis [30; 38; 47], and hence in the following, we use some tools from this theory. First, we define a lattice for computing the loss function. **Definition 1** ([30; 38; 47]).: _A lattice \(L\) in \(\mathbb{R}^{s}\) is defined as a finite set of points in \(\mathbb{R}^{s}\) that is closed under addition and subtraction._ Given a lattice \(L\), the set of collocation points is defined as \(L^{*}=\{\mathbf{x}_{1},\ldots,\mathbf{x}_{N}\}\coloneqq L\cap[0,1]^{s}\). In this paper, we consider an appropriate lattice for computing the physics-informed loss. Considering that the loss function to be minimized is (2), it is natural to determine the lattice \(L\) (and hence the set of collocation points \(\mathbf{x}_{j}\)'s) so that the difference \(|(2)-(1)|\) of the two loss functions is minimized. Suppose that \(\varepsilon(\mathbf{x}):=\|\mathcal{N}[\tilde{u}](\mathbf{x})\|^{2}\) is smooth enough and admits the Fourier series expansion: \[\varepsilon(\mathbf{x})\coloneqq\|\mathcal{N}[\tilde{u}](\mathbf{x})\|^{2}=\sum_{\mathbf{ h}}\hat{\varepsilon}(\mathbf{h})\exp(2\pi\mathrm{i}\mathbf{h}\cdot\mathbf{x}),\] where \(\mathrm{i}\) denotes the imaginary unit and \(\mathbf{h}=(h_{1},h_{2},\ldots,h_{s})\in\mathbb{Z}^{s}\). Substitution of this Fourier series into \(|(2)-(1)|\) yields \[\begin{split}\left|\int_{[0,1]^{s}}\|\mathcal{N}[\tilde{u}](\bm {x})\|^{2}\mathrm{d}\mathbf{x}-\frac{1}{N}\sum_{j=1}^{N}\sum_{\mathbf{h}\in\mathbb{Z}^ {s}}\hat{\varepsilon}(\mathbf{h})\exp(2\pi\mathrm{i}\mathbf{h}\cdot\mathbf{x}_{j})\right| \\ =\left|\frac{1}{N}\sum_{j=1}^{N}\sum_{\mathbf{h}\in\mathbb{Z}^{s},\bm {h}\neq 0}\hat{\varepsilon}(\mathbf{h})\exp(2\pi\mathrm{i}\mathbf{h}\cdot\mathbf{x}_{j}) \right|,\end{split} \tag{3}\] where the equality follows from the fact that the Fourier mode of \(\mathbf{h}=0\) is equal to the integral \(\int_{[0,1]^{s}}\|\mathcal{N}[\tilde{u}](\mathbf{x}_{j})\|^{2}\mathrm{d}\mathbf{x}\). Before optimizing (3), the dual lattice of lattice \(L\) and an insightful lemma are introduced as follows. **Definition 2** ([30, 38, 47]).: _A dual lattice \(L^{\top}\) of a lattice \(L\) is defined as \(L^{\top}\coloneqq\{\mathbf{h}\in\mathbb{R}^{s}\mid\mathbf{h}\cdot\mathbf{x}\in\mathbb{Z},\ ^{\forall}\mathbf{x}\in L\}\)._ **Lemma 1** ([30, 38, 47]).: _For \(\mathbf{h}\in\mathbb{Z}^{s}\), it holds that_ \[\frac{1}{N}\sum_{j=1}^{N}\exp(2\pi\mathrm{i}\mathbf{h}\cdot\mathbf{x}_{j})=\begin{cases} 1&(\mathbf{h}\in L^{\top})\\ 0&(\mathrm{otherwise}.)\end{cases}\] Based on this lemma, we restrict the lattice point \(L\) to the form \(\{\mathbf{x}\mid\mathbf{x}=\mathbf{s}+\frac{j}{N}\mathbf{z}\text{ for }\mathbf{s}\in\mathbb{Z}^{s},j\in \mathbb{Z}\}\) with a fixed integer vector \(\mathbf{z}\); the set \(L^{*}\) of collocation points is \(L\cap[0,1]^{s}=\{\text{decimal part of }\frac{j}{N}\mathbf{z}\mid j=0,\ldots,N-1\}\). Then, instead of searching \(\mathbf{x}_{j}\)'s, a vector \(\mathbf{z}\) is searched. This form has the following advantages. By restricting to this form, \(\mathbf{x}_{j}\)'s can be obtained automatically from a given \(\mathbf{z}\), and hence the optimal collocation points \(\mathbf{x}_{j}\)'s do not need to be stored as a table of numbers, making a significant advantage in implementation. Another advantage is theoretical; the optimization problem of the collocation points can be reformulated in a number theoretic way. In fact, for \(L\) as shown above, it is confirmed that \(L^{\top}=\{\mathbf{h}\mid\mathbf{h}\cdot\mathbf{z}\equiv 0\pmod{N}\}\). If \(\mathbf{h}\cdot\mathbf{z}\equiv 0\pmod{N}\) then there exists an \(m\in\mathbb{Z}\) such that \(\mathbf{h}\cdot\mathbf{z}=mN\) and hence \(\frac{j}{N}\mathbf{h}\cdot\mathbf{z}=mj\in\mathbb{Z}\). Conversely, if \(\mathbf{h}\cdot\mathbf{z}\not\equiv 0\pmod{N}\), clearly \(\frac{1}{N}\mathbf{h}\cdot\mathbf{z}\notin\mathbb{Z}\). Therefore, from the above lemma, (3) is bounded from above by \[\sum_{\mathbf{h}\in\mathbb{Z}^{s},\mathbf{h}\neq 0,\mathbf{h}\cdot\mathbf{z}\equiv 0\pmod{N}}| \hat{\varepsilon}(\mathbf{h})|, \tag{4}\] and hence the collocation points \(\mathbf{x}_{j}\)'s should be determined so that (4) becomes small. This problem is a number theoretic problem in the sense that it is a minimization problem of finding an integer vector \(\mathbf{h}\) subject to the condition \(\mathbf{h}\cdot\mathbf{z}\equiv 0\pmod{N}\). This problem has been considered in the field of number theoretic numerical analysis. In particular, optimal solutions have been investigated for integrands in the Korobov spaces, which are spaces of functions that satisfy a certain smoothness condition. **Definition 3** ([30, 38, 47]).: _The function space that is defined as \(E_{\alpha}=\{f:[0,1]^{s}\to\mathbb{R}\mid\exists c,|\hat{f}(\mathbf{h})|\leq c/( \bar{h}_{1}\bar{h}_{2}\cdots\bar{h}_{s})^{\alpha}\}\) is called the Korobov space, where \(\hat{f}(\mathbf{h})\) is the Fourier coefficients of \(f\) and \(k=\max(1,|k|)\) for \(k\in\mathbb{R}\)._ It is known that if \(\alpha\) is an integer, for a function \(f\) to be in \(E_{\alpha}\), it is sufficient that \(f\) has continuous partial derivatives \(\partial^{q_{1}+q_{2}+\cdots+q_{s}}f/\partial_{1}^{q_{1}}\cdot\partial_{2}^{q_ {2}}\cdots\partial_{s}^{q_{s}},0\leq q_{k}\leq\alpha\ (k=1,\ldots,s)\). For example, if a function \(f(x,y):\mathbb{R}^{2}\to\mathbb{R}\) has continuous \(f_{x},f_{y},f_{xy}\), then \(f\in E_{1}\). The main result of this paper is the following. **Theorem 1**.: _Suppose that the activation function of \(\tilde{u}\) and hence \(\tilde{u}\) itself are sufficiently smooth so that there exists an \(\alpha>0\) such that \(\|\mathcal{N}[\tilde{u}]\|^{2}\in E_{\alpha}\). Then, for given integers \(N\geq 2\) and \(s\geq 2\), there exists an integer vector \(\mathbf{z}\in\mathbb{Z}^{s}\) such that \(L^{*}=\{\text{decimal part of }\frac{j}{N}\mathbf{z}\mid j=0,\ldots,N-1\}\) is a "good lattice" in the sense that_ \[\int_{[0,1]^{s}}\|\mathcal{N}[\tilde{u}](\mathbf{x})\|^{2}\mathrm{d}\mathbf{x}\leq \frac{1}{N}\sum_{\mathbf{x}_{j}\in L^{*}}\|\mathcal{N}[\tilde{u}](\mathbf{x}_{j})\|^{2 }+O\left(\frac{(\log N)^{\alpha s}}{N^{\alpha}}\right). \tag{5}\] For a proof of this theorem, see Appendix A. In this paper, we call the learning method that minimizes \[\frac{1}{N}\sum_{\mathbf{x}_{j}\in L^{*}}\|\mathcal{N}[\tilde{u}](\mathbf{x}_{j})\|^{2}\] for a lattice \(L\) that satisfies (5) _the good lattice training (GLT)_. The proposed GLT, of which the order of the convergence is \(O(\frac{(\log N)^{\alpha s}}{N^{\alpha}})\), can converge much faster to the integrated loss (2) than the uniformly random sampling (i.e., the Monte Carlo method, of which the order of the convergence is \(O(1/\sqrt{N})\)) if the activation function of \(\tilde{u}\) and hence the neural network \(\tilde{u}\) itself are sufficiently smooth so that \(\mathcal{N}[\tilde{u}]\in E_{\alpha}\) for a large \(\alpha\). Furthermore, the error increases only in proportion to \((\log N)^{\alpha s}\) as the dimension increases. Therefore, the proposed GLT remains effective for high-dimensional problems, almost unaffected by the curse of dimensionality. This makes PINNs available for higher dimensional problems. Although the above theorem shows the existence of a good lattice, we can obtain a good lattice in the following way in practice. When \(s=2\), we can use the Fibonacci sequence \(1,1,2,3,5,8,13,\ldots\), which is defined by \(F_{1}=F_{2}=1,\;F_{k}=F_{k-1}+F_{k-2}\;(k\geq 3)\). It is known that by setting \(N=F_{k}\) and \(\mathbf{z}=(1,F_{k-1})\)[30, 38], we obtain a good lattice. For example, when \(N=13\), \(\mathbf{z}=(1,8)\) gives a good lattice \(L=\{(0,0),(\frac{1}{13},\frac{8}{13}),(\frac{2}{13},\frac{3}{13}),(\frac{3}{13 },\frac{11}{13}),\ldots\}\). When \(s=2\) and \(N\) is not a Fibonacci number, or when \(s>2\), there is no known method to generate a good lattice using a sequence of numbers. However, it is possible to numerically find the optimal \(\mathbf{z}\) for a given \(N\) with a computational cost of \(O(N^{2})\). The procedure is as follows: First, if \(\|\mathcal{N}[\tilde{u}]\|^{2}\) belongs to Koborov space, then (4) can be estimated as \[\sum_{\mathbf{h}\in\mathbb{Z}^{s},\mathbf{h}\neq 0,\mathbf{h}\cdot\mathbf{z}\equiv 0\pmod{N}} \frac{c}{(\bar{h}_{1}\bar{h}_{2}\cdots\bar{h}_{s})^{\alpha}}. \tag{6}\] In particular, essentially this upper bound is achieved when \(\|\mathcal{N}[\tilde{u}]\|^{2}\) becomes the following function: \[\|\mathcal{N}[\tilde{u}]\|^{2}=\prod_{k=1}^{s}F_{\alpha}(x_{k}),\quad F_{ \alpha}(x_{k})=1+\sum_{h\in\mathbb{Z},h\neq 0}\frac{\exp(2\pi\mathrm{i}hx_{k})}{|h |^{\alpha}},\] Actually, when \(\alpha\) is even, this function is known to be explicitly written by using the Bernoulli polynomials \(B_{\alpha}(x)\)[38]: \[F_{\alpha}(x_{k})=1-(-1)^{\frac{\alpha}{2}}\frac{(2\pi)^{\alpha}B_{\alpha}}{ \alpha!}.\] Since this is a polynomial function, the integral can be found exactly; hence it is possible to find a loss function for this function for each lattice \(L\). Therefore, to find an optimal \(\mathbf{z}\), the loss function with respect to the above function should be minimized. The computational cost for computing the loss function for each \(L\) is \(O(N)\). Even considering that each component of \(\mathbf{z}\) is in \(\{0,\ldots,N-1\}\), searching for the optimal \(\mathbf{z}\in\mathbb{Z}^{s}\) would require the computational cost \(O(N^{s})\); however, if \(N\) is a prime number or the product of two prime numbers, the existence of a \(\mathbf{z}\) of the form \(\mathbf{z}=(1,l,l^{2}\pmod{N},\ldots,l^{s-1}\pmod{N})\) that gives a good lattice is known [19, 20, 38]. Since \(l\in\{0,1,\ldots,N-1\}\), there are only \(N\) candidates for \(l\), and hence the computational cost for finding the optimal \(\mathbf{z}\) is only \(O(N^{2})\) for each \(N\). Furthermore, as this optimization process can be fully parallelized, the computational time is quite short practically. The values of \(\mathbf{z}\) have been explored in the field of number theoretic numerical analysis, and typical values are available as numerical tables in, e.g., [7, 16]. LimitationsNot limited to the proposed GLT, but many methods to determine collocation points are not directly applicable to non-rectangular or non-flat domain \(\Omega\)[36]. To achieve the best performance, it is recommended to deform the domain \(\Omega\) to fit a flat rectangle. For such a technique, see, e.g., [18; 40]. In addition, because the proposed GLT is based on the Fourier series expansion, it is basically assumed that the loss function is periodic. This problem can be addressed by variable transformations [38]. For example, if an \(s\)-dimensional integral \(\int_{[0,1]^{s}}f(\mathbf{x})\mathrm{d}\mathbf{x}\) is to be computed, the integrand \(f\) can be transformed to a periodic one by using a smooth increasing function \(\phi:[0,1]\rightarrow[0,1]\) with \(\phi^{\prime}(0)=\phi^{\prime}(1)=0\): \[\int_{[0,1]^{s}}\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\! \!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\! \!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\! \!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\! \!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\! \!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\! \!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\! \!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\! \!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\! \!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\! \!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\! \!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\! \!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\! \!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\! \!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\! \!\! equations. The state of the NLS equation is complex; we simply treated it as a 2D real vector for training and used its absolute value for evaluation and visualization. Following Raissi et al. [33], we evaluated the performance using the relative error, which is the normalized squared error \(\mathcal{L}(\tilde{u},u;\mathbf{x}_{i})=(\sum_{i=1}^{N_{\mathbf{x}_{i}}}\|\tilde{u}(\mathbf{ x}_{i})-u(\mathbf{x}_{i})\|^{2})^{1/2}/(\sum_{i=1}^{N_{\mathbf{x}_{i}}}\|u(\mathbf{x}_{i})\|^{2 })^{1/2}\) at predefined \(N_{e}\) collocation points \(\mathbf{x}_{i}\). This is also a finite approximation to \(|\tilde{u}-u|_{2}/|u|_{2}\). For Poisson's equation with \(s=2\), we followed the original learning strategy using the L-BFGS-B method preceded by the Adam optimizer [17] to ensure precise convergence. For other datasets, we trained PINNs using the Adam optimizer with cosine decay of a single cycle to zero [24] for 200,000 iterations and sampling a different set of collocation points at each iteration; we found that this strategy improves the final performance. See Appendix B for details. We determined the collocation points using four different methods: uniformly random sampling, uniformly spaced sampling, LHS, and the proposed GLT. For the GLT, we took the number \(N\) of collocation points and the corresponding integer vector \(\mathbf{z}\) from numerical tables in [7, 16]. We also applied random shifts in (7). To maintain consistency, we used the same value of \(N\) for both uniformly random sampling and LHS. For uniformly spaced sampling, we selected the square number \(N\) (or the biquadratic number when \(s=4\)) that was closest to a number used in the GLT. Subsequently, we created a unit cube of \(N^{1/s}\) points on each side. Additionally, we introduced random shifts to the collocation points, with \(r_{\bullet}\sim U([0,1/N^{1/s}])\), ensuring that the collocation points were uniformly distributed. Then, we transformed the unit cube \([0,1]^{s}\) to the original domain \(\Omega\). We conducted five trials for each number \(N\) and each method. All experiments were conducted using Python v3.7.16 and tensorflow v1.15.5 [1] on servers with Intel Xeon Platinum 8368. Results: Accuracy of Physics-Informed LossFirst, we evaluate the accuracy of the physics-informed loss (1) in approximating the integrated loss (2). Regardless of the method, as the number \(N\) of collocation points increases, the physics-informed loss (1) approaches the integrated loss (2). With fewer collocation points, the physics-informed loss varies significantly depending on the selection of collocation points, resulting in a larger standard deviation. We trained the PINNs on the NLS equation using LHS with \(N=610\) collocation points. Then, we evaluated the physics-informed loss of the obtained PINNs for different methods and different numbers of collocation points. For each combination of method and number, we performed 1,000 trials and summarized their standard deviation of the physics-informed loss in Fig. 2. Except for the GLT, the other methods exhibit a similar trend, showing a linear reduction in standard deviation on the log-log plot. This trend aligns with the theoretical result that the convergence rate of Monte Carlo methods is \(O(1/\sqrt{N})\). On the other hand, the GLT demonstrates an accelerated reduction as the number \(N\) increases. This result implies that by using the GLT, the physics-informed loss (1) approximates the integrated loss (2) more accurately with the same number \(N\) of collocation points, leading to faster training and improved accuracy. Results: Performance of PINNsFigure 3 shows the average relative error \(\mathcal{L}\) with solid lines and the maximum and minimum errors with shaded areas. These results demonstrate that as \(N\) increases, the relative error \(\mathcal{L}\) decreases and eventually reaches saturation. This is because of numerical errors in the datasets, discretization errors in relative error \(\mathcal{L}\), and the network capacity. We report the minimum numbers \(N\) of collocation points with which the relative error \(\mathcal{L}\) was saturated in Table 1. Specifically, we consider a relative error \(\mathcal{L}\) below 130 % of the minimum observed one as saturated; the thresholds are denoted by horizontal red lines in Fig. 3. The proposed GLT demonstrated equivalent performance with significantly fewer collocation points. This suggests that the proposed GLT can achieve comparable performance with significantly less computational cost. Next, we equalized the number \(N\) of collocation points (and therefore, the computational cost). In the bottom rows of Table 1, we report the relative error \(\mathcal{L}\) for collocation points with which the relative error \(\mathcal{L}\) of one of the comparison methods saturated, as denoted by vertical green lines in Fig. 3. A smaller loss \(\mathcal{L}\) indicates that the method performed better than others with the same computational cost. The Figure 2: The number \(N\) of collocation points and the standard deviation of the physics-informed loss. proposed GLT yielded nearly half or less of the relative error \(\mathcal{L}\) for the NLS, KdV, and AC equations, and the difference is significant for Poisson's equation with \(s=2\). We show the true solutions and the residuals of example results with such \(N\) in Fig. 4. We also investigated longer training with smaller mini-batch sizes in Appendix C. \begin{table} \begin{tabular}{l l r r r r} \hline \hline & & NLS & KdV & AC & \multicolumn{2}{c}{Poisson} \\ \cline{4-6} & & & & \(s=2\) & \(s=4\) \\ \hline \multirow{3}{*}{\# of points \(N^{\dagger}\)} & \(\bullet\) uniformly random & 6,765 & 10,946 & 4,181 & \(>\)17,711 & 1,019 \\ & \(\bullet\) uniformly spaced & 1,600 & 6,724 & 11,025 & 6,724 & 1,296 \\ & \(\bullet\) LHS & 4,181 & 17,711 & 10,000 & \(>\)17,711 & 562 \\ & \(\bullet\) GLT (proposed) & **610** & **987** & **987** & **1,597** & **307** \\ \hline \multirow{3}{*}{relative error \(\mathcal{L}^{\ddagger}\)} & \(\bullet\) uniformly random & 7.60 & 3.32 & 1.82 & 4.141 & 28.7 \\ & \(\bullet\) uniformly spaced & 4.88 & 3.25 & 1.79 & 1.859 & 29.2 \\ & \(\bullet\) LHS & 6.45 & 2.94 & 1.43 & 6.174 & 24.3 \\ & \(\bullet\) GLT (proposed) & **1.55** & **1.90** & **0.74** & **0.027** & **16.4** \\ \hline \multicolumn{6}{l}{\# of points \(N\) at competitive relative error \(\mathcal{L}\) (under horizontal red line in Fig. 3).} \\ \multicolumn{6}{l}{\(\ddagger\) relative error \(\mathcal{L}\) at competitive \# of points \(N\) (on vertical green line in Fig. 3).} \\ \multicolumn{6}{l}{Shown in the scale of \(10^{-5}\) for Poisson’s equation and \(10^{-3}\) for others.} \\ \end{tabular} \end{table} Table 1: Trade-Off between Number \(N\) of Collocation Points and Relative Error \(\mathcal{L}\). Figure 4: Example results at competitive number \(N\) of collocation points (on vertical green line in Fig. 3). The leftmost panel shows the true solution. The remaining panels show the residuals of PINNs’ results using uniformly random sampling, uniformly spaced sampling, LHS, and GLT, from left to right. The residuals are multiplied by the factors in parentheses. Figure 3: The number \(N\) of collocation points and the relative error \(\mathcal{L}\). ### Competitive Physics-Informed Neural Networks Experimental SettingsCompetitive PINNs (CPINNs) are an improved version of PINNs that additionally uses a neural network \(D:\Omega\rightarrow\mathbb{R}\) called a discriminator [48]. Its objective function is \(\frac{1}{N}\sum_{i=1}^{N}D(\mathbf{x}_{i})\mathcal{N}[\vec{u}](\mathbf{x}_{i})\); the discriminator \(D\) is trained to maximize it, whereas the neural network \(\vec{u}\) is trained to minimize it. This setting is regarded as a zero-sum game, and its Nash equilibrium offers the solution to a given PDE. Moreover, this setting enables to use the (adaptive) competitive gradient descent (CGD) algorithm [34; 35], accelerating the convergence. The objective function is also regarded as a finite approximation to the integral \(\int_{\Omega}D(\mathbf{x})\mathcal{N}[\vec{u}](\mathbf{x})\mathrm{d}\mathbf{x}\); therefore, the proposed GLT can be applied to CPINNs. We modified the code accompanying the manuscript and investigated the NLS and Burgers' equations2. The NLS equation is identical to the one above. See Appendix B for details about Burgers' equation. The number \(N\) of collocation points was 20,000 by default and varied. All experiments were conducted using Python v3.9.16 and Pytorch v1.13.1 [31] on servers with Intel Xeon Platinum 8368 and NVIDIA A100. Footnote 2: See Supplementary Material at [https://openreview.net/forum?id=z9SIj-IM7tn](https://openreview.net/forum?id=z9SIj-IM7tn) (MIT License) ResultsWe summarized the results in Fig. 5. For the NLS equation, when the collocation points were determined by LHS, the relative error \(\mathcal{L}\) of CPINNs decreased slowly even with \(N=20,000\), and there was almost no improvement for \(N\leq 2,584\). On the other hand, when the proposed GLT was used, the error decreased rapidly even with \(N=2,584\). In the case of the Burgers' equation, CPINNs using GLT made some progress in learning with \(N=2,584\) collocation points, while CPINNs using LHS required \(N=6,765\) collocation points. These results indicate that the proposed GLT exhibits competitive or superior convergence speed with 2.5 to 8 times fewer collocation points. The original paper demonstrated that CPINNs have a faster convergence rate than vanilla PINNs, but the GLT can further accelerate it. ## 5 Conclusion This paper highlighted that the physics-informed loss, commonly used in PINNs and their variants, is a finite approximation to the integrated loss. From this perspective, it proposed good lattice training (GLT) to determine collocation points. This method enables a more accurate approximation of the integrated loss with a smaller number of collocation points. Experimental results using PINNs and CPINNs demonstrated that the GLT can achieve competitive or superior performance with much fewer collocation points. These results imply a significant reduction in computational cost and contribute to the large-scale computation of PINNs. We focused on the physics-informed loss in the domain. If the domain is \(s\geq 3\)-dimensional, the initial and boundary conditions are of \(s\geq 2\) dimensions, and their loss functions are also subject to the proposed GLT. As shown in Figs. 3 and 5, the current problem setting reaches performance saturation with around \(N=1,000\) collocation points. However, Figure 2 demonstrates that the GLT significantly enhances the approximation accuracy even when using further more collocation points. This implies that the GLT is particularly effective in addressing larger-scale problem settings, which will be explored further in future research. Figure 5: The number of iterations and the relative error \(\mathcal{L}\).
2310.00564
DYNAP-SE2: a scalable multi-core dynamic neuromorphic asynchronous spiking neural network processor
With the remarkable progress that technology has made, the need for processing data near the sensors at the edge has increased dramatically. The electronic systems used in these applications must process data continuously, in real-time, and extract relevant information using the smallest possible energy budgets. A promising approach for implementing always-on processing of sensory signals that supports on-demand, sparse, and edge-computing is to take inspiration from biological nervous system. Following this approach, we present a brain-inspired platform for prototyping real-time event-based Spiking Neural Networks (SNNs). The system proposed supports the direct emulation of dynamic and realistic neural processing phenomena such as short-term plasticity, NMDA gating, AMPA diffusion, homeostasis, spike frequency adaptation, conductance-based dendritic compartments and spike transmission delays. The analog circuits that implement such primitives are paired with a low latency asynchronous digital circuits for routing and mapping events. This asynchronous infrastructure enables the definition of different network architectures, and provides direct event-based interfaces to convert and encode data from event-based and continuous-signal sensors. Here we describe the overall system architecture, we characterize the mixed signal analog-digital circuits that emulate neural dynamics, demonstrate their features with experimental measurements, and present a low- and high-level software ecosystem that can be used for configuring the system. The flexibility to emulate different biologically plausible neural networks, and the chip's ability to monitor both population and single neuron signals in real-time, allow to develop and validate complex models of neural processing for both basic research and edge-computing applications.
Ole Richter, Chenxi Wu, Adrian M. Whatley, German Köstinger, Carsten Nielsen, Ning Qiao, Giacomo Indiveri
2023-10-01T03:48:16Z
http://arxiv.org/abs/2310.00564v2
# DYNAP-SE2: a scalable multi-core dynamic neuromorphic asynchronous spiking neural network processor ###### Abstract With the remarkable progress that technology has made, the need for processing data near the sensors at the edge has increased dramatically. The electronic systems used in these applications must process data continuously, in real-time, and extract relevant information using the smallest possible energy budgets. A promising approach for implementing always-on processing of sensory signals that supports on-demand, sparse, and edge-computing is to take inspiration from biological nervous system. Following this approach, we present a brain-inspired platform for prototyping real-time event-based Spiking Neural Networks (SNNs). The system proposed supports the direct emulation of dynamic and realistic neural processing phenomena such as short-term plasticity, NMDA gating, AMPA diffusion, homeostasis, spike frequency adaptation, conductance-based dendritic compartments and spike transmission delays. The analog circuits that implement such primitives are paired with a low latency asynchronous digital circuits for routing and mapping events. This asynchronous infrastructure enables the definition of different network architectures, and provides direct event-based interfaces to convert and encode data from event-based and continuous-signal sensors. Here we describe the overall system architecture, we characterize the mixed signal analog-digital circuits that emulate neural dynamics, demonstrate their features with experimental measurements, and present a low- and high-level software ecosystem that can be used for configuring the system. The flexibility to emulate different biologically plausible neural networks, and the chip's ability to monitor both population and single neuron signals in real-time, allow to develop and validate complex models of neural processing for both basic research and edge-computing applications. ## 1 Introduction As technology has progressed, the need for processing more sensory data at the edge has increased dramatically. In particular, an increasing amount of applications are expected to process data near the sensors, without resorting to remote computing servers. For these types of applications it is of prime importance to minimize power consumption and latency, while maintaining robustness and adaptability to changing conditions. The processors used in these applications therefore need to process the data being measured by the sensors continuously, in real-time, and to extract relevant information using the smallest possible energy budgets. A promising approach for implementing always-on processing of sensory signals that supports on-demand, sparse, and edge-intelligence computation, is that of using event-based Spiking Neural Networks (SNNs) [1, 2, 3, 4, 5, 6, 7]. The event-based representation has been shown to be particularly well suited to transmitting analog signals across noisy channels, while maximizing robustness to noise and minimizing bandwidth requirements and power consumption [1, 8, 9]. Furthermore, by encoding only the changes in the signals, this representation is optimally suited for sensory signals that change sparsely in time, producing data only when necessary [2, 4]. The computational paradigm that best exploits the event-based representation is that of SNNs. As one of the largest sources of energy consumption in electronic processing systems is _data-movement_[10, 11], the best way to minimize power consumption in event-based SNNs is to implement them as massively-parallel in-memory computing architectures that process the data on the fly, as it is being sensed, without having to store it and retrieve it. It is therefore important to match the rate of the data arriving in input to the processing rate and the time constants of the synapses and neurons in the SNN. Neuron and synapse circuits can be configured to process natural Figure 1: Photo of the DYNAP-SE2 chip, which has an area of \(98\,mm^{2}\) manufactured in 180nm CMOS technology as a cost effective prototyping platform. signals such as human voice, gestures, or bio-signals, by setting their time constants to tens or hundreds of milliseconds (and significantly reducing their processing speed). This can improve the information retention and processing ability of feed-forward SNNs. However, processing of signals that contain very long and multiple timescales using this approach requires resorting to recurrent SNNs (RNNs) [12, 13, 14]. These types of networks provide a valuable algorithmic foundation for adaptive and efficient processing of continuous sensory signals, as they can be configured to exhibit a wide range of dynamics that are fundamental in lowering the amount of storage resources required to process, recognize, and generate long temporal sequences and patterns. Conventional neural network accelerators and digital implementations of SNNs [15, 16] can be in principle used to design and train both feed-forward and recurrent neural networks. However their memory storage and data movement requirements increase their power budget significantly and negates their advantages compared to using standard computing architectures [17]. The original neuromorphic engineering approach proposed in [18, 19] aims to solve the above challenges by using analog circuits that operate in weak-inversion (subthreshold) and in physical time to implement neural dynamics for solving sensory processing tasks, in a data-driven manner. In this approach each neuron and synapse computational element is implemented using a dedicated physical circuit, without resorting to time-multiplexing of shared computing resources. Computation is therefore massively parallel and distributed, and takes place only if the synapse/neuron is driven by input events. For interactive real world data processing, the event-based mixed signal approach is an optimal match: it allows carrying out physical-time sensory processing with low-power circuits, and the implementation of artificial intelligence computing primitives for solving extreme edge computing applications [12, 19]. In this paper we present a mixed-signal neuromorphic processor that follows this approach. It directly emulates the dynamics of biological neurons and synapses using analog integrated circuits for computation, and asynchronous digital circuits for transmitting the events (spikes) produced by the neurons to destination synapses or to the output pads. The processor features a clock-free asynchronous digital hierarchical routing scheme which runs in native real-time and ensures low latency [20]. The processor we present is denoted as the DYnamic Neuromorphic Asynchronous Processor-ScalablE 2 DYNAP-SE2 This chip significantly extends the features of the previous generation DYNAP-SE [20] at the synapse and neuron circuit level, at the network-level, and at the asynchronous routing fabric level. We show here how the DYNAP-SE2 offers rich neuronal dynamics across different timescales to support a wide spectrum of biologically plausible recurrent networks. We present the overall architecture and describe in detail the individual circuits, providing experimental results measured from the chip to validate the theory. To enable near-sensor processing the DYNAP-SE2 also integrates an on-chip analog front-end (AFE) with low-noise amplifiers, band-pass filters and asynchronous delta modulators for converting input waveforms into streams of address-events [21]. Similarly, DYNAP-SE2 includes a direct 2D sensor event pre-processor[22] that can cut, scale and arbitrarily map 2D event stimuli from a Dynamic Vision Sensor (DVS) [23]. The structure of this paper is the following. Section 2 presents an overview of the general architecture and available resources of the chip. Section 3 reviews the common building blocks that are crucial to understanding and using the chip. Section 4 enumerates the core analog neural circuit with application examples and real measurement. Section 5 elaborates the routing scheme and methods for building large scale neural networks. Section 6 briefly describes the interfaces the chip presents to the outside world and Sec. 7 describes the software system that supports the usability of the chip. As the analog front-end is independent of the neuron cores and event processing, for more information regarding its circuit design and application see [21]. ## 2 Chip overview ### System architecture Computation is centered on the 1024, analog, integrate-and-fire neurons arranged in \(2\times 2\) cores of grids of \(16\times 16\) neurons each. Each neuron has 64 synapses and four dendritic branches. The only way to send information to the neurons and for the neurons to send information out is through digital spikes. The routing scheme will be elaborated in Section 5. As opposed to many computational models, the neurons do not receive analog current injection directly, and the membrane potential is also not accessible. These design choices are taken for scalability reasons, because there is no easy way to access thousands of analog values at the same time, while digitized spikes can easily be routed using time-multiplexing [24]. Thus, in order to provide analog input to the network, a neuromorphic sensor [25] (such as a DVS [26] or AFE [21] ) that encodes a signal into spikes is needed, and the computation and learning algorithms should be completely spike-based. As summarized in Fig. 2, each neuron circuit is composed of synaptic, dendritic and somatic compartments with many conditional blocks for dynamic features, which are constructed in a highly modular way, meaning that all of them can be bypassed with digital latches when not needed. The default state of these latches after reset is always disabled, so the users do not have to disable them by setting parameters to extreme values as in the previous generation. In order to better monitor and debug the network, the user can select one neuron per core to monitor, the membrane potential of which is directly buffered to an external pin, and multiple other intermediate analog current signals are converted into pulse-frequency modulated signals using spiking analog-to-digital converters (sADC). In addition, a delay pulse internal to a couple of specific synapses and the homeostasis direction of the monitored neuron are also buffered to external pins. Section 6.3-6.4 include more details about the monitoring. ### Specifications The specifications of DYNAP-SE2 are summarized in Table 1. ## 3 Common neuromorphic building blocks ### Differential pair integrator (DPI) The DPI is current-mode a low-pass filter that enables a wide range of dynamic features in neuromorphic aIC design [19]. It has many advantages such as small area, high power efficiency and good controllability, and is thus used in silicon synapse and neuron designs, as well as longer time constant adaptation [32] and homeostasis circuits [33]. When used as a linear integrator, it can exploit the super-position principle and receive high-frequency spike trains to produce an output that represents the sum of many synapses receiving low-frequency inputs. #### 3.1.1 Circuit The basic circuit and block diagram of a DPI is shown in Fig. 4. #### 3.1.2 Equations and typical operating regimes The most general equation in current mode for the output \(I_{out}\) is \[\tau\dot{I}_{out}+I_{out}=\frac{I_{in}}{I_{tau}}\frac{I_{gain}I_{out}}{I_{gain} +I_{out}} \tag{1}\] where the time constant \(\tau=\frac{CU_{T}}{\kappa I_{tot}}\). The non-linear equation can be simplified in the Figure 3: One neural core with 256 neurons in a 16 \(\times\) 16 array. Figure 2: Neuronal compartments. 64 synapses with 4-bit weights and conditional delay and short-term plasticity (STP) convert pre-synaptic spikes to pulses. The pulses are low-pass-filtered by one of the four dendrites to generate post-synaptic currents (PSC). The dendrites have conditional alpha-function excitatory PSCs, a diffusive grid, membrane voltage gating and ion-channel conductances. The PSCs are injected into the soma, which can switch between a thresholded [27] and exponential integrate-and-fire model [28], with conditional adaptation and ‘calcium’-based homeostasis. When the neuron fires, the AER spike is sent to up to four chips. three typical operating regimes: 1. \(I_{out}\gg I_{gain}\), \[\tau\dot{I}_{out}+I_{out}=\frac{I_{gain}}{I_{tau}}I_{in}\] (2) which is a first-order linear system with input \(I_{in}\) and state variable \(I_{m}\), 2. \(I_{gain}\gg I_{out}\), \[C\dot{V}_{out}=I_{in}-I_{tau}\] (3) which is a linear integration of inputs on the membrane capacitor, \begin{table} \begin{tabular}{c|c c} \hline \hline & Enhanced features & Novel features \\ \hline \multirow{3}{*}{Resource} & 4 cores with 250 configurable biases. & 8-channel delta-modulated AFE [21]. \\ & 1024 integrate-and-fire neurons. & DVS interface with pre-processing [22]. \\ & Can target up to \(\pm 7\times\pm\) surrounding chips. & 64-channel sADC on-chip monitoring [29]. \\ \hline \multirow{3}{*}{Neuron} & Exponential [30] \& threshold soma model. & Emulation of calcium current [31]. \\ & Spike-frequency adaptation [32]. & Homeostasis using gain regulation [33]. \\ & Monitoring of membrane potential. & Internal state probing with sADC [29]. \\ \hline \multirow{3}{*}{Synapse} & 64 synapses per neuron. & Quadruple (256) fan-in mode. \\ & 11-bit content-addressable memory (CAM). & 2-bit precise and mismatched delays [34]. \\ & 4-bit flexibly configurable weight. & Short term plasticity (depression) [1]. \\ \hline \multirow{3}{*}{Dendrite} & Excitatory: AMPA, NMDA (distal). & Alpha function excitatory PSC [35]. \\ & Inhibitory: GABAA (proximal), GABA\({}_{\text{B}}\) (distal). & Conductance on distal dendrites [35]. \\ & Membrane potential-gated NMDA mechanism [31]. & 2D resistive grid on AMPA [36]. \\ \hline \hline \end{tabular} \end{table} Table 1: Summary of enhanced and new features of DYNAP-SE2 compared to a current multi-purpose mixed signal prototyping platform DYNAP-SE [20] offered by the neuromophile engineering community. Figure 4: N- and P-type DPI circuits and corresponding block diagrams. The output current \(I_{out}\) can be thought of as a low-pass filtered version of the input current \(I_{in}\). The circuit is designed in current mode, where \(I_{x}\) (\(x\in\{tau au,gain,out\}\)) is the current flowing in the diode-connected transistor with voltage \(V_{x}\) of the corresponding type (for example \(I_{out}\) and \(V_{out}\) in the schematics). 3. \(I_{in}\ll I_{tau}\), \[\tau\dot{I}_{out}+I_{out}=0\Leftrightarrow C\dot{V}_{out}=I_{tau}\] (4) which is an exponential decay for \(I_{out}\) and linear ramp-down for \(V_{out}\). ### Mirrored output The output current can be flipped using a current mirror so that it flows in the same direction as the input, as shown in Fig. 5. ### Pulse extender As the information in the network is exclusively carried with spikes, which are extremely short duration (sub-nanosecond) digital pulses, they would be largely inconsequential for the analog circuits, thus there must be a way to convert the spikes into analog pulses with a longer duration. For instance, the input presynaptic spikes have to be converted into analog post-synaptic currents, and the neuron spikes have to trigger refractory periods and negative feedback mechanisms such as spike-frequency adaptation and homeostasis, etc. This conversion is achieved with a class of pulse extender circuits. #### 3.3.1 Basic pulse extender The most simple and low power pulse extender circuit is shown in Fig. 6. The pulse width \(T_{pulse}\) is controlled by the discharging current \(I_{pw}\) in an inversely proportional manner: \[T_{pulse}\propto\frac{1}{I_{pw}} \tag{5}\] #### 3.3.2 Delayed pulse extender The pulse extender circuit in Fig. 6 charges the capacitor immediately to V\({}_{\mathrm{dd}}\) when the input event arrives, which makes the output pulse also immediate. If the charging current of the input current is also restricted with an analog parameter, the output pulse will be delayed with reference to the Figure 5: N- and P-type DPI with mirrored output. The new output \(I_{out}\) flows in the opposite direction to the original one in Fig. 4 but has the same magnitude. input [34]. The circuit is shown in Fig. 7. The delay time \(T_{delay}\) is controlled by the charging current \(I_{delay}\), and pulse width \(T_{pulse}\) by the discharging current \(I_{pw}\), both in an inversely proportional manner: \[T_{delay}\propto\frac{1}{I_{delay}},T_{pulse}\propto\frac{1}{I_{pw}} \tag{6}\] #### 3.3.3 Loss of information Both pulse extension and delay mechanisms will make each spike take longer. The important edge case is when another event arrives before the pulse of the previous event finishes. From the circuit and information theoretic perspective, since the 'time left' information (for either delay or pulse width) is stored as the voltage on the capacitor, it is impossible to keep track of multiple of them with only one state variable. If two pulses overlap, one of them must be dropped. Because physical systems are causal, the second pulse cannot remove the already started one but only overwrite the remaining part of it. Figure 6: Minimal and low power pulse extender. When the active-low input event arrives, the capacitor \(C\) immediately charges to \(\mathrm{V_{dd}}\), then discharges with current \(I_{pw}\). For the minimal pulse extender \(\mathrm{PX_{MIN}}\) with only one transistor and one capacitor, the voltage \(V_{C}\) on the capacitor is the output. This circuit is simple, but the output is not clean (dashed waveform) and consumes more power as it stays around \(\mathrm{V_{dd}}/2\) longer. For the low-power pulse extender \(\mathrm{PX_{EFF}}\), once \(V_{C}\) reaches the switching threshold around \(\mathrm{V_{dd}}/4\), positive feedback will discharge the capacitor rapidly (solid line), so the output pulse is cleaner and consumes less power. The switching threshold is shifted down to \(\sim\mathrm{V_{dd}}/4\) by the unsymmetrical starved inverter as well as sizing the P-FET physically the same size as the N-FET and resulting in a beneficial pull-up/pull-down drive strength imbalance. With this the capacitance can be significantly smaller while still achieving the same time constant. For the low-power pulse extender circuit, the capacitor will be recharged to V\({}_{\rm dd}\) immediately when the second event arrives, thus the pulse restarts. Mathematically, the output pulse is the union (logical OR) of the incoming pulses. For the delayed pulse extender circuit, the charging can only start when the output pulse is inactive, otherwise the output of the C-element will remain at 1. If another input event arrives during the delay phase or in the extreme case during the transition between delay and pulse phase, the output of the C-element will still be 0. In both cases, the output of the C-element does not change, meaning that the information is dropped. In other words, if the inter-spike interval is shorter than the delay, the second spike will be ignored. ### Event low pass filter When a pulse extender is combined with a DPI as shown in Fig. 8, it serves as an event low-pass filter (LPF). Figure 7: Delayed pulse extender. The C-element [37] (shown as ©) is an asynchronous digital circuit that changes its output to \(X\) when both inputs are equal to \(X\). When the active-low event arrives, if there is no output pulse (1), the output of the C-element goes from 1 to 0, which starts the charging of the capacitor with current \(I_{delay}\). When the voltage on the capacitor exceeds the threshold of the inverter, the output pulse becomes active (0) and positive feedback charges the capacitor to V\({}_{\rm dd}\) immediately. The output of the C-element then goes to 1, which starts the discharging of the capacitor with current \(I_{pw}\). When the voltage on the capacitor drops below the threshold of the inverter, the output pulse finishes (1). Let the (active low) input be \(x(t)=\sum_{i=1}^{N}\delta\left(t-t_{i}\right)\) where the \(t_{i}\) are the spike times, the pulse width of the pulse extender be \(T_{pulse}\), the time constant and threshold parameters for the DPI be \(I_{tau}andI_{gain}\), and the weight parameter be \(I_{w}\). \(\tau=\frac{CU_{T}}{\kappa I_{tau}}\) and \[W=\frac{I_{gain}I_{w}}{I_{tau}}\frac{T_{pulse}}{\tau}=\frac{\kappa I_{gain}I_{ w}T_{pulse}}{CU_{T}}\propto I_{gain}I_{w}T_{pulse} \tag{7}\] If \(\forall i=1,\cdots,N,t_{i+1}-t_{i}>T_{pulse}\) and \(\frac{I_{tau}}{I_{w}}\tau\ll T_{pulse}\ll\tau\), the combined circuit is a first-order low-pass filter with transfer function \[\frac{Y(s)}{X(s)}=\frac{\tau W}{\tau s+1} \tag{8}\] Similarly for the delayed pulse extender with the extra delay parameter \(T_{delay}\), if \(\forall i=1,\cdots,N,t_{i+1}-t_{i}>T_{delay}+T_{pulse}\) and \(\frac{I_{tau}}{I_{w}}\tau\ll T_{pulse}\ll\tau\), the combined circuit is a delayed first-order low-pass filter with transfer function \[\frac{Y(s)}{X(s)}=\frac{\tau We^{-T_{delay}s}}{\tau s+1} \tag{9}\] If we plug in \(X(s)=\mathcal{L}\left[x(t)\right]=\sum_{i=1}^{N}e^{-t_{i}s}\), the integral \[\int_{0}^{\infty}y(t)\mathrm{d}t=\lim_{s\to 0}Y(s)=\tau WN \tag{10}\] which implies that the system is linear, and the total output charge per input event is \[Q=\tau W=\frac{I_{gain}I_{w}}{I_{tau}}T_{pulse} \tag{11}\] The output only depends on hyperparameters \(\tau\), \(W\) and \(T_{delay}\) or even \(Q\) and \(T_{delay}\) if \(\tau\ll t_{i+1}-t_{i}\) (\(i=1,\cdots,N\)). ### Digital-to-analog converters The parameters required to properly operate the analog circuits in the chip are generated on chip by on-chip programmable digital-to-analog converters (DAC). Because of the large scale of the neural network, i.e. 1024 neurons \(\times\) (\(\sim\)20 somatic parameters + \(\sim\)20 parameters for the four dendrites + 64 synapses per neuron \(\times\) 14 synaptic parameters), if every neuron and every synapse would have individually configurable parameters, there would be around one million parameters to set. As a trade-off, the neurons are divided into four cores of 256 neurons each, and most of the parameters are shared across all neurons and synapses within a core, and implemented with separate parameter generator DACs for each core. A very few but important cases Figure 8: Event low pass filter consisting of a pulse extender PX and a DPI. The input \(x\) is a set of discrete events (treated as sum of Dirac functions) and the output \(y\) is an analog current waveform. such as the individual synaptic delays and weights are implemented with a flexible DAC mechanism, consisting of several global parameters for the 'base' currents and individual digital latches in each individual unit to chose a binary combination of the 'base' currents. ### Parameter generator The current-based parameter generator used in this chip generates accurate analog currents over a very large dynamic range [38]. This parameter generator is enhanced with a proportional to absolute temperature (PTAT) and complementary to absolute temperature (CTAT) current reference for current temperature stabilization. The general formula for any current parameter \(I_{\rm parameter}\) is \[I_{\rm parameter}=k_{\rm parameter}I_{\rm coarse}(n_{\rm coarse})\frac{n_{ \rm fine}}{255} \tag{12}\] where integers \(n_{\rm coarse}\in[0,5]\), \(n_{\rm fine}\in[0,255]\). \(k_{\rm parameter}\) is a scaling factor which is roughly constant for all \(n_{\rm coarse}\) and \(n_{\rm fine}\) values, but a more precise non-ideality correction from simulations based on the transistor type and size is also available. Estimates of the values of the 'base' currents \(I_{\rm coarse}(n_{\rm coarse})\) are shown in Table 2. It is important to note that the error in these estimates increases with the coarse value, and because of mismatch, different \((n_{\rm coarse},n_{\rm fine})\) combinations that produce the same result according to Eq. (12) may give different results on actual hardware. In the case of very low currents, \(n_{\rm coarse}=0\) always gives the highest accuracy. Therefore, it is recommended to always use lower \(n_{\rm coarse}\) values when possible. Especially when \(n_{\rm fine}=0\), the parameter generator outputs the dark current of the corresponding transistor, and can be very different for different \(n_{\rm coarse}\) values. As for other implementations [38], a small-scale non-monotonicity, caused by a large transistor stack moving out of saturation in the current branch also exists in this implementation and can be corrected via calibration with a pre-recorded look-up table. \begin{table} \begin{tabular}{|l|c|c|c|c|c|c|} \hline \(n_{\rm coarse}\) & 0 & 1 & 2 & 3 & 4 & 5 \\ \hline \(I_{\rm coarse}\) & 70 pA & 550 pA & 4.45 nA & 35 nA & 0.28 \(\mu\)A & 2.25 \(\mu\)A \\ \hline \end{tabular} \end{table} Table 2: Nominal \(I_{\rm coarse}\) value for each \(n_{\rm coarse}\) value Figure 9: One DAC (two horizontal structures) with the adjacent sADC block (bright rectangle) between two adjacent neural cores. For very small currents the DAC requires a settling time for the parameters to reach their steady-state programmed values, which can take up to several seconds. For circuit parameters that are in the voltage-domain instead of the current one, the voltage \(V_{\mathrm{parameter}}\) at the gate of the diode-connected transistor of the appropriate type that conducts the parameter current in sub-threshold is given by \[V_{\mathrm{parameter}}=\left\{\begin{array}{rl}\frac{U_{T}}{\kappa}\ln\frac{I _{\mathrm{parameter}}}{I_{0}}&\textrm{(if N $-$ type)}\\ \mathrm{V_{dd}}-\frac{U_{T}}{\kappa}\ln\frac{I_{\mathrm{parameter}}}{I_{0}}& \textrm{(if P $-$ type)}\end{array}\right. \tag{13}\] ### Flexible DAC For the 4-bit synaptic weight and 2-bit delay, in order to achieve maximum flexibility, a customized DAC is used. The circuit (in P-type) is shown in Fig. 10. The base currents \(I_{b0}\) through \(I_{bn}\) come from the parameter generator, and the digital configurations \(x_{0}\) through \(x_{n}\) are stored in latches, The output current follows \[I_{out}=\sum_{i=0}^{n}x_{i}I_{bi} \tag{14}\] If an always-on minimal current is wanted, the P-FET connected to \(\overline{x_{0}}\) could be bypassed, which implies \(x_{0}\equiv 1\) in Eq. (14). If we set \(I_{i}=2^{-i}I_{b0}\) (for \(i=1,\cdots,n\)), the flexible DAC could be used as a normal \(n+1\) bit DAC. If higher dynamic range is needed, the different \(I_{bi}\)'s can also be very different, but the bit resolution will be lower as a trade off. ## 4 Silicon neuron circuits ### Somatic compartment The center of the silicon neuron is the integrate-and-fire soma circuit. Based on the desired 'firing' mechanisms, there are two switchable somatic models on the chip: * Thresholded: the neuron fires when the membrane potential reaches a threshold; * Exponential: the neuron receives positive feedback that drives spike output [28]. In addition, there are conditional spike-frequency adaptation circuit [32] and homeostasis circuits [33] that can be activated on either model. The overall architecture of the somatic circuit is shown in Fig. 11. Figure 10: Flexible DAC of \(n+1\) bits with minimal current (including \(\overline{x_{0}}\) transistor, dashed line) and \(n\) bits without it (dashed transistor connected to \(\overline{x_{0}}\) bypassed). #### 4.1.1 Somatic DPI - information integration The integration of information on the soma is achieved with the N-type DPI circuit introduced in Section 3.1. There are two basic parameters to control the somatic DPI - the leak (SOIF_LEAK parameter, or the \(I_{tau}\) of the DPI) and the gain (SOIF_GAIN parameter, or the \(I_{gain}\) of the DPI). The neuron receives post-synaptic current \(I_{dendritic}\) from three dendritic branches AMPA, NMDA and GABA\({}_{\rm B}\), and the somatic current \(I_{somatic}\) from shunting inhibitory dendrite GABAA\({}_{\rm A}\). The output is the membrane potential \(I_{mem}\) in current mode or \(V_{mem}\) in voltage mode. The most commonly used conditional function is the constant DC current injection (enabled using the latch SO_DC and configured with the SOIF_DC parameter), which goes into the input branch of the DPI, together with the dendritic input \(I_{dendritic}\). The DC input can be used to set a proper resting potential and even drive a constant firing rate. One can also turn off any specific neuron using the latch SOIF_KILL. Mathematically, the DPI inputs corresponding to Section 3.1 are \[I_{in}=\max\left(I_{dendritic}+I_{DC},0\right) \tag{15}\] \[I_{tau}=I_{leak}+I_{somatic} \tag{16}\] Figure 12 shows the membrane voltage \(V_{mem}\) waveform recorded for a neuron on the chip for the two somatic models with the same DC input but different gains. #### 4.1.2 Biologically plausible time constant The somatic DPI employs a \(7.72\,\)pF capacitance to achieve a biologically plausible time constant. When the leak of the neuron is set to its minimum, which is the leakage current of the transistor, the slew rate of \(V_{mem}\) can achieve \(108\,\pm\,12\) mV/s (measured across one core). Thus a single neuron can hold a'memory' for up to about five seconds, enabling processing of signals on a biologically plausible timescale. The biologically plausible time constant is a trade off and the reason for a comparatively higher power consumption compared to other systems. Measurement results and discussion on the power consumption is presented in more detail in subsection 4.1.4. Figure 11: Somatic circuit block diagram. All the conditional functions within the dashed outline can be disabled or bypassed using digital latches. #### 4.1.3 Refractory period - maximum firing rate After the spike is generated, the neuron enters a state in which integration is blocked: this is the (absolute) refractory period in biology. It is an important computational feature, as it sets an upper limit on the firing rate and introduces non-linearity. The refractory period circuit as shown in Fig. 13. The length of the refractory period is controlled by the discharging current \(I_{\text{refractory}}\) (SOIF_REFR parameter). Based on Eq. (5), the maximum firing rate \(r_{max}\) or equivalently the inverse of the length of the refractory period \(T_{\text{refractory}}\) is proportional to the recharging current: \[r_{max}=\frac{1}{T_{\text{refractory}}}\propto I_{\text{refractory}} \tag{17}\] The capacitance of the refractory period pulse extender is about 2 pF. The longest refractory period is achieved when the parameter is set to its minimum value. The measurement result across one core shows that the maximum refractory period for the thresholded model is 1.58 \(\pm\) 0.10 s, and 0.748 \(\pm\) 0.045 s for the exponential model. The difference is because the pulse extender circuits are different in the two models. The thresholded model uses the low-power pulse extender and the exponential model uses the simplified minimal pulse extender without positive feedback. The latter also has the problem that there might be multiple events generated for one neuron spike, which makes the exponential model unsuitable for building a complex network. #### 4.1.4 Two models for spike generation The two leaky integrate-and-fire (I&F) neuron models are the thresholded I&F model adapted from [40] as an intermediate Figure 12: Comparison of the two somatic models in different operating regimes. With a lower gain value (left), the integration phase is logarithmic (linear \(I_{mem}\) in Eq. (2)). With a higher gain value (right), the integration phase is linear (exponential \(I_{mem}\) in Eq. (2)). The top two plots show the the thresholded model with firing threshold set to around 0.5 V. The bottom two plots show the exponential model, where \(V_{mem}\) has an exponentially increasing shape that leads to the neuron firing. While we show data for the voltage across the output capacitor of the circuits, the neuron uses the current resulting from the voltage across the capacitor. This is given by the exponential of the plotted voltage and it is affected by the relevant transistor variables (e.g., \(U_{T}\), \(\kappa\)) [39]. development step towards the later [41] and the adapted exponential I&F model as shown in [42]. They share the integration circuit described in subsection 4.1.1, but have different ways of generating spikes. The two models are selected using the SOIF_TYPE latch (default 0 = thresholded model, 1 = exponential model). 1. Thresholded I&F model The thresholded I&F generates a spike whenever the membrane potential (\(I_{mem}=I_{out}\) of the somatic DPI) exceeds a certain threshold \(I_{\mathrm{spkthr}}\) (controlled by the parameter SOIF_SPKTHR). The circuit is shown in Fig. 14. The generated spike will give a positive feedback to the DPI by charging \(I_{mem}\) to its maximum immediately, thus the spike pulse width is just the time for the following asynchronous digital encoder to respond and can be as low as a few nanoseconds (thus the ramp-up of \(I_{mem}\) is too sharp to be buffered to the monitoring pin and cannot be seen) and it is more power efficient due to being shorter. The top two plots in Fig. 12 show the firing pattern in the thresholded model. Measurement results show that it consumes \(150pJ\) per somatic spike when spiking at 80 Hz for the full soma operation, including the integration of the DC input. 2. Exponential I&F model The exponential integrate and fire circuit is shown in Fig. 15. As the membrane voltage \(V_{mem}\) increases and exceeds a certain threshold, a positive feedback current proportional to \(I_{mem}\) is injected onto the membrane capacitor. This makes the neuron fire with an exponential curve as shown in the bottom plots in Fig. 12. The threshold is the point at which the exponential feedback overpowers the leak, and is not controlled by any additional parameter. Measurement results show that the full soma consumes \(300pJ\) per somatic spike for 80 Hz spiking, double the power consumption of the thresholded model (also including the integration power consumption). The main reason is that the spike pulses are longer. Figure 13: Refractory circuit and its block diagram. It combines the pulse extender from Section 3.3.1 with event routing handshaking. In the idle state both the request (\(\overline{\mathrm{req}}\)) and acknowledge (\(\overline{\mathrm{ack}}\)) signals are inactive (1). When the neuron emits a spike, (\(\overline{\mathrm{spike}}=0\)), \(\overline{\mathrm{req}}=0\) is sent to the encoder, which returns \(\overline{\mathrm{ack}}=0\). When both \(\overline{\mathrm{req}}=\overline{\mathrm{ack}}=0\), the pulse extender is triggered, which discharges the neuron until the spike disappears (\(\overline{\mathrm{spike}}=\overline{\mathrm{req}}=1\)). The encoder then releases \(\overline{\mathrm{ack}}\) (\(\overline{\mathrm{ack}}=1\)) and the refractory period starts by discharging at a rate determined by \(I_{\mathrm{refractory}}\), during which the neuron’s membrane potential is clamped to ground. #### 4.1.5 Neuronal dynamics on a longer timescale controllable parameters are the LPF biases: \(I_{w}\) (SOAD_W), \(I_{gain}\) (SOAD_GAIN) and \(I_{tau}\) (SOAD_TAU). Figure (a)a shows measurements of the adaptation of the neuron with constant input. Figure (b)b shows the spike-frequency adaptation measurement with alternating DC input. Notice that the parameters were chosen to give long time constants. In real applications, shorter time constants can reduce the effects of device mismatch. 2. Homeostasis The homeostasis mechanism is also known as synaptic scaling. It regulates the excitability of the neuron so that the firing rate stays in the medium range (or a target). On <chip-name>, this is achieved with the automatic gain control (AGC) mechanism which can achieve a very long timescale of up to hours. First, the firing rate of the neuron is estimated using a 'calcium current' \(I_{Ca}\), which is implemented using an LPF consisting of the pulse extender shared with the spike-frequency adaptation mechanism described above and a non-shared DPI, and should have a relatively long time constant in order to act as an indicator of Figure 16: Spike-frequency adaptation and calcium current. (a) Adaptation and calcium currents. The vertical bars are standard deviations over 200 trials. The neuron receives constant DC input. When it fires at time \(t=0\), the output of the adaptation and calcium DPIs increase by a certain amount and then decay exponentially. The adaptation current is subtracted from the DC and distal dendritic input. The calcium has a independent weight and a longer time constant, and will fluctuate around a level proportional to the average firing rate of the neuron. (b) Spike-frequency adaptation application example. When DC input is first presented at time \(t=0\), the neuron starts to spike at a high rate, causing the adaptation current to increase until it reaches a high enough value to shunt the input, which enters the firing pattern as shown in Fig. (b)b, and the firing rate drops. When the DC input is removed at \(t=0.6\) s, the adaptation current decays exponentially to 0, until the neurons starts firing again (at high rate) when DC input is again presented at \(t=1.4\) s. the overall neural activity. The calcium current monitored with sADC is shown in Fig. 16a), The homeostasis function is enabled using the latch HO_ENABLE. The DPI biases are the weight \(I_{Ca,w}\) (\(\mathsf{SOCA\_W}\)), threshold \(I_{Ca,thr}\) (\(\mathsf{SOCA\_GAIN}\)) and time constant \(I_{Ca,tau}\) (\(\mathsf{SOCA\_TAU}\)). The output (in current mode) is used as an input to the AGC circuit, and can also be chosen as the reversal potential for the conditional conductance dendrites (see Section 4.3.1) The basic control logic of the AGC is a negative feedback on the somatic gain (or on NMDA gain, controlled by the latch HO_SO_DE where default \(0=\) somatic, \(1=\) NMDA) to keep the calcium current around a reference level \(I_{Ca,ref}\) (\(\mathsf{SOHO\_VREF}\) parameter). Usually, \[\frac{\mathrm{d}V_{gain}}{\mathrm{d}t}=\Delta\cdot\mathrm{sign}\left(I_{Ca, ref}-I_{Ca}\right) \tag{18}\] \[\Delta_{+}=\frac{\mathsf{SOHO\_VREF\_H}}{\mathsf{SOHO\_VREF\_M}}=\frac{ \mathsf{SOHO\_VREF\_M}}{\mathsf{SOHO\_VREF\_M}}=\Delta_{-} \tag{19}\] but the ratios could also be set differently to get different ramp-up and ramp-down rates. The output gain voltage can also be reset directly to \(\mathsf{SOHO\_VREF\_M}\), which is controlled by the latch HO_ACTIVE (default \(0=\) reset, \(1=\) enable homeostasis). Figure 17 shows the working mechanism and measurement results of the homeostasis circuit. ### Synaptic compartment Each neuron contains 64 synapses and four dendritic branches. Each synapse can be attached to any one of the four dendritic compartments. More details of the dendrite circuits will be discussed in Section 4.3. The synaptic and dendritic compartment generate post-synaptic currents from pre-synaptic events. The synapse is a delayed, weighted, low-pass-filter as shown in Fig. 8 that takes the pre-synaptic events as its input and outputs analog pulses with programmable width and height, which are used as the inputs to the dendritic DPI blocks. A block diagram of the synapse is shown in Fig. 18. #### 4.2.1 Synaptic delay The delay current DAC of the type described in Section 3.7 contains two digital latches named \(\mathsf{precise\_delay}\) for \(x_{1}\) and \(\mathsf{mismatched\_delay}\) for \(x_{2}\), and three analog parameters: \(\mathsf{SYPD\_DLY0}\) for \(I_{0}\), \(\mathsf{SYPD\_DLY1}\) for \(I_{1}\) and \(\mathsf{SYPD\_DLY2}\) for \(I_{2}\). The naming '\(\mathsf{precise\_delay}\)' and '\(\mathsf{mismatched\_delay}\)' comes from the design feature that \(\mathsf{SYPD\_DLY2}\) has higher mismatch than the other two, in order to give a distribution of delays across a core. \(x_{0}\) is fixed to \(1\), which means \(\mathsf{SYPD\_DLY0}\) sets the minimum output current and thus maximum delay time. Different combinations of the settings of the two latches can also be interpreted as providing four groups of delays, as shown in Table 3. An illustration of the four groups of delay distributions is shown in Fig. 19. Note that this is just one example of the analog parameter configurations, shorter (down to a few microseconds) and longer (up to one second) delays are also possible; the combined use of the two precise and one mismatched delay parameters gives control over shaping the delay distribution for the desired application. #### 4.2.2 Short-term plasticity Short-term plasticity (STP) implements depression of the synaptic weight after every pre-synaptic spike. The circuit is shown in Fig. 19(a). There are two configurable parameters: \(I_{\text{stpw}}\) (SYAN_STDW parameter) sets the steady state value, and \(I_{\text{stpstr}}\) (SYAN_STDSTR parameter) sets the strength or how much the output will change for each spike. \begin{table} \begin{tabular}{|c|c|c|} \hline & mismatched\_delay = 0 & mismatched\_delay = 1 \\ \hline \multirow{2}{*}{precise\_delay = 0} & \(T_{delay}\propto\left(I_{dly0}\right)^{-1}\) & \(T_{delay}\propto\left(I_{dly0}+I_{dly2}\right)^{-1}\) \\ & high delay, low mismatch & high delay, high mismatch \\ \hline \multirow{2}{*}{precise\_delay = 1} & \(T_{delay}\propto\left(I_{dly0}+I_{dly1}\right)^{-1}\) & \(T_{delay}\propto\left(I_{dly0}+I_{dly1}+I_{dly2}\right)^{-1}\) \\ & low delay, low mismatch & low delay, high mismatch \\ \hline \end{tabular} \end{table} Table 3: Latch configuration for four groups of delays. Figure 17: Homeostasis. (a) The neuron receives Poisson-distributed input events at an average of \(100\,\mathrm{Hz}\) starting at \(t=0\). To begin with, the neuron has a very high gain and thus a very high firing rate. This makes the calcium current \(I_{Ca}\) much higher than the reference (target value – dashed line) and a down regulation of the gain takes place. At around \(t=2.5\,\mathrm{s}\), the gain is low enough that the firing rate decreases and the calcium current drops below the reference value, and the gain regulation changes sign. The feedback regulation then keeps the firing activity (calcium current) fluctuating around the reference level. (b) Homeostasis dynamics on a longer timescale. The automatic gain control regulates the gain of the soma very slowly until the firing rate reaches the target in about 15 minutes. Both shorter (milliseconds to seconds) and longer time constants (hours to days) can also be achieved. When there is no pre-spike, assuming \(V_{\rm stp}\) is not very far from \(V_{\rm stpw}\), the P-FET is approximately a pseudo-resistor: \[C\frac{\mathrm{d}V_{\rm stp}}{\mathrm{d}t}=\frac{V_{\rm stpw}-V_{\rm stp}}{R} \tag{20}\] which means that \(V_{\rm stp}\) will converge to \(V_{\rm stpw}\) exponentially with time constant \(\tau=RC\). For small signals (\(V_{\rm stp}\approx V_{\rm stpw}\)) the corresponding current \(I_{\rm stp}\) following \(I_{\rm stp}=I_{0}\epsilon^{\kappa\frac{V_{\rm stp}}{U_{T}}}\) also converges at \(\tau\). During a pre-spike pulse, assuming \(I_{\rm stpstr}\gg I_{0}\epsilon^{\kappa\frac{V_{\rm stpw}-V_{\rm stp}}{U_{T}}}\): \[C\frac{\mathrm{d}V_{\rm stp}}{\mathrm{d}t}=-I_{\rm stpstr} \tag{21}\] which means that \(V_{\rm stp}\) will drop linearly at rate \(\frac{I_{\rm stpstr}}{C}\), and the output current \(I_{\rm stp}\) decays exponentially with time constant \(\tau=\frac{CU_{T}}{\kappa I_{\rm stpstr}}\). ### Dendritic compartment The dendritic block contains two excitatory (AMPA and NMDA) and two inhibitory (GABA\({}_{\rm B}\) and GABA\({}_{\rm A}\)) DPI compartments, which turn pre-synaptic events into excitatory and inhibitory PSCs. The block diagram is shown in Fig. 21. Figure 18: Synapse block diagram. The input pulse is the active low \(\overline{\rm match}\) signal coming from the content addressable memory (CAM) (see Section 5.1). The output current of the delayed weighted pulse extender (see Section 3.3.2) will be copied and directed to one of the dendritic branches. The weight can either come from a 4-bit DAC of the type described in Section 3.7 (outputs \(I_{w}\), \(n=3\)) or from the short term plasticity (STP) output (\(V_{\rm stp}\)), chosen by the latch STP (default 0 = DAC, 1 = STP). The delay current parameter comes from another 2-bit DAC of the type described in Section 3.7 (output \(I_{delay}\), \(n=2\) but with always-on \(I_{0}\)). The pulse width control \(I_{pw}\) is set by the \(\mathsf{SYPD\_EXT}\) parameter. The output demultiplexer uses one-hot encoding, where four latches control whether the current goes to each of the four dendritic branch DPIs. For the two excitatory dendrites AMPA and NMDA, there is also a copy of the current provided to the double DPI (DDPI) responsible for producing alpha-function shaped EPSCs (see Section 4.3.2). Figure 19: Four groups of synaptic delay distributions. The configuration of the latches are given in Table 3. The measurement results show the standard deviations in \(I_{dly0}\), \(I_{dly1}\) and \(I_{dly2}\) to be \(5.4\%\), \(6.7\%\) and \(37.1\%\) respectively. With the different standard deviations the spread and position of the delay distribution can be freely configured via parameters as \(I_{dly0}\) and \(I_{dly1}\) and/or \(I_{dly2}\) are summed depending on the individual synaptic configuration. The summed current then controls the effective delay applied. Figure 20: (a) Short term depression circuit and (b) measurement result. The synapse receives \(167\,\mathrm{Hz}\) input from time \(t=0\) to \(t=60\) ms, during which the DPI output first increases due to the time constant of several ms, and then decreases due to the decreased weight caused by the short-term depression. After \(60\,\mathrm{ms}\), when there are no further input spikes, the weight recovers with a time constant of roughly \(50\,\mathrm{ms}\). The vertical dashed lines show the standard deviation over \(100\) trials. #### 4.3.1 Conductance dendrites The AMPA, NDMA and GABA\({}_{\rm B}\) dendrites can be individually switched to conductance mode to emulate a large class of biologically inspired synaptic models. The circuit is shown in Fig. 22 and is adapted from [35]. The output from the conductance block \(I_{conductance}\) to the soma is a tanh function of the difference between the reversal potential \(V_{reversal}\) set by the parameter \(\mathsf{REV}\) and \(V_{neuron}\) which is either the somatic membrane potential \(V_{mem}\) or the calcium current \(V_{Ca}\) (selected using the latch COHO_CA_MEM, default \(0=V_{mem}\), \(1=V_{Ca}\)): \[I_{conductance}=I_{ dendrite}\tanh\frac{V_{reversal}-V_{neuron}}{U_{T}}\] The measurement result shown in Fig. 23a illustrates a simple example of using the conductance function. #### 4.3.2 Double-DPI -- alpha function EPSC Both AMPA and NMDA EPSCs can accurately emulate alpha function synapse potentials with an additional inhibitory DPI (P-type but with mirrored output as described in Section 3.2) [35]. The difference Figure 21: Dendrite compartment block diagram. Input \(I_{in}\) is the sum of the delayed extended weighted pulse coming from the synaptic compartments. The two excitatory dendrites AMPA and NMDA have conditional alpha function blocks, and along with GABA\({}_{\rm B}\) have conditional conductance blocks. The AMPA dendrite also contains a conditional diffusion block. The NMDA dendrite has conditional membrane voltage gating block. The conditional blocks can be bypassed using digital latches. The sum of the output currents from AMPA(+), NMDA(+) and GABA\({}_{\rm B}(-)\) is \(I_{dendritic}\); the only component of \(I_{somatic}\) is the shunting current into GABA\({}_{\rm A}\). current between the excitatory and the inhibitory DPIs (EDPI and IDPI) produces an alpha-function-shaped EPSP. Quantitatively, \[I_{\text{DDPI}}=\max\left(I_{\text{EDPI}}-I_{\text{IDPI}},0\right)=\max\left(W_{E} e^{-\frac{t}{\tau_{E}}}-W_{I}e^{-\frac{t}{\tau_{I}}},0\right)\] where the coefficients \(W_{E}\) and \(W_{I}\) are controlled by the parameters \(\mathsf{EGAIN}\) and \(\mathsf{IGAIN}\) respectively and the time constants \(\tau_{E}\) and \(\tau_{I}\) are controlled by the parameters \(\mathsf{ETAU}\) and \(\mathsf{ITAU}\) respectively as described in Section 3.4. The measurement result shown in Fig. 23b illustrates a simple example of using the alpha function dendrite. #### 4.3.3 Diffusion over a 2D grid The AMPA dendritic compartment offers an conditional 1D or 2D resistive grid similar to that described in [36] to diffuse incoming EPSCs between nearby neurons. The circuit is shown in Fig. 24a. An example of one dimensional (horizontal) diffusion is shown in Fig. 25. #### 4.3.4 NMDA -- gating with the membrane potential The NMDA dendritic compartment can gate the incoming current depending on the membrane potential, shown in Fig. 24b. The measurement result shown in Fig. 23c illustrates a simple example of using the NMDA threshold circuit. It is important to note that disabling the gating using the latch and enabling it but setting \(V_{\text{NMDA}}\) to \(0\) are not equivalent, as one would predict from an ideal computational model, because of the different leakage current with and without the NMDA gating circuit. Measurement shows the latter condition may give several picoamps more leakage thus decreasing the excitability of the neuron. ## 5 Digital event routing and mapping scheme ### Inter-neuron routing and connection mapping scheme The routing scheme used within the core has been inspired by [20]. The details of this should not concern the user unless special edge cases are encountered (e.g., applications requiring very low latency or very high firing rate or many neurons firing Figure 22: Conductance block circuit (left: P-type, right: N-type) Figure 23: Application examples for the conditional dendritic functions: conductance, alpha-function and NMDA gating. (a) The neuron has both excitatory dendrites in conductance mode, with one of the reversal potentials set to \(0.5\,\mathrm{V}\) and its synaptic weight very high, and the other has the reversal potential at around \(0.7\,\mathrm{V}\) but the weight is low. The spiking threshold is set to around \(0.6\,\mathrm{V}\). Starting from the resting potential at around \(0.35\,\mathrm{V}\), when the first dendrite receives an input spike at time \(t=0\), it charges the soma up to the reversal potential, and when the second dendrite receives a spike shortly afterwards at time \(t=5\) ms, it further charges the soma until it crosses the firing threshold and emits a spike (the neuron then goes into its refractory period). However, if the second dendrite receives its input (at time \(t=100\) ms) before the first dendrite (at time \(t=105\) ms), then since the second dendrite by itself cannot drive the neuron to fire (due to the low weight) but the first dendrite cannot charge the soma once \(V_{mem}\) reaches its reversal potential (\(0.5\,\mathrm{V}\)), which is lower than the firing threshold, the neuron does not emit a spike and slowly leaks back to its resting potential. Thus this neuron could be used to detect the order in time of the two inputs, since it fires if and only if one input comes shortly before the other. (b) The neuron uses both excitatory dendrites, one using the alpha function and the other using only the normal DPI. If the first dendrite receives an input spike at time \(t=0\), it will start to charge the soma slowly (according to the alpha function), and if the second dendrite receives a spike shortly afterwards at time \(t=20\) ms, it will charge the soma even further to cross the firing threshold and emit a spike. However, if the second dendrite receives its input (at time \(t=300\) ms) before the first dendrite (at time \(t=320\) ms), then since the effect of the second dendrite goes away very fast, and the first dendrite by itself cannot charge the soma to cross the firing threshold either, the neuron does not emit a spike. This mechanism introduces a delayed dynamic, so it can also be used to detect the order of the two inputs. (c) The neuron uses the AMPA and NMDA dendrites. If the AMPA dendrite receives an input spike at time \(t=0\), it will charge the membrane potential to a value higher than the NMDA threshold (which is set to around \(0.1\,\mathrm{V}\)), and if the NMDA dendrite receives a spike shortly afterwards at time \(t=5\) ms, it will charge the soma to cross the firing threshold and emit a spike. However, if the NMDA dendrite receives the input (at time \(t=100\) ms) before the AMPA dendrite (at time \(t=105\) ms), then since the membrane potential at the moment when the NDMA dendrite receives the spike was still lower than the NMDA threshold, it has no effect on the soma, and the AMPA dendrite by itself cannot charge the soma to cross the firing threshold, so the neuron does not emit a spike. This mechanism forces an asymmetric condition on when the soma receives the input, so it can also be used to detect the order of the two inputs. simultaneously). The user must however understand the addressing scheme in order to make connections between neurons. The principle idea is to use AER to encode the spikes into a stream of bit patterns, so that they can be easily transmitted and routed within and outside of the chips. More Figure 24: Conditional dendritic blocks. (a) 2D diffusive grid connected to the AMPA dendrite. This can be enabled neuron-wise using the latch \(\mathsf{DEAM\_AMPA}\), and includes the corresponding neuron pseudo-resistor \(\mathsf{NRES}\) (\(R_{n}\) in the figure), the horizontal pseudo-resistor \(\mathsf{HRES}\) (\(R_{h}\) in the figure, between neuron \(n\) and \(n+1\)), and the vertical pseudo-resistor \(\mathsf{VRES}\) (\(R_{v}\) in the figure, between neuron \(n\) and \(n+16\)). The pseudo-resistors are implemented with single P-FETs, and the controllable parameters are the gate voltages \(\mathsf{DEAM\_NRES}\), \(\mathsf{DEAM\_HRES}\) and \(\mathsf{DEAM\_VRES}\). (b) NMDA gating. When enabled using the \(\mathsf{DENM\_NMDA}\) latch, the output current of the NMDA DDPI (here \(I_{in}\)) will flow out into the neuron’s \(I_{dendritic}\) if and only if the membrane potential \(V_{m}\) is higher than the NMDA threshold \(V_{\text{NMDA}}\) (set by \(\mathsf{DENM\_NMEV}\) parameter). Figure 25: AMPA diffusion in one dimension. The input spike is only sent to the neuron in the middle (neuron n), but the diffusion creates a bump in the membrane potentials in the neurons in its (here, 1D) neighborhood. specifically, on DYNAP-SE2, each normal inter-neuron event is encoded as a 24-bit word comprising a format indicator bit (bit 23 = 0) and four variable fields as shown in Table 4, the event tag, the target chip displacements in the x and y directions (dx and dy respectively) and the cores mask that determines which cores the event is delivered to on the target chip. Each neuron has four 23-bit SRAMs to store four combinations of tag, dy, dx and cores. When the pre-neuron fires, the router will read and transmit the content of these four SRAMs. This is known as source mapping. This is in contrast to DYNAP-SE [20] which does not include arbitrary source mapping and is therefore limited in the network connectivity it could implement. There is no dedicated 'enable' bit for an outgoing event, but if none of the four cores on the target chip is selected (\(\texttt{cores}=0000\texttt{b}\)), the event will be dropped by the router. The events are transmitted inside a 2D grid of trees, where every chip has a tree routing structure and four grid connections to the neighboring chips. When an event arrives at a chip (this can be the sender chip itself), the top-level router will decide, based on the target chip displacement bits, whether the event should be kept for this chip (dx = 0 and dy = 0) or forwarded further on one of the grid buses (west if dx \(<\) 0, east if dx \(>\) 0, south if dx \(=\) 0 and dy \(<\) 0, north if dx \(=\) 0 and dy \(>\) 0, see Section 6.2 for more details). If the top-level router decides to keep the event, it will be sent to all cores that are selected in the cores bits. Once it has arrived in a core, an event is identified only by its 11-bit tag. This means that when two events with the same tag arrive in the same core, there is no way for a neuron in that core to tell them apart, even if they come from different pre-neurons. This is used to share synapses as the tags can be assigned arbitrarily in the source mapping. The 11-bit tag is broadcast to all 256 neurons \(\times\) 64 synapses in the core. Each synapse is provided with an 11-bit CAM. If all eleven bits of the broadcast tag match those in a synapse's CAM, an active low'match' signal is sent to the synapse circuitry as described in the caption of Fig. 18. This matching process is known as destination mapping. ### Example configurations To better illustrate the tag scheme, two concrete examples of how the tag in the SRAMs of the pre-neurons and in the CAMs of the post-neurons can be used are shown in Python-like pseudo-code: 1. For all-to-all connections from n neurons (in list pre) to r synapses on each of n neurons (in list post), a single tag x is used: for i in range(n): neurons[pre[i]].grams[0].tag = x for k in range(r): neurons[post[i]].cams[k].tag = x \begin{table} \begin{tabular}{|c| 2. To connect each of the n pre neurons (in list pre) to the \((2\texttt{r}+1)\) neighbors (mod n) in the n post neurons (in list post), tags in the interval \([\texttt{x},\texttt{x}+\texttt{n}]\) are used: for i in range(n): neurons[pre[i]].srams[0].tag = x + i for k in range(-r, r + 1): neurons[post[i]].cams[r + k].tag = x + ((i + k) % n) ### Multiplexing of four neurons For networks that require higher synaptic counts, there is an option to merge the dendrites of four neurons into one (enabled using the latch DE_MUX, set for each core individually). This increases the number of synapses per neuron to 256 and reduces the number of neurons by a factor of four. More specifically, the PSCs \(I_{ dendritic}\) and \(I_{somatic}\) of neurons 0, 1, 16 and 17 will all go to the soma of neuron 0; those of neurons 2, 3, 18 and 19 will go to the soma of neuron 2, etc. ### 2D event sensor routing and mapping scheme A separate pipeline for mapping and routing is available for 1D and 2D event streams originating from sensors. It is an earlier version of the event pre-processor block described in [22]. These sensor events can be routed in an alternative event word format on the 2D routing grid buses described in Section 5.1. The events are then encoded with a format indicator bit (bit 23 = 1) and five variable fields as shown in Table 4, the event polarity pol, the x and y coordinates of the event (pixel_x and pixel_y respectively), and the target chip displacements in the x and y directions (dx and dy respectively). The mapping pipeline consists of multiple stages as shown in Fig. 26. The pipeline has the following blocks: * Sensor Interface: The chip can interpret event formats from the following sensors directly via parallel AER: DAVIS346 [43]; DAVIS240 [44]; DVS128_PAER [23]. Other sensors such as AEREAR2 [45] or ATIS [46] can be interfaced to the event routing grid by following the sensor event word format described above. * Pixel Filtering: Up to 64 arbitrary addresses can be discarded from the sensor event stream. This is done in one step using content addressable memory. * Event Duplication: The pipeline can optionally duplicate and forward unprocessed events to one of the four surrounding chips. * Sum Pooling: This can be used to scale the 2D input space by 1:1, 1:2, 1:4 or 1:8 in the x and y directions individually. * Cutting: Cutting can be used to cut a 1\(\times\)1 up to 64\(\times\)64 pixel sized patch out of the 2D input space that is forwarded for source mapping. * Polarity Filtering: Polarity selection provides the ability to use a specific polarity or both polarities. * Source Mapping: A patch of 64\(\times\)64 pixels can be arbitrarily mapped one to one (specifying tag, dx, dy and cores) to the standard event word format. Such mapped events are introduced to the top level router for further routing and mapping inside the normal event system, as described in Section 5.1. ## 6 Chip interfaces In addition to the North, South, East and West grid bus interfaces already alluded to in Sec. 5 and further remarked upon in Sec. 6.2 below, each DYNAP-SE2 has a multi-purpose input interface (Sec. 6.1), a few pins for limited direct monitoring of internal signals (Sec. 6.3), outputs from on-chip monitoring circuits (Sec. 6.4), a sensor interface as described in Sec 5.4, and inputs and monitoring points for the Analog Front-End (AFE). See [21] for more details of the AFE and Fig. 27 for how it appears on the chip. ### Multi-purpose input-interface The input interface (II) uses split-parallel AER to cover a wide range of configuration and communication functions including direct event input from a host system and chip configuration which in turn includes parameter generator configuration, neuron latch configuration, connectivity memory (SRAM, CAM) configuration and natural signal AFE configuration. Split-parallel AER means that notional 40-bit AE words are presented in two cycles of \(40/2+1\) bits each, i.e. one cycle for the most significant and one for the least significant half of each AE word. The additional bit in each cycle is used to differentiate the two half-words. This split parallel operation is chosen to keep the chip pin count more manageable. Figure 26: The sensory mapping and routing pipeline. As one pipeline can only process one patch of at most 64\(\times\)64 pixels, the Event Duplication block can clone and send sensor events to a second pipeline on one of the four surrounding chips by providing the target coordinates via the Destination Append block. The spike events can be sent to \(\pm 7\) in \(x\) and \(y\) chip grid coordinates. ### Inter-chip event communication As alluded to in Sec. 5, each chip has four high-speed asynchronous AER buses on the four sides to directly transfer events in and out of the chip. The pins are assigned in such a way that adjacent chips can be conveniently connected together, which facilitates network scalability across a 2D grid. Each chip can directly address a neighborhood comprising up to seven chips in each direction, which allows a maximal \(8\times 8\) fully connected chip array without any external mapping. Using an alternative packet format, this grid also transmits and receives sensor events to and from its direct neighbors, see Sec. 5.4. ### Direct monitoring Some important analog signals are copied to six external pins through rail-to-rail buffers so that they can be monitored directly off-chip using an oscilloscope for debugging purposes. These are a neuron membrane potential from all four cores and analog voltage or current reference parameters from Parameter Generators 0 and 1. Also externally available are digital homeostasis charging direction signals from all four cores and a digital delay pulse extender pulse from particular synapses on each core. ### On-chip monitoring Sixty-four on-chip, current-based spiking analog to digital converters (sADC) ensure easy monitoring of all relevant neural signals. This greatly improves the configuration experience and usability. The signals are divided into three separately configurable groups, in order to adapt to the wide range of signal magnitudes. \begin{table} \begin{tabular}{c c c} \hline Group 0 & Group 1 & Group 2 \\ \hline External profiling voltage & Internal calibration voltage & Internal calibration voltage \\ Membrane potential & Adaptation/Ca DPI & Synapse 20/41 weight \\ Refractory pulse extender & Dendritic DPIs & Homeostasis gain \\ \hline \end{tabular} \end{table} Table 5: sADC groups Figure 27: The corner of the chip, showing the eight channels of the Analog Front-End (AFE), including everything presented in [21]. ## 7 Software ### Synsense Samna In order to enable users to perform experiments with DYNAP-SE2 chips, software support is provided through the Samna* software **[Samna{}]**. Samna has been developed by Synsense **[Synsense{}]** to support a diverse range of current and future neuromorphic chips. Footnote *: name hidden for double-blind review process #### 7.1.1 Objectives of Samna Samna aims to: provide unified support for a diverse range of neuromorphic chips; be'remotable'; provide a GUI, and at the same time a conventional programming interface; be performant; and run on multiple operating systems. All of the chips supported by Samna should be supported in a similar way, such that once a user is familiar with the GUI and the API for one chip, the experience is reasonably portable to the use with other chips, thus saving the user familiarization time. Samna aims to support the remote use of DYNAP-SE2 (and other chips) such that the user interface and user-supplied code can (but need not) run on a different computer (e.g. the user's laptop) from the computer to which the chips are attached, be it at the same desk, in a server room in the same building, or half-way around the world. This facility has already proved invaluable in teaching. Students working at home have been able to perform experiments on DYNAP-SE2 chips without having to be physically provided with the hardware. Experience with earlier generations of mixed-signal neuromorphic chips has shown that it is highly advantageous to provide a graphical user interface (GUI) to provide visual feedback of, for instance, neural spiking activity, and to provide on-screen virtual potentiometers to control on-chip analog parameters. This is particularly important while initially tuning those parameters. At the same time, for anything beyond this most trivial of interactions, an application programming interface (API) of some kind is essential. In earlier software, the existence of these two interfaces, through which the state of the neuromorphic chips which are being used could be altered, caused problems, as the state could be changed in the GUI without this being apparent to code using the API and _vice versa_. Avoiding these kinds of discrepancies between different components' view of the state information has been key to the architecting of Samna. The API presented to the user is in Python 3, as Python has become the _de facto_ standard in neuroscience, in particular in the field of modeling and simulation [47, 48]. The underlying code, however, is in C++ (C++17) for performance. Finally, for broad acceptance and ease of use, it is important that Samna is supported on multiple platforms. Currently Linux and macOS are supported. ### The Software and Hardware Stack Figure 28 shows the full stack of DYNAP-SE2 software and hardware, from the user's Python code and the GUI at the top to the DYNAP-SE2 chips at the bottom. Figure 28: Full software and hardware stack showing the main DYNA-SE2 related components of Samna and the corresponding hardware. The modules marked with a * were written as part of the DYNA-SE2 project. When Samna is used with other chips, the corresponding module (not shown) is used instead of the DYNA-SE2 module. If a different interface board is used, a different module will be used instead of the OpalKelly module. The following description concentrates on the DYNAP-SE2 and FPGA firmware communication modules of Samna, as these were the modules written in the course of the DYNAP-SE2 project. #### 7.2.1 User code, GUI and object store Although the GUI is part of Samna, it is on equal footing with the user's code when accessing the rest of the system. Both talk to the DYNAP-SE2 module of Samna via a local remoting layer and a remote object store where the remote object store and everything below it may be on a remote computer. Objects from the DYNAP-SE2 module (and other similar modules supporting other hardware, not shown in Fig. 28) can be placed in the object store and transparently retrieved from there by the user's code and/or the GUI. They can then be manipulated and returned to the store and thus to the lower modules. The user's Python code only sees a Python extension library which can be imported in the usual fashion: import <software> from <software>.<chip> import * import samna from samna.dynapse2 import * From this point on, barring a little setup to connect to a remote Samna node, the user need not be aware of the presence of the object store, or that the hardware might be attached to a remote machine. The classes in <software>.<chip> samna.dynapse2 can all be used transparently as if everything was local. Within Samna, the actual Python interface to the underlying C++ code is implemented with the aid of pybind11 [49]. #### 7.2.2 DYNAP-SE2 module Within Samna's DYNAP-SE2 module, there are DYNAP-SE2Interface classes which provide an interface to facilities provided by the PCB(s) on which the DYNAP-SE2 chips are mounted. At the time of writing, two DYNAP-SE2Interface classes exist: DYNAP-SE2DevBoard and DYNAP-SE2Stack are available for the two present PCB types, dev board and stack respectively. Alongside the DYNAP-SE2Interface class is the DYNAP-SE2Model class which provides an interface to an abstraction, held in a DYNAP-SE2Configuration class, of the hardware state in the physical DYNAP-SE2 chip(s). The DYNAP-SE2 chips do not support the read-out of internal state, so the entire state information is held in software in the DYNAP-SE2Configuration class and other aggregated classes which are not shown in the figure. See Sec. 7.2.5 below for details. In operation, the user's code, and/or the GUI, obtains a reference to a DYNAP-SE2Model object via the object store, then gets the current configuration of the hardware from the DYNAP-SE2Model object as a DYNAP-SE2Configuration object, modifies that object and the tree of objects within it representing the neuron and synapse configuration information, and applies the DYNAP-SE2Configuration object back into the DYNAP-SE2Model object and hence to the hardware. This process can then be performed repeatedly, see Fig. 29. In this way, changes made by the user's code are visible to the GUI and _vice versa_. When the DYNAP-SE2Configuration object is set back into the DYNAP-SE2Model object, the DYNAP-SE2Model determines the changes from the current configuration and uses event generator functions to produce a list of configuration events sufficient to bring about those changes on the DYNAP-SE2 chip(s). This list of events is then passed to the DYNAP-SE2Interface object for transmission to the hardware. Meanwhile, address-event (AE) streams to and from the hardware pass directly to and from the user code and the GUI directly via the same DYNAP-SE2Interface object. #### 7.2.3 FPGA firmware communication module and below The FPGA firmware communication module manages the packet-based communication with the firmware instantiated in the FPGA on the hardware. To avoid overhead associated with constantly allocating and freeing packet buffers, the firmware communication module manages a pool of constant-length packet buffers. Empty packet buffers are then obtained by the overlying hardware-specific module(s), in this case by a DYNAP-SE2Interface object in the DYNAP-SE2 module, when there are events to send to the hardware. The hardware-specific module is responsible for filling in the payload of the packet before calling back into the firmware communication module to let the latter complete the header of the packet with appropriate payload size information and put the packet on a transmit queue. The firmware communication module is also home to a thread which continually attempts to read from the underlying hardware platform support module. At the time of writing, for DYNAP-SE2 this is always the OpalKelly module, since both the supported dev board and stack boards interface via Opal Kelly [50] FPGA Integration Modules. After each read, the firmware communication module determines whether the firmware is ready to accept more data, and if so, how much. It then takes as many packets as possible from the transmit queue and writes them out via the OpalKelly module, packing them into the blocks that the OpalKelly layer understands. Once the packet buffer contents have been copied into the OpalKelly blocks, the packet buffers are returned to the packet buffer pool. The OpalKelly model abstracts the 'Pipe' and 'Wire' interface provided by the Opal Kelly hardware and communicates with the hardware via libusb [51]. Finally when the Opal Kelly board receives the blocks assembled by the software, the FPGA firmware unpacks the individual packets from the Opal Kelly blocks and passes the event data contained in the packets to the DYNAP-SE2 chips via the appropriate bus. Figure 29: get_configuration(), modify configuration, apply_configuration() loop. #### 7.2.4 Events from the chip(s) Events coming from the inter-chip communication buses and from the sADC output of the DYNA-SE2 chip(s) are read by the firmware in the FPGA on the Opal Kelly board. In the case of inter-chip communication events, these events are timestamped and placed in packets. In the case of sADC events, the number of events received for each possible sADC address in a fixed time interval are counted, and all of these counts are placed into a different packet type at the end of the interval. In both cases, the packets are placed in blocks and transmitted over USB to the host. When these blocks are read by the thread referred to above in Samna's FPGA firmware communication module, the packets are unpacked from the blocks into buffers taken from the packet buffer pool and dispatched according to packet type. In the case of the normal timestamped events, the packets are placed into a queue from which they can be read by the top-level code via the DYNA-SE2Model object. In the case of sADC count packets, the packet contents are written into a buffer which always holds the latest sADC count values which is also available to be read by top-level code via the DYNA-SE2Model object. #### 7.2.5 DYNAP-SE2Configuration aggregation hierarchy As mentioned above in Sec. 7.2.2, the entire DYNA-SE2 hardware state information is held in the software in DYNA-SE2Configuration objects and a hierarchical aggregation of Plain Old Data (POD) types and objects of further classes: DYNA-SE2Chip, DYNAP-SE2Core, DYNAP-SE2Neuron, DYNAP-SE2Synapse etc., which themselves are (almost all) POD types, i.e. they are aggregates with only public data. It is this hierarchically organised data structure which the user manipulates in their Python code to control the operation of the DYNAP-SE2 chips. ## 8 Discussion The large range of dynamics and computing features supported by the DYNAP-SE2 support the definition of networks that can solve a wide range of applications. Similarly, the DYNAP-SE2 fully configurable tag-based routing system enables the definition of arbitrary network topologies, ranging from simple feed-forward neural networks, to fully recurrent ones. Feed-forward networks are the simplest form of network architectures, in which the neurons process events as they move through the layers of the network. Sparse feed forward networks can be built by dividing the available neurons into layers, and forming unidirectional synaptic connections between layers [52]. Unlike in standard crossbar and addressable column approaches [53, 54], the CAM-based synaptic addressing allows all the available physical synapses to be used [20]. To support dense feed forward networks and allow users to define heterogeneous networks with different fan-in and fan-out figures, each core allows the number of programmable synapses to be increased to 256 per neuron, at the cost of a reduced number of neurons (64 instead of 256). The asynchronous and mixed signal design of the DYNAP-SE2 is particularly well suited for emulating the dynamics of recurrent spiking neuronal network architectures. The native support for recurrent mapping and continuous physical time emulation overcomes the limits of digital time-multiplexed simulation systems, avoiding the need for complex clock tree designs and reducing signal synchronization issues. Reservoir networks use recurrent connections to build complex network dynamics supporting a'memory trace' of their activity over time. Attractor networks can exploit recurrent connectivity patterns to memorize patterns, recover partial or corrupted input patterns, and perform stateful computation [55, 56]. Both feed-forward and recurrent networks can be configured to implement time-to-first-spike (TTFS) computation. This paradigm relies on the latency of spike waves traveling through a network, like wavefront algorithms [57] or as seen in the nervous systems of weakly electric fish [58]. The low-latency nature of DYNAP-SE2 and its ability to support delay-based synapses make TTFS applications first class citizens. In particular, the fact that synapses can be configured to belong to one of four delay classes (with two well-matched -precise- classes, and two purposely mismatched -inhomogeneous- classes) provide a controlled distribution of delays which enables both precise time-to-first-spike configurations, and randomly timed networks [59, 60]. The ability to configure synapses as diffusive gap junctions [61] with 2D nearest neighbor connections supports the configuration of networks with local spatially distributed connectivity kernels, as originally proposed in [36, 62]. In addition, excitatory synapse circuits can be configured to emulate both slow voltage-gated NMDA receptor dynamics [31] as well as fast AMPA dynamics [35]. For both AMPA and NMDA synapse types (as well as both inhibitory types, GABA-A and GABA-B), the 4-bit weight resolution, combined with the configurable weight-range scale enable users to explore and implement more advanced hardware-in-the-loop learning systems. The improved spike-frequency adaptation circuits present in the neuron circuits [41], the neuron's homeostatic synaptic scaling circuit [33], and the synapse short term depression plasticity control [31] provide the user with a large range of computational primitives for exploring dynamics at multiple time scales and produce complex dynamic behaviors [63]. Finally, the ability to monitor all dendritic, somatic and synaptic current traces via asynchronous current-to-frequency ADCs [38] greatly simplifies prototyping and debugging in experiments that explore the dynamics and computing abilities of the DYNAP-SE2. ## 9 Conclusion We presented a full custom implementation of a DYNAP-SE2, built for prototyping small networks of spiking neurons that emulate the dynamics of real neurons and synapses with biologically plausible time constants, for interacting with natural signals in real time. We argued that the real-time nature of the system and its direct sensory-input interfaces for receiving 1D and 2D event streams make this an ideal platform for processing natural signals in closed-loop applications. We characterized in detail all circuits present on the chip and presented chip measurements that demonstrate their proper operating function. This platform will enable the prototyping of biologically plausible sensory-processing systems and the construction of physical neural processing systems that can be used to validate (or invalidate) hypotheses about neural computing models. The authors would like to thank Mohammadi Sharifshazileh his work on the initial PCB design and management of the packaging process. The authors would like to thank Melika Payvand for her help with design submission administration and additional simulations of the AMPA resistive grid design. The authors would like to acknowledge Sunil Sheelavant for his contribution to the pad frame schematic. The authors would like to acknowledge the financial support from SynSense AG, Thurgauerstrasse 60, 8050 Zurich, Switzerland, and NeuroAgents an ERC Consolidator project (No. 724295) [https://doi.org/10.3030/724295](https://doi.org/10.3030/724295). Ole Richter would like to acknowledge the financial support of the CogniGron research center and the Ubbo Emmius Funds (University of Groningen). During the ASIC design Ole Richter was solely affiliated to SynSense AG. **Author Contribution:** G.I. conceived the original concepts and analog circuit designs. Q.N. and O.R. implemented the mixed-signal and the asynchronous circuit designs and architecture. C.W. and G.K. designed the printed circuit board and peripheral logic. C.W. and C.N. wrote the low-level firmware. A.W. and C.N. wrote the high-level software. C.W. carried out chip measurements and testing. All authors contributed to the manuscript writing efforts, G.I. supervised the project.
2303.04612
Differential Privacy Meets Neural Network Pruning
A major challenge in applying differential privacy to training deep neural network models is scalability.The widely-used training algorithm, differentially private stochastic gradient descent (DP-SGD), struggles with training moderately-sized neural network models for a value of epsilon corresponding to a high level of privacy protection. In this paper, we explore the idea of dimensionality reduction inspired by neural network pruning to improve the scalability of DP-SGD. We study the interplay between neural network pruning and differential privacy, through the two modes of parameter updates. We call the first mode, parameter freezing, where we pre-prune the network and only update the remaining parameters using DP-SGD. We call the second mode, parameter selection, where we select which parameters to update at each step of training and update only those selected using DP-SGD. In these modes, we use public data for freezing or selecting parameters to avoid privacy loss incurring in these steps. Naturally, the closeness between the private and public data plays an important role in the success of this paradigm. Our experimental results demonstrate how decreasing the parameter space improves differentially private training. Moreover, by studying two popular forms of pruning which do not rely on gradients and do not incur an additional privacy loss, we show that random selection performs on par with magnitude-based selection when it comes to DP-SGD training.
Kamil Adamczewski, Mijung Park
2023-03-08T14:27:35Z
http://arxiv.org/abs/2303.04612v1
# Differential Privacy Meets Neural Network Pruning ###### Abstract A major challenge in applying differential privacy to training deep neural network models is scalability. The widely-used training algorithm, _differentially private stochastic gradient descent (DP-SGD)_, struggles with training moderately-sized neural network models for a value of \(\varepsilon\) corresponding to a high level of privacy protection. In this paper, we explore the idea of dimensionality reduction inspired by neural network pruning to improve the scalability of DP-SGD. We study the interplay between neural network pruning and differential privacy, through the two modes of parameter updates. We call the first mode, _parameter freezing_, where we pre-prune the network and only update the remaining parameters using DP-SGD. We call the second mode, _parameter selection_, where we select which parameters to update at each step of training and update only those selected using DP-SGD. In these modes, we use public data for freezing or selecting parameters to avoid privacy loss incurring in these steps. Naturally, the closeness between the private and public data plays an important role in the success of this paradigm. Our experimental results demonstrate how decreasing the parameter space improves differentially private training. Moreover, by studying two popular forms of pruning which do not rely on gradients and do not incur an additional privacy loss, we show that random selection performs on par with magnitude-based selection when it comes to DP-SGD training. ## 1 Introduction Differential privacy (DP) [4] is a gold standard privacy notion that is widely used in many applications in machine learning. Generally speaking, the _accuracy_ of a model trained with a dataset trades off with the guaranteed level of _privacy_ of the individuals in the dataset. One of the most popular differentially private (DP) training algorithms for deep learning is _DP-SGD_[1], which adds a carefully calibrated amount of noise to the gradients during training using stochastic gradient descent (SGD) to provide a certain level of differential privacy guarantee for the trained model at the end of the training. Since it adds noise to the gradients in every training step, its natural consequence is that the accuracy of the model drops. Typically, the trade-off between the privacy and accuracy gets worse when the model size gets larger, as the dimension of the gradients increases accordingly. In the current state of differentially private classifier training, the performance between small and large models is striking. A small two-layer convolutional neural network trained on MNIST data with \(\epsilon=2\) provides a classification accuracy of \(95\%\)[16]. However, a larger and more complex architecture, the ResNet-50 model, containing \(50\)-layers, trained on ImageNet data with \(\epsilon<5\) provides a mere classification accuracy of \(2.4\%\), while the same model without privacy guarantee achieves \(75\%\) accuracy [7]. Given that this is the current-state-of-the-art in the literature, we cannot help but notice a disappointingly huge gap between the differeitally privately trained and non-privately trained classifiers. Why is there such a large gap between what the current state-of-the-art deep learning can do and what the current state-of-the-art differentially private deep learning can do? The reason is that those deep models that can reliably classify high-dimensional images are extremely _large-scale_ and DP-SGD does not scale to these large models. The definition of DP requires that every parameter dimension has to be equally guarded. For example, consider two models, where first model has \(100\) parameters and second model has \(1000\) parameters, where these parameters are normalized by some constant (say \(1\)) to have a limited sensitivity, which is required for the DP guarantee. As we need to add an equal amount of independent noise to each of the parameters to guarantee DP, where the parameters are normalized by the same constant, the signal-to-noise ratio per parameter becomes roughly \(100\) times worse in the second model with \(1000\) parameters compared to the first model with \(10\) parameters. From this observation, it might look almost dispiriting to make any reasonably sized deep neural network models differentially private and maintain their original accuracies. In this work, inspired neural network pruning, we explore the impact of reducing the parameter space on differentially private training. Respectively, we apply pruning in two forms, (1) parameter freezing where the set of trainable network parameters is decreased prior to the private training, and (2) parameter selection, where the parameter space is preserved but only a subset of weights is updated at every iteration. This work results in a number of intriguing observations: 1. For training in a differentially private fashion, pruning in both forms improves the network performance at a given privacy level, compared to DP-SGD. Interestingly, we found that our pruning-based dimensionality reduction is as effective as the PCA-based dimensionality reduction like that in [16], while these two use an entirely different criterion to reduce the dimensionality of the parameters. 2. At small \(\epsilon\) (i.e., in high privacy regime), we found that higher pruning rates improves the accuracy of the DP trained models. 3. Parameter freezing improves the performance more at small \(\epsilon\) (i.e., in high privacy regime), while parameter selection fares better in medium-to-low privacy levels. 4. Surprisingly, random selection fares the same or better as selecting weights based on the magnitude of the gradients. Similar observations have been made in [19], but not in the context of transferring knowledge from public to private data. 5. Similar to transfer learning, the more similar private and public data are, the better the performance of our algorithm gets even in the presence of noise for privacy. Experimental results prove to narrow the gap between the performance of privately trained models and that of non-privately trained models by improving the privacy-accuracy trade-offs in training large-scale classifiers. In what comes next, we start by describing relevant background information before introducing our method. ## 2 Background This work builds on the ideas from neural network pruning. While neural network pruning has a broad range of research outcomes, we summarize a few relevant works that help understand the core ideas of our algorithm. We then also briefly describe differential privacy for an unfamiliar audience. ### Neural Network Pruning The main reasoning behind neural network pruning is that neural networks are typically considered over-parametrized, and numerous observations indicate that pruning out non-essential parameters does not sacrifice a model's performance by much. There are two types of pruning techniques: one-shot pruning and iterative pruning. **One-shot pruning.** One-shot pruning is the process that follows a three-step procedure. The network is trained from scratch. This model, also known as the pre-trained model, is the base for network pruning. Then given some criteria, the model is pruned, and some parameters are removed which results in a new architecture which is a sub-architecture of the original model. This step, however, results in the loss of accuracy. To compensate for this loss, the remaining network is fine-tuned to recover the accuracy. This is the idea we will use in our first mode, parameter freezing, where we pre-train a model with a public dataset and pre-prune the parameters based on a certain criterion. We then train these remaining parameters using DP-SGD. **Iterative pruning.** The second mode is iterative pruning. Iterative pruning is similar to one-shot pruning but the three-step process known from one-shot pruning is repeated multiple times and the parameters are pruned gradually. While in one-shot pruning, the parameter removal happens at one time, iterative pruning proceeds over several iterations. At each iteration, a fraction of parameters is removed and the rest of the network is fine-tuned. This is the very idea we will use in our second mode, parameter selection. We select parameters to update in every training step, where this selection is done based on public data, and update the selected ones using private data with DP-SGD. Consequently, we adapt these ideas to improve differentially private training by reducing the space of the parameter to be updated. This distinguishes our work from the majority of the neural network compression literature, which aims to compress the model. This procedure is supposed to alleviate the accuracy-privacy trade-off and shift the Pareto line. Subsequently, we present the core privacy ideas which stand behind the above-mentioned trade-off. ### Differential privacy and DP-SGD A mechanism \(\mathcal{M}\) is (\(\epsilon\), \(\delta\))-DP, if the output of the mechanism given a dataset \(\mathcal{D}\) is _similar_ to that given a neighbouring dataset \(\mathcal{D}^{\prime}\) where neighbouring means \(\mathcal{D}\) and \(\mathcal{D}^{\prime}\) have one sample difference, and the similarity is defined by a selected value of \(\epsilon\) and \(\delta\), which quantify the privacy guarantees. Mathematically, when the following equation holds, we say \(\mathcal{M}\) is (\(\epsilon\), \(\delta\))-DP: \(\Pr[\mathcal{M}(\mathcal{D})\in S]\leq e^{\epsilon}\cdot\Pr[\mathcal{M}( \mathcal{D}^{\prime})\in S]+\delta,\) where the inequality holds for all possible sets of the mechanism's outputs \(S\) and all neighbouring datasets \(\mathcal{D}\), \(\mathcal{D}^{\prime}\). The _Gaussian mechanism_ is one of the most widely used DP mechanisms. As the name suggest, the Gaussian mechanism adds noise drawn from a Gaussian distribution, where the noise scale is proportional to two quantities, the first one is, so called, _global sensitivity_ (which we denote by \(\Delta\)) and the second one is a privacy parameter (which we denote by \(\sigma\)). The global sensitivity of a function \(g\)[3] denoted by \(\Delta_{g}\) is defined by the maximum difference in terms of \(L_{2}\)-norm \(\|g(\mathcal{D})-g(\mathcal{D}^{\prime})\|_{2}\), for neighbouring \(\mathcal{D}\) and \(\mathcal{D}^{\prime}\). In the next section we will describe the relationship between global sensitivity and gradient clipping in case of neural networks. The privacy parameter \(\sigma\) is a function of \(\epsilon\) and \(\delta\). Given a selected value of \(\epsilon\) and \(\delta\), one can readily compute \(\sigma\) using numerical methods, e.g., the auto-dp package by [15]. It is worth noting two properties of differential privacy. The _post-processing invariance_ property [3] states that the composition of any data-independent mapping with an \((\epsilon,\delta)\)-DP algorithm is also \((\epsilon,\delta)\)-DP. The _composability_ property [3] states that the strength of privacy guarantee degrades in a measurable way with repeated use of the training data. In the neural network training, we first take a mini-batch of data samples drawn from the training dataset, then compute the sum or average of the gradients evaluated on the mini-batch. Here, we simply do not know how much one datapoint's difference would change the L2 norm of the sum or the average of the gradients. Hence, we adopt a simple clipping procedure to ensure the average or sum of the gradients has a limited sensitivity. Once we clip the sample-wise gradient - the gradient evaluated on each datapoint in the mini-batch - we add the Gaussian noise, where the noise scale is proportional to the clipping norm and \(\sigma\) in case of sum, or the clipping norm and \(\sigma\) divided by the mini-batch size in case of average. The resulting algorithm is called DP-SGD[1]. Due to the composability of differential privacy, the cumulative privacy loss increases as we increase the number of training epochs (i.e., as we access the training data more often with a higher number of epochs). When models are large-scale, the required number of epochs until convergence increases as well, which imposes more challenges in achieving a good level of accuracy at a reasonable level of privacy. Our method, which we introduce next, provides a solution to tackle this challenge. ## 3 Method We propose a differentially private training framework that uses public data for pre-training a large-scale classification model and then fine-tunes the model to private data by updating only a few selected gradients using DP-SGD. We call our method, _differentially private sparse stochastic gradient descent_ (DP-SSGD). The summary of our algorithm is given in Fig. 1. ### Vanilla DP-SGD Suppose a neural network model with an arbitrary architecture denoted by \(f\), and parameterized by \(\theta\). We first describe the vanilla DP-SGD algorithm [1]. As in the regular stochastic gradient descent, at each training step \(t\), a dataset mini-batch \(\mathcal{B}^{(t)}\) (where \(|\mathcal{B}|=B\)) is drawn, and, given that mini-batch, the gradient of the loss \(l\) is computed. However, to ensure the privacy, the learning needs to be controlled, and thus the \(L2\)-norm of the gradients is bounded with the, so-called, clip-norm \(C\). As such, the gradient is given by \(g=\frac{1}{B}\sum_{b\in\mathcal{B}^{(t)}}\nabla^{C}[b]\), where the sample-wise gradient \(\nabla^{C}[b]=\frac{\partial}{\partial\theta}l(b)\) is norm-clipped such that \(\|\frac{\partial}{\partial\theta}l(b)\|_{2}\leq C\) for all \(b\in\mathcal{B}^{(t)}\) to ensure the limited sensitivity of the gradients. We then add noise to the average gradient such that \[\theta^{(t+1)}\ \leftrightarrow\ \theta^{(t)}-\frac{\eta}{B}\left[\sum_{b\in B ^{(t)}}\nabla^{C}[b]+\sigma C\zeta\right] \tag{1}\] where \(\eta\) is the learning rate, and \(\sigma\) is the privacy parameter, which is a function of a desired DP level \((\epsilon,\delta)\) (larger value of \(\sigma\) indicates higher level of privacy), and \(\zeta\) is the noise such that \(\zeta\sim\mathcal{N}(0,I)\). Note that higher clipping norms \(C\) result in higher levels of noise added to the gradient. How our method deviates from DP-SGD is in the following way. ### Sparsification The key tool used for our method is gradient pruning which selects which weight parameters are updated. For a given layer, let \(I\) be a list of vectors such that \(i\in I\) and \(i\in\mathbb{R}^{4}\) for convolutional layers where the indices of \(i\) describe output, input and two dimensional kernel dimensions, and \(i\in\mathbb{R}^{2}\) for fully-connected layers, where the indices describe output and input dimensions. As a result of this selection step, we split the index set \(I\) of all the weights into two groups. The first group is an index set \(I_{s}\) that contains all the selected indices for the gradients that we will update in the following step; another index set \(I_{ns}\) that contains all the non-selected (or discarded) indices for the gradients that we will not update. Moreover, define pruning rate \(p\) as the fraction of the gradients which are discarded. Then \(I=I_{s}\cup I_{ns}\) **Parameter index selection.** Now at time \(t\), we subsample a a mini-batch \(\mathcal{B}^{(t)}\) from the private dataset and compute the gradients on the private mini-batch. As in DP-SGD, we clip the sample-wise gradients. However, for each \(b\in\mathcal{B}\), we clip _only_ the selected weights indicated by the index set \(I_{s}\): \[\nabla^{C}=\frac{\nabla^{C}[I_{s},b]}{\max\left(1,\frac{|\nabla^{C}[I_{s},b]|}{ C}\right)}, \tag{2}\] Smaller gradient norm benefits gradients in two crucial ways. Firstly notice that decreasing the size of the gradients will be clipped only if \(|\nabla^{C}[I_{s},b]|>C\). Moreover, they are clipped proportionally to the value \(\frac{|\nabla^{C}[I_{s},b]|}{C}\), therefore small gradient norm results in less clipping. Reducing the parameter size results in decreasing the norm and preserving larger gradient values. In other words, we trade off small gradients for keeping the large signal. Whether we use the full-size gradients or the gradients of selected gradients, if we use the same clipping norm \(C\), the sensitivity of the sum of the gradients in both cases is simply \(C\). However, adding noise to a vector of longer length (when we do not select weights) has a worse signal-to-noise ratio than adding noise to a vector of shorter length (when we do select weights). Moreover since the neural network models are typically over-parameterized and contain a high level of redundancy, we observe that dropping a large portion of gradients does not hamper the training. This means the length of \(I_{s}\) can be significantly smaller than the length of \(I\). This is useful in reducing the _effective_ sensitivity of the sum of the gradients. We then update the parameter values for those selected using DP-SGD: \[\mathbf{\theta}^{(t+1)}[I_{s}]=\hat{\mathbf{\theta}}^{(t)}[I_{s}]-\frac{ \eta_{t}}{B}\left[\sum_{b\in\mathcal{B}^{(t)}}\nabla^{C}[I_{s},b]+\sigma C \zeta\right], \tag{3}\] where \(\zeta\sim\mathcal{N}(0,I)\). For the parameters corresponding to the non-selected gradients indicated by \(I_{ns}\), we simply do not update the values for them, by \[\mathbf{\theta}^{(t+1)}[I_{ns}]=\mathbf{\theta}^{(t)}[I_{ns}]. \tag{4}\] We finally update the parameter values to the new values denoted by \(\mathbf{\theta}^{(t+1)}\). We repeat these steps until convergence. ### Two modes of sparsification In the previous section, we define the sparsification. In this section, we describe sparsity constraints, that is which weights can be updated at every iteration. We distinguish two modes of sparsifying the neural network training, inspired by neural network pruning. In the first mode given the pretrained model, we select a fixed set of parameter indices that are removed from the original network and the remaining parameters are fine-tuned. The second one is to maintain the original dimensions of the network and, at every iteration, select the subset of parameters to be updated. We describe in detail the two modes below. **Parameter freezing.** We first assume parameter redundancy. According to neural network pruning literature, a model can be compressed by removing redundant parameters, and retain the original performance via retraining. In this line of thinking, the index set of selected weights, \(I_{s}\), remains fixed throughout the training (which coresponds to a compressed model in network pruning). That is for any iterations \(t_{i}\) and \(t_{j}\), \(I_{s}^{t_{i}}=I_{s}^{t_{j}}\). Let us note in this work we are not concerned about the model size, unlike in network pruning literature. That is as it is given in Sec. 3 we do not remove the parameters, per se, but we freeze them. That is, \(p\) weights are frozen and the remaining weights are updated during the fine-tuning procedure. **Parameter selection.** We now assume gradient redundancy. In one-shot pruning, the model is pruned prior to the retraining and then a fixed set of parameters is fine-tuned. Nevertheless, our task is not concerned with decreasing the size of the model, and hence removing weights may be unnecessarily restrictive. In our case, we allow each of the weights to be updated at every iteration, however only some of weights will be updated at a given iteration. That is for two iterations \(t_{i}\) and \(t_{j}\) generally, \(I_{t_{i}}\neq I_{t_{j}}\) but \(I_{t_{i}}\subset I_{t}\) and \(I_{t_{j}}\subset I_{t}\). Notice that parameter freezing and variable parameter selection are two opposing modes. In the first mode, we allow no flexibility to the model and fix the parameter set at the beginning of the training. In the second mode, we allow for maximum flexibility as no parameter is dis ``` 0: Tensor \(\nabla\) that contains the gradients evaluated on each data sample in a mini-batch \(S\), pruning rate \(C\) (a constant) that determines the compression rate of the resulting average gradient matrix (average across data samples), norm clipping hyperparameters \(\gamma\), criterium \(\leftarrow\{max,rand\}\). 0: Sparse and differentially private average gradient matrix 1:functionSelect-indices(\(C\), criterium, weights) 2:\(I\leftarrow\) indices of weights 3:if Random then 4:\(I_{ns}\gets p\cdot len(I)\) indices of \(I\), selected uniformly at random 5:else 6:if Max then 7:\(I_{as}\leftarrow\) argsort(weights) 8:\(I_{ns}\leftarrow\) bottom \(p\cdot len(I)\) indices of \(I_{as}\) 9:endif 10:endif 11:\(I_{s}\gets I\smallsetminus I_{ns}\)return\(I_{ns}\) 12:endfunction 13: 14:functionDP-SGD(\(\nabla\), \(I_{ns}\), \(\gamma\), \(\sigma\)) 15: We compute the average gradient matrix: \(\mathbf{g}=\frac{1}{B}\sum_{k=1}^{S}\nabla[:,s]\), where \(b\in\mathcal{B}\). 16: We ensure \(\nabla^{2}[I_{s}]\leq\gamma\) by clipping the squared norm by \(\gamma\). 17: We privatize the gradients in the selected index set, \(\nabla\leftarrow\nabla[I_{s}]+\mathbf{n}\), where \(\mathbf{n}\sim\mathcal{N}(0,\sigma^{2}C^{2}I)\). return\(I_{ns},I_{s}\) 18:endfunction 19: 20:functionDP-Sparse-SGD(\(\nabla,C,\sigma,\gamma\), criterium, \(\mathcal{B}\), weights) 21:if freezing then 22:\(I_{ns}\leftarrow\) Select-indices 23:endif 24:for batch \(\mathcal{B}\)do 25:if selection then 26:\(I_{ns}\leftarrow\) Select-indices 27:endif 28:\(I\leftarrow\nabla[I_{ns}]=0\) 29:\(\nabla_{DP-SSGD}\leftarrow\) DP-SGD 30:endforreturn\(\nabla_{DP-SSGD}\) 31:endfunction ``` **Algorithm 1**DP-SSGD ## 4 Related work Recently, there has been a flurry of efforts on improving the performance of DP-SGD in training large-scale Figure 1: DP-SSGD algorithm. The algorithms consists of two parts, indices selection based on criterium and privatized gradient update. In case of freezing mode, indices selection is made only once before the training. In case of selection mode, indices are selected at every iteration. Notice we do not use any gradient information to select the indices, thus preserving privacy budget. neural network models. These efforts are made from a wide range of angles, as described next. For instance, [10] developed a sign-based DP-SGD approach called DP-SignSGD for more efficient and robust training. [11] replaced the ReLU activations with the tempered sigmoid activation to reduce the bias caused by gradient clipping in DP-SGD and improved its performance. Furthermore, [12] suggested modifying the loss function to promote a fast convergence in DP-SGD. [2] developed a paradigm for neural network architecture search with differential privacy constraints, while [14] a gradient hard thresholding framework that provides good utility guarantees. [8] proposed a grouped gradient clipping mechanism to modulate the gradient weights. [6] suggested a simple architectural modification termed ScaleNorm by which an additional normalization layer is added to further improve the performance of DP-SGD. The transfer learning idea we use in our work also has been a popular way to save the privacy budget in DP classification. For instance, [13] suggested transferring features learned from public data to classify private data with a minimal privacy cost. [9] developed an architecture which consists of an encoder and a joint classifier, where these are pre-trained with public data and then fine-tuned with private data. When fine-tuning these models, [9] also used the idea of neural network pruning to sparsify the gradients to update using DP-SGD. Our method is more general than that in [9] in that we sparsify the gradients given any architecture, while [9] focuses on the particular architecture they introduced and specific fine-tuning techniques for the architecture. Many attempts which take advantage of public data have improved the baseline performance. A recent work improved the accuracy of a privately trained classifier (ResNet-20) for CIFAR10 from \(37\%\) to \(60\%\) accuracy at \(\epsilon=2\)[16]. Another work improved the accuracy of a privately trained classifier (ResNet-18) for ImageNet from \(6\%\) to \(48\%\) accuracy at \(\epsilon=10\)[7]. However, there is still a huge room to improve further, given that the non-privately trained classifiers of the same architecture for each of these datasets reach \(90\%,75\%\), respectively. Existing works for reducing the dimension of gradients in DP-SGD also use public data for estimating the subspaces with which the dimension of the gradients are reduced [5, 18, 16, 17]. [19] suggested random selection of gradients to reduce the dimensionality of the gradients to privatize in DP-SGD. Unlike these works, we also reduce the dimension of the gradients by selecting the gradients on the magnitude of each weight or weight, inspired by neural network pruning. Besides, [19] proposed to freeze the parameters progressively. We introduce two different (and complementary) settings where the fixed set of parameters is frozen, and where no parameters are frozen. ## 5 Experiments We conduct experiments on two datasets, MNIST and CIFAR-10. Following [16], MNIST is trained on a small convolutional neural network with two convolutional and one fully-connected layer, CIFAR-10 is trained on Resnet-20. We replace all batch normalization layers with group normalization as group normalization averages only within a sample, not across samples (like batch normalization) which prevents proper privacy analysis. The networks are first pre-trained with public datasets. In case the number of classes of the pre-trained dataset is different, the last layer is removed and randomly initialized. Then, the networks are trained on a private dataset at three privacy levels, \(\epsilon=2,5\) and \(8\). The smaller number indicates higher levels of privacy and \(\infty\) stands for non-private training. The parameter details are given in the Appendix. ### DP-SSGD pruning comparison In the DP-SSGD pruning comparison study we compare two modes, parameter freezing and parameter selection. The former decreases the size of the model prior to the training with private data with the pruning ration \(p\), and the latter maintains the original size and varies a subset of updated weights over the course of the training such that at every iteration \(p\) gradients are discarded. In both modes, random and maximum magnitude criteria are used. Then each of the four settings is tested on three levels of private training to test the behavior of the proposed method on different privacy levels, strong, medium and weak. Moreover, we vary the pruning level \(p\) from 0 (no pruning) to 0.9. Every set-up is tested five times and we report the average across them. For CIFAR-10, we treat CIFAR-100 as public data and pre-train Resnet-20 on CIFAR-100 (accuracy 6.8% on CIFAR-10). For MNIST, we pre-trained the small convolutional network with a \(0.05\%\) subset of MNIST (96.1% on MNIST), which we treat as public data. The study on the interplay between public and private data is given in Figure 2 describes the summary of the results. The findings are absorbing. For small \(\epsilon\) increasing the pruning rate actually improves the model performance. There is a positive correlation between the pruning rate and the test accuracy. This is the case both for parameter freezing and variable selection. That is, the network learns more with fewer gradients updated in the presence of high levels of noise (further confirming the claim that the signal-to-noise is increased as the pruning increases.). This is in contrast to the training with lower levels of privacy where pruning the gradients hurts the accuracy. The medium level of privacy (middle column in Fig. 2) is the case in-between and indeed shows ambiguous results. Pruning may be beneficial up to certain degree after which point, the test accuracy decreases. Further hyperparameter tuning may be beneficial to determine optimal pruning ratio for a given privacy setting. The relationships between pruning and privacy level are more pronounced for larger Resnet architectures than for smaller convolutional networks. As a result, larger networks may benefit from the DP-SGD training where the gradients are pruned. But when trained in non-private setting, pruning gradients is likely to hurt its performance. Intuitively, using all the weights increases the norm of the parameter matrix, which triggers the clipping of weights. On the one hand, clipping affects the larger weights more than the smaller ones, thus decreasing the values of the gradients which make the most difference. On the other hand, smaller weights impact learning negatively in twofold ways. As given by the pruning literature, they are less relevant for model learning, and secondly, in a private setting, they cause the larger, more relevant weights to lose their information by decreasing their gradient value. Finally, what may be seen as surprising is that magnitude pruning performs similarly to random pruning, which may mark another difference between pruning the private and non-private training. In non-private setting, magnitude pruning is often proved effective as a network compression mechanism. ### Benchmark comparison The numerical results are summarized in Table 1. The results are presented for three datasets, CIFAR, MNIST and Imagenet. In the proposed method, DP-SSGD, we present two types of results, parameter freezing and variable parameter selection, along with DP-SGD and GEP [16], which also studies gradient redundancy and produces low-dimensional gradient embedding. The numbers come from the original paper. The results are consistent with the ablation study. Parameter freezing performs better for higher levels of privacy (and smaller levels of epsilon), and variable parameter selection gains an edge when the training gets closer to the non-private setting. In the parameter freezing setting, we optimize over a fixed, smaller set of parameters which, it can be hypothesized, increases their signal-to-noise over the course of the training. On the other hand, the larger parameter space in the case of variable selection may result in the noise dominating the learned signal. Figure 2: The effect of pruning rate on the accuracy of the differentially private training for a fixed epsilon. The plots on the top depicts Resnet training on Cifar-10, at the bottom, small convolutional network trained on MNIST. In the figure legend, random freezing means randomly selected parameter freezing, max freezing means the parameters whose magnitude is large are frozen. Similarly, random variable means parameter selection uniformly at random during training; and max variable means parameter selection based on the magnitude during training. ### Which public data to use? So far, we showed the results with a fixed public dataset. We use public data to pre-train the model before the private training starts, and also to select which parameters to update in the parameter selection mode based on the magnitude. So, the proximity between the public and private dataset pairs plays an important role in the success of our algorithm. An intuitive reasoning is that if the public data is more similar to private data, one needs a less number of fine-tuning steps with differential privacy to achieve the same accuracy. We test this reasoning in our next experiment. For differentially private CIFAR-10 classifier, we tested CIFAR-100, SVHN, and 5% of CIFAR10 data as public data. The DP-trained classifiers' accuracies are summarized in Table 2. For differentially private MNIST classifier, we tested SVHN and 5% of MNIST data as public data. The DP-trained classifiers' accuracies are summarized in Table 3. From these experiments, we conclude that for simple datasets like MNIST, using a small portion of the private data as public data provides a good initialization before the private training. However, for more complex data like CIFAR10, using the small portion of the same dataset does not provide good initialization. Rather, it is encouraged to look for datasets that are more complex than the private data as public data. ## 6 Conclusion In this paper, we conclude that, as far as the training of highly parametrized networks is concerned, differentially private training with limited privacy budget curbs the possibility to train all the parameters at once in the same way as the non-private training. Furthermore, this work shows the positive relationship between decreasing the updated parameter space and training performance. Given varying privacy budget, disparate modes of sparsifications may be preferred. Finally, random parameter selection proves to be a remarkable way of sparsifying network for differentially private training. \begin{table} \begin{tabular}{c c c c c} \hline \hline CIFAR-10 & \(\epsilon\) & Rand (param freezing) & Rand (param selection) & GEP & DP-SGD \\ \hline & 2 & **72.11** & 70.11 & 59.7 & 68.5 \\ & 5 & **81.09** & 79.99 & 70.1 & 79.8 \\ & 8 & 81.75 & **81.9** & 74.9 & 81.3 \\ \hline MNIST & \(\epsilon\) & Rand (param freezing) & Rand (param selection) & GEP & DP-SGD \\ \hline & 2 & **97.02** & 96.96 & 96.3 & 97.5 \\ & 5 & 98.09 & **98.18** & 97.9 & 98.0 \\ & 8 & 98.17 & 98.26 & **98.4** & 98.05 \\ \hline \hline \end{tabular} \end{table} Table 1: Test accuracy for two datasets, CIFAR-10 and MNIST trained with differential privacy constraints. For DP-SSGD, we present the results at three privacy levels \(\epsilon=2,5,8\). For DP-SSGD, we present the performance of random pruning. DP-SGD numbers take into account pre-training on the public model and are obtained via DP training without pruning \begin{table} \begin{tabular}{c c c c} \hline \hline \(\epsilon\) & CIFAR100 & SVHN & CIFAR10 (\(5\%\)) \\ \hline 2 & 72.11 & 11.87 & 54.35 \\ 5 & 81.09 & 18.56 & 53.9 \\ 8 & 81.9 & - & 62.13 \\ \hline \hline \end{tabular} \end{table} Table 2: For training a classifier for CIFAR-10, we tested three different public datasets. CIFAR100, which is similar to CIFAR-10, SVHN, which is quite different from SVHN, and 5% of CIFAR-10, which is the same as the private dataset while the quantity is not sufficient enough to provide a good classification performance. These numbers are from varying pruning rates and sparsification modes. \begin{table} \begin{tabular}{c c c c} \hline \hline \(\epsilon\) & SVHN & MNIST (\(5\%\)) \\ \hline 2 & 95.14 & 97.02 \\ 5 & 96.47 & 98.18 \\ 8 & 96.84 & 98.26 \\ \hline \hline \end{tabular} \end{table} Table 3: For training a classsifier for MNIST, we tested two different public datasets. SVHN, which is more complex than MNIST, and 5% of MNIST. Unlike the CIFAR-10 data, for MNIST, the pre-trained classifier with only 5% of MNIST data provides a good initialization for private training. These numbers are from varying pruning rates and sparsification modes.
2304.03864
SGDP: A Stream-Graph Neural Network Based Data Prefetcher
Data prefetching is important for storage system optimization and access performance improvement. Traditional prefetchers work well for mining access patterns of sequential logical block address (LBA) but cannot handle complex non-sequential patterns that commonly exist in real-world applications. The state-of-the-art (SOTA) learning-based prefetchers cover more LBA accesses. However, they do not adequately consider the spatial interdependencies between LBA deltas, which leads to limited performance and robustness. This paper proposes a novel Stream-Graph neural network-based Data Prefetcher (SGDP). Specifically, SGDP models LBA delta streams using a weighted directed graph structure to represent interactive relations among LBA deltas and further extracts hybrid features by graph neural networks for data prefetching. We conduct extensive experiments on eight real-world datasets. Empirical results verify that SGDP outperforms the SOTA methods in terms of the hit ratio by 6.21%, the effective prefetching ratio by 7.00%, and speeds up inference time by 3.13X on average. Besides, we generalize SGDP to different variants by different stream constructions, further expanding its application scenarios and demonstrating its robustness. SGDP offers a novel data prefetching solution and has been verified in commercial hybrid storage systems in the experimental phase. Our codes and appendix are available at https://github.com/yyysjz1997/SGDP/.
Yiyuan Yang, Rongshang Li, Qiquan Shi, Xijun Li, Gang Hu, Xing Li, Mingxuan Yuan
2023-04-07T23:25:48Z
http://arxiv.org/abs/2304.03864v2
# SGDP: A Stream-Graph Neural Network Based Data Prefetcher ###### Abstract Data prefetching is important for storage system optimization and access performance improvement. Traditional prefetchers work well for mining access patterns of sequential logical block address (LBA) but cannot handle complex non-sequential patterns that commonly exist in real-world applications. The state-of-the-art (SOTA) learning-based prefetchers cover more LBA accesses. However, they do not adequately consider the spatial interdependencies between LBA deltas, which leads to limited performance and robustness. This paper proposes a novel Stream-Graph neural network-based Data Prefetcher (SGDP). Specifically, SGDP models LBA delta streams using a weighted directed graph structure to represent interactive relations among LBA deltas and further extracts hybrid features by graph neural networks for data prefetching. We conduct extensive experiments on eight real-world datasets. Empirical results verify that SGDP outperforms the SOTA methods in terms of the hit ratio by 6.21%, the effective prefetching ratio by 7.00%, and speeds up inference time by 3.13\(\times\) on average. Besides, we generalize SGDP to different variants by different stream constructions, further expanding its application scenarios and demonstrating its robustness. SGDP offers a novel data prefetching solution and has been verified in commercial hybrid storage systems in the experimental phase. Our codes and appendix are available at [https://github.com/yyysjz12997/SGDP/](https://github.com/yyysjz12997/SGDP/). data prefetching, graph neural networks, logical block address, data mining ## I Introduction In the big data era, the demand for high-performance storage systems is increasing rapidly. The Input/Output (I/O) speed gap between different storage devices in a hybrid storage system might cause high access latency [16]. To fill this gap, the cache is designed to temporarily keep data that are likely to be accessed in the future. The performance of cache, commonly represented by **hit ratio**, has a direct impact on the performance of the whole storage system. To improve the hit ratio, data prefetching is introduced as an essential technique in the cache. Prefetchers reduce access latency by fetching data from their original storage in slower memory to cache before they are needed [54]. Common block-level cache prefetchers take in logical block address (LBA) access sequences as input (i.e., some integer numbers). Prefetchers predict the LBA of the block that might be accessed in a short time and decide whether to pre-load it or not. There are two major challenges in the design of effective prefetchers. First, the LBA access sequences in real-world applications have complex patterns due to concurrent and random accesses from different users or applications, which are common in modern large-scale storage systems [22, 51]. Second, effective prefetchers need to be accurate. Inaccurate prefetchers waste both I/O bandwidth and cache space [19]. Therefore, designing effective prefetchers is vital for storage systems. Traditional prefetchers prefetch the data by matching LBA access sequences to specific predefined rules. However, they can hardly adapt to complex real-world scenarios as their predefined rules are limited to specific simple patterns such as sequential reading [18]. To learn complex patterns, several learning-based methods [1, 3, 4, 7] are applied. Recently, long short-term memory (LSTM) based methods like DeepPrefetcher [20] and Delta-LSTM [5] have shown promising results. They model the **LBA delta** (i.e., the difference between successive access requests), which covers more LBA accesses. However, due to concurrent accesses, the chronological order of LBA deltas within a short time period is likely to be disrupted. DeepPrefetcher and Delta-LSTM disregard the internal temporal correlation and result in limited performance. Graph structures can effectively use nodes and edges to represent LBA (delta) and access sequence, and can mine intrinsic access patterns beyond chronological order in hybrid storage systems like relational databases. Therefore, to improve the performance of prefetching especially in applications with complex patterns, this work models the relations among LBA deltas using graph neural network, and proposes a novel method called Stream-Graph Neural Network-Based Data Prefetcher (**SGDP**), as shown in **Figure**1. Specifically, we encode LBA deltas and split them into shorter streams. Then we build weighted directed graphs based on LBA delta streams and extract relations of sequential connection and temporal accesses of LBA deltas from each stream, which are represented as sequential connect matrices and full-connect matrices, respectively. By fusing those two matrices, we get hybrid matrices that contain the relations of LBA deltas. Finally, the hybrid matrix, along with embedding LBA deltas of each stream is fed into a gated graph neural network to learn access patterns for prefetching. Extensive experiments on eight real-world datasets show that SGDP outperforms the SOTA prefetchers in terms of performance and efficiency. The contributions of this work are summarized as follows: 1. SGDP can accurately learn complex access patterns by capturing the relations of LBA deltas in each stream. The relations are represented by sequential connect matrices and full-connect matrices using graph structures. 2. To the best of our knowledge, SGDP is the first work that utilizes the stream-graph structure of the LBA delta in the data prefetching problem. Using gated graph neural networks and attention mechanisms, we extract and aggregate sequential and global information for better prefetching. 3. As a novel solution in the hybrid storage system, SGDP can be generalized to multiple variants by different stream construction methods, which further enhances its robustness and expands its application to various real-world scenarios. 4. SGDP outperforms SOTA prefetchers by 6.21% on hit ratio, 7.00% on effective prefetching ratio, and speeds up inference time by 3.13\(\times\) on average. It has been verified in commercial hybrid storage systems in the experimental phase and will be deployed in the future product series. ## II Related Work **Traditional Data Prefetcher** The most commonly used prefetcher is the Stride prefetcher [27] which uses a reference prediction table to store the last few accessed LBAs and the stride to obtain the required LBA. Although it can capture a constant stride in sequential access patterns, it can hardly detect variable strides in irregular access patterns. Temporal prefetchers learn irregular access patterns by memorizing pairs of correlated LBAs [34, 39, 8, 40]. However, due to inconsistent correlation address pairs, these traditional methods cannot achieve good performance in practice. **Learning-based Data Prefetcher** Prefetching needs to be accurate, as a small error in the numerical value of a prefetched LBA leads to useless prefetch and a waste of cache space and I/O bandwidth. Even though prefetching can be treated as a prediction problem, regression-based time-series prediction models like ARIMA are not widely considered by researchers. Classification-based methods seem more favoured because they can cover more LBA accesses, but not practical as it is hard to cover all LBAs. For example, in Microsoft Research Cambridge traces [2], the top-1000 most frequently occurring **LBAs** cover only 2.8% of all the LBA accesses, whereas the top-1000 most frequently occurring **LBA deltas** cover 91.7% of all LBA accesses [5]. To learn more complex access patterns, many deep learning approaches are proposed and consider the LBA delta as input directly [19]. Deep-Prefetcher [20] transforms the LBA sequence into LBA deltas, then employs the word2vec model and LSTM architecture to capture the hidden feature in the input sequence. However, it is inefficient on large-scale trace datasets. Delta-LSTM is Fig. 1: The workflow of the SGDP framework. In Step 1, we compress the search space and reduce the learning complexity. In Step 2, we compute the hybrid connection matrix \(\mathbf{M}_{h}\) with sequential and global information and embed the LBA delta stream into a matrix \(\mathbf{S}_{\Delta}\). In Step 3, using gated graph neural networks to update the latent node vectors. Each stream is represented as the combination of the local preference \(\mathbf{v}_{l}\) and global interaction \(\mathbf{v}_{g}\) by an attention network. In Step 4, we predict the candidate with the highest score and decode it to get the next accessed LBA for prefetching. This framework corresponds to the four steps of **Algorithm 1**. proposed [5] and addresses the large and sparse LBA space by co-learning top-\(K\) LBA delta and I/O size features. Within top-\(K\) (e.g., \(K=1000\)) classes, the searching space is restricted, which alleviates the class explosion problem. However, both of them do not consider the relations of LBA deltas to capture the more complex patterns (e.g., the continuous LBA accesses across many pages), which results in limited performance. **Prefetching with Graph-based Structure** Complex patterns in LBA access streams can be constructed by graphs [43, 53]. Nexus uses metadata relationship graphs to assist prefetching decision-making [56]. Ainsworth et al. design a prefetcher for breadth-first searches on graphs [55]. These methods transform a sequence of observed LBAs into a directed graph, in which a node is utilized to represent a block access event to model block access patterns. However, LBA accesses are quite sparse, which results in large graphs in these LBA sequence-based methods and makes these prefetchers quite ineffective in practice. ## III Preliminaries Consider an LBA access sequence with length \(n\): \[\langle lba_{i}\rangle_{i=1}^{n}=\langle lba_{1},lba_{2},\ldots,lba_{n}\rangle, \tag{1}\] in which \(lba_{i}\in N\) represents the address number of the \(i\)-th accessed blocks. The data prefetching problem can be regarded as given \(\langle lba_{i}\rangle_{i=1}^{n}\), predict \(lba_{n+1}\). Following the previous learning-based prefetchers, we compute LBA deltas (\(ld\)): \[ld_{i}=lba_{i+1}-lba_{i}, \tag{2}\] \[\langle ld_{i}\rangle_{i=1}^{n-1}=\langle ld_{1},ld_{2},\ldots,ld_{n-1}\rangle. \tag{3}\] In order to get the prediction of the next LBA, \(\widehat{lba}_{n+1}\), we predict the delta \(\widehat{ld}_{n}\). Note that the variables with the \(\widehat{\ }\) symbol denotes the predicted values. In short, the data prefetching problem is formulated as follows: \[\widehat{lba}_{n+1}=lba_{n}+\widehat{ld}_{n}. \tag{4}\] To restrict the model size, the number of classes of LBA deltas that needs to be predicted is capped to a fixed number of \(K+1\). Here \(K\) is acquired by top-\(K\) most frequently occurring LBA delta in \(\langle ld_{i}\rangle_{i=1}^{l-1}\), and the extra class is for the other infrequent LBA deltas. The prefetcher treats this extra class as no-prefetch because infrequent LBA delta is hard to predict. We redefine these \(K+1\) classes as \(LD=\{ld_{c_{0}},ld_{c_{1}},\ldots,ld_{c_{K+1}}\}\), \(ld_{c_{0}}\) representing the no-prefetch class and \(\{ld_{c_{1}},\ldots,ld_{c_{K+1}}\}\) representing the top-\(K\) ones. The model predicts the \(ld_{c_{i}}\) of the next LBA delta, and prefetches it when the predicted class is in the top-\(K\) and does not prefetch if the class is \(ld_{c_{0}}\). Using the LBA delta and Top-\(K\) mechanism can effectively reduce the sparse problem and the search space of the model. ## IV Methodology ### _LBA Delta Streams_ It would yield expensive costs if building the directed graph of the LBA delta sequence generated by the whole LBA sequence (length \(\geq 1\times 10^{7}\)). To alleviate this problem, we use the concept of data access **stream**. We split the whole LBA delta sequence into shorter streams which represent the temporal access patterns. Specifically, we consider LBA accesses with close access times to be in the same stream. Whenever the time interval between two LBA accesses is longer than a preset time limit \(T\) (e.g. \(T=\) 0.1ms), the LBA sequence will be split to generate a new stream. We then split the LBA delta sequence correspondingly and use a sliding window inside each stream to generate equal-length LBA delta streams. A split LBA delta stream \(\mathbf{s}_{\Delta}\) can be represented by a vector \(\mathbf{s}_{\Delta}=[ld_{s,1},ld_{s,2},...,ld_{s,n}]\) in the chronological order, where \(ld_{s,i}\) denotes the \(i\)-th LBA delta in the stream \(\mathbf{s}_{\Delta}\). The LBA delta stream is not only suitable for building directed graphs but also implies the temporal locality of LBA accesses. ### _LBA Delta Based Graph Structure_ As discussed in **Section** II, LBA-based graph structure is ineffective for data prefetching in practice. To solve this problem, we propose a high-order graph based on the LBA delta. Here we present a toy example in **Figure** 2 to show that LBA deltas can also be represented by a directed graph. Consider three users sending concurrent sequential read requests. The concurrent requests are combined into one LBA sequence before being sent to the storage system. Following the LBA delta computation progress in **Section** IV-A, we can simplify the original LBA sequence that has 12 different LBAs and represent it with an LBA delta sequence with only 5 different nodes. We can build a directed graph based on the LBA delta sequence by using LBA deltas as a node and linking all the LBA deltas with their successor. In contrast to previous works on extracting useful features from access patterns between nearby accessed LBAs only, we observed if an LBA request sequence is divided into several Fig. 2: Example of LBA delta and graph. streams, different streams are possible to be accessed by a similar pattern. Non-sequential features can be extracted from the observed access patterns by monitoring the change (or difference) between successive LBA requests. This is achieved by learning the hybrid connection matrix (which contains adjacent and interactive relations) along with the embedded LBA deltas. Also, the number of the graph nodes is constant, that is \(K+1\). ### _Weighted Directed Stream-based Graph_ Without loss of generality, each LBA delta stream \(\mathbf{s}_{\Delta}\) can be modeled as a directed graph \(\mathcal{G}_{\mathbf{s}_{\Delta}}=(\mathcal{V}_{\mathbf{s}_{\Delta}},\mathcal{ E}_{\mathbf{s}_{\Delta}})\). Each node in the directed graph \(\mathcal{G}_{\mathbf{s}_{\Delta}}\) expresses one of the classes of LBA deltas \(ld_{s,a}\in LD\). We build the graph with two kinds of edges, as shown in **Figure**3. The first one \((ld_{s,a},ld_{s,a+1})\in\mathcal{E}_{\mathbf{s}_{\Delta}}\) represents the order in an LBA delta stream \(\mathbf{s}_{\Delta}\) by linking \(ld_{s,a}\) to its successor \(ld_{s,a+1}\). The second one \((ld_{s,a},ld_{s,b})\in\mathcal{E}_{\mathbf{s}_{\Delta}}\) is built by fundy connecting all nodes in the stream to capture the global information of each LBA delta stream. We denote the set of sequential edges as \(\mathcal{E}_{\mathbf{s}_{\Delta}}^{S}\) and full-connected edges as \(\mathcal{E}_{\mathbf{s}_{\Delta}}^{F}\). We compute the adjacency matrices \(\mathbf{M}_{S}\) and \(\mathbf{M}_{F}\) of \(\mathcal{E}_{\mathbf{s}_{\Delta}}^{S}\) and \(\mathcal{E}_{\mathbf{s}_{\Delta}}^{F}\) separately. As every LBA delta node might appear more than once in a stream, we normalize the weights on each edge in \(\mathcal{E}_{\mathbf{s}_{\Delta}}\). The weight of an edge is set to be its occurrence counts divided by the out-degree of its start node. The higher the weight, the stronger the correlation between the corresponding two nodes. The incoming parts of \(\mathbf{M}_{S}\) and \(\mathbf{M}_{F}\) are computed as Eq. (5) and (6), \[\mathbf{M}_{S}^{in}=\sum_{i=1}^{K+1}\frac{\mathbf{1}((ld_{s,a},ld_{s,a+1}) \mathcal{E}_{\mathbf{s}_{\Delta}}^{S})}{\mathbf{1}((ld_{s,i},ld_{s,a+1}) \mathcal{E}_{\mathbf{s}_{\Delta}}^{S})},\ (a\leq n-1), \tag{5}\] \[\mathbf{M}_{F}^{in}=\sum_{i=1}^{K+1}\frac{\mathbf{1}((ld_{s,a},ld_{s,b}) \mathcal{E}_{\mathbf{s}_{\Delta}}^{F})}{\mathbf{1}((ld_{s,i},ld_{s,b}) \mathcal{E}_{\mathbf{s}_{\Delta}}^{F})\times|b-a|},\ (a,b\leq n), \tag{6}\] where \(\mathbf{1}(\cdot)\) is indicator function and the outgoing parts \(\mathbf{M}_{F}^{out}\) and \(\mathbf{M}_{F}^{out}\) is computed in the same manner. Then, we expand \(\mathbf{M}_{S}\) and \(\mathbf{M}_{F}\) to the same dimension, \(\mathbf{M}_{S},\mathbf{M}_{F}\in\mathbb{R}^{(K+1)\times 2*(K+1)}\). To facilitate the fuse of information in \(\mathbf{M}_{S}\) and \(\mathbf{M}_{F}\), we conduct a weighted sum of them named as hybrid connection matrix \(\mathbf{M}_{h}\). Then, the preprocessed LBA delta stream is embedded with the hybrid connection matrix \(\mathbf{M}_{h}\) and fed into a graph neural network. Specifically, we obtain each node vector \(\overrightarrow{ld}_{s,i}\in\mathbb{R}^{d}\) that indicates the \(d\)-dimensional latent vector of the original \(ld_{s,i}\in LD\). Each LBA delta stream \(\mathbf{s}_{\Delta}\) can be presented as an embedding matrix \(\mathbf{S}_{\Delta}\) by DeepWalk [58] where each node vector \(\overrightarrow{ld}_{s,i}\in\mathbb{R}^{d}\) denotes a \(d\)-dimensional real-valued latent vector. Note that SGDP can support LBA streams of various lengths and various graph model constructing strategies. ### _Latent Node Vectors Updating_ We apply the vanilla graph neural network (GNN) proposed by [49] and gated-recurrent-units-based GNN (gated GNN) [50] to obtain latent features of nodes. Specifically, for each LBA delta stream vector \(\mathbf{S}_{\Delta}=[\overrightarrow{ld}_{1}^{t-1},\overrightarrow{ld}_{2}^ {t-1},...,\overrightarrow{ld}_{n}^{t-1}]\) in the graph \(\mathcal{G}_{\mathbf{s}_{\Delta}}\), the update functions can be formalized as, \[\mathbf{a}^{t}=\mathbf{A}_{\mathbf{M}_{h}}^{t-1}(\mathbf{S}_{\Delta}{\mathbf{ W_{a}}}^{t}+{\mathbf{b_{a}}}^{t}), \tag{7}\] \[\mathbf{z}^{t}=\sigma({\mathbf{W_{z}}}^{t}\mathbf{a}^{t}+{\mathbf{U_{z}}}^{t }\overrightarrow{ld}_{n}^{t-1}), \tag{8}\] \[\mathbf{r}^{t}=\sigma({\mathbf{W_{r}}}^{t}\mathbf{a}^{t}+{\mathbf{U_{r}}}^{t }\overrightarrow{ld}_{n}^{t-1}), \tag{9}\] \[\tilde{\mathbf{h}}^{t}=tanh({\mathbf{W_{h}}}^{t}\mathbf{a}^{t}+{\mathbf{U_{h}}} ^{t}(\mathbf{r}^{t}\odot\overrightarrow{ld}_{n}^{t-1}), \tag{10}\] \[\mathbf{h}^{t}=(1-\mathbf{z}^{t})\odot\overrightarrow{ld}_{n}^{t-1}+\mathbf{z} ^{t}\odot\tilde{\mathbf{h}}^{t}, \tag{11}\] where \(\mathbf{A}_{\mathbf{M}_{h}}^{t-1}\in\mathbb{R}^{1\times 2n}\) is two rows of blocks (outgoing and incoming) in \(\mathbf{M}_{h}\) corresponding to node \(ld_{n}^{t-1}\). \(\mathbf{a}^{t}\) extracts the contextual features of neighborhoods for node \(ld_{n}^{t-1}\) with weight matrix \({\mathbf{W_{a}}}^{t}\in\mathbb{R}^{d\times 2d}\) and bias vector \({\mathbf{b_{a}}}^{t}\in\mathbb{R}^{2d}\). Then, we take \(\mathbf{a}^{t}\) and previous LBA delta vector \(\overrightarrow{lb}_{n}^{t-1}\) as input and feed them into the gated GNN. The updated functions are shown in Eq. (8)\(\sim\)(11). \(\mathbf{z}^{t}\) and \(\mathbf{r}^{t}\) are the updates and the reset gate, and control which features to be reserved or discarded. \(\sigma(\cdot)\) represents the logistic sigmoid function and \(\odot\) denotes the element-wise multiplication operator. \({\mathbf{W_{z}}}^{t}\), \({\mathbf{W_{r}}}^{t}\), \({\mathbf{W_{h}}}^{t}\) and \({\mathbf{U_{z}}}^{t}\), \({\mathbf{U_{r}}}^{t}\), \({\mathbf{U_{h}}}^{t}\) are the weight matrices to be learned. The final state \(\mathbf{h}^{t}\) is the latent node vector, which is the sum of the candidate states and the previous hidden states. Note that the model will update all nodes until they converge. ### _Generating Stream Hybrid Embedding Vector_ The next accessed LBA is strongly correlated with the previous ones, and that relationship is inversely proportional to the interval between the two LBAs. Therefore, we apply a hybrid embedding vector to extract features, i.e., local embedding and global embedding. Firstly, the local embedding vector named \(\mathbf{v}_{l}^{t}\) is defined as the last accessed LBA delta \(\overrightarrow{ld}_{n}^{t-1}\), \[\mathbf{v}_{l}^{t}=\overrightarrow{ld}_{n}^{t-1}. \tag{12}\] Fig. 3: Example of two kinds of graphs. The global embedding vector \(\mathbf{v}_{g}^{t}\) aggregates all node vectors in the LBA delta stream \(\mathbf{S}_{\Delta}\). Specially, we use the soft-attention approach to more effectively represent the different levels of priority, as Eq. (13) and (14) show, \[\alpha_{i}^{t}=\mathbf{q}^{t}{}^{\top}\sigma(\mathbf{W_{1}}{}^{t}\widehat{ld}_{ n}^{t-1}+\mathbf{W_{2}}{}^{t}\widehat{ld}_{i}^{t-1}+\mathbf{b}_{g}^{t}), \tag{13}\] \[\mathbf{v}_{g}^{t}=\sum_{i=1}^{n}\alpha_{i}^{t}\overline{\widehat{ld}_{i}^{t-1}}, \tag{14}\] where \(\mathbf{W_{1}}{}^{t},\mathbf{W_{2}}{}^{t}\in\mathbb{R}^{d\times d}\) and \(\mathbf{q}^{t}\in\mathbb{R}^{d}\) are weight matrices, and \(\mathbf{b}_{g}^{t}\in\mathbb{R}^{d}\) is bias vector. Finally, the hybrid embedding vector \(\mathbf{v}_{h}^{t}\) combines the local embedding vector \(\mathbf{v}_{l}^{t}\) and the global embedding vector \(\mathbf{v}_{g}^{t}\) linearly, as the Eq. (15) shows, \[\mathbf{v}_{h}^{t}=\mathbf{W}_{\mathbf{f}}{}^{t}[\mathbf{v}_{l}^{t};\mathbf{v }_{g}^{t}]+\mathbf{b_{h}}{}^{t}, \tag{15}\] where \(\mathbf{W_{f}}{}^{t}\in\mathbb{R}^{d\times 2d}\) is weight matrix and \(\mathbf{b_{h}}{}^{t}\in\mathbb{R}^{d}\) is bias vector. The final hybrid embedding vector \(\mathbf{v}_{h}^{t}\) of the LBA delta stream \(\mathbf{S}_{\Delta}\) is in the \(d\) dimensions. ### _Forecasting and Prefetching_ After extracting the hybrid embedding vector \(\mathbf{v}_{h}^{t}\), we predict the score of each LBA delta candidate \(\widehat{\mathbf{z}}_{i}^{t}\) in stream \(\mathbf{s}_{\Delta}\) by multiplying \(\mathbf{v}_{h}^{t}\) and \(\widehat{ld}_{i}^{t-1}\) as \[\widehat{\mathbf{z}}_{i}^{t}=\mathbf{v}_{h}^{t}{}^{\top}\widehat{ld}_{i}^{t-1}. \tag{16}\] We take the candidate with the highest score as the predicted LBA delta. Besides, in order to train with labels, we need to compute the probability of each node \(\widehat{\mathbf{y}}^{t}\in\mathbb{R}^{K+1}\) in the next step using the softmax function, which is \[\widehat{\mathbf{y}}^{t}=\mathit{Softmax}(\widehat{\mathbf{z}}^{t}). \tag{17}\] The loss function is the cross-entropy of prediction \(\widehat{\mathbf{y}}^{t}\) and ground truth \(\mathbf{y}^{t}\) with regularization, as shown in Eq. (18). \[\mathcal{L}(\widehat{\mathbf{y}}^{t})=-\sum_{i=1}^{m}[\mathbf{y}_{i}^{t}log( \widehat{\mathbf{y}}_{i}^{t})+(1-\mathbf{y}_{i}^{t})log(1-\widehat{\mathbf{y }}_{i}^{t})]+\lambda\|\theta\|_{2}^{2}, \tag{18}\] where \(\lambda\) is \(l2\)-norm penalty factor, \(\theta\) is weight vectors. Finally, we decode the index of \(\max\widehat{\mathbf{z}}_{i}^{t}\) to \(\widehat{ld}_{s,n+1}\), predict the next accessed LBA by Eq. (4), and prefetch the corresponding block from storage into the cache. Overall, we summarize the proposed SGDP framework in **Algorithm 1**. ## V Experimental Settings ### _Datasets_ We use representative eight datasets in production servers from different applications, including six datasets from an open-source benchmark **MSRC** and two datasets from a real enterprise storage system **HW**: **MSRC**\({}^{*}\) (Microsoft Research Cambridge) [2]: It collects a 1-week LBA sequence of live enterprise servers at Microsoft. We use its five datasets from different application scenes named {**hm_1, mds_0, proj_0, prxy_0, src1_2**}. **Input:** An LBA sequence \(\langle lba_{i}\rangle_{i=1}^{l}=\langle lba_{1},lba_{2},\ldots,lba_{l}\rangle\), the top number of most frequent LBA delta \(K\), dimension of embedding vector of each LBA delta stream \(d\), cache size \(N\), maximum iteration \(Q\), stop criteria \(tol\). ``` 1:Step 1: LBA stream preprocessing 2:Compute delta of each adjacent LBA pair in \(\langle lba_{i}\rangle_{i=1}^{l}\) and get LBA delta \(\langle ld_{i}\rangle_{i=1}^{l-1}=\langle ld_{1},ld_{2},\ldots,ld_{n-1}\rangle\). 3:Encode \(ld\)s in all LBA streams by \(top(K)\) to \(LD\). 4:Generate LBA delta stream \(\mathbf{s}_{\Delta}\) by time limit and slide window. 5:Step 2: Embed LBA delta stream to a graph 6:Compute \(\mathbf{M}_{S}\) by Eq. (5) and \(\mathbf{M}_{F}\) by Eq. (6). 7:Expand \(\mathbf{M}_{S}\) and \(\mathbf{M}_{F}\) and conduct weighted sum to get \(\mathbf{M}_{h}\). 8:Conduct embedding of each \(\mathbf{s}_{\Delta}\in\mathbb{R}^{n}\) into \(\mathbf{S}_{\Delta}\in\mathbb{R}^{d\times n}\). 9:Step 3: Update hybrid embedding vector and training 10:Initialize the parameters in the gated GNN model. 11:for\(q=1,...,Q\)do 12:Compute the Eq.(7) \(\sim\) Eq.(18) to fit each stream with the input \(\mathbf{M}_{h}\) and \(\mathbf{S}_{\Delta}\). 13:Update the weight matrices list {\(\mathbf{W_{z}}\), \(\mathbf{W_{r}}\), \(\mathbf{W_{h}}\), \(\mathbf{U_{z}}\), \(\mathbf{U_{r}}\), \(\mathbf{U_{h}}\), \(\mathbf{W_{1}}\), \(\mathbf{W_{2}}\), \(\mathbf{W_{f}}\)} and vectors list {\(\mathbf{b_{g}}\), \(\mathbf{b_{h}}\)} by Adam with ground truth \(\mathbf{y}\). 14:Convergence checking: if \(\mathcal{L}(\widehat{\mathbf{y}})<tol\), break; otherwise, continue. 15:endfor 16:Step 4: Conduct forecasting and data prefetching 17:Conduct Eq.(16) and get \(\max\widehat{\mathbf{z}}\) with the updated model. 18:Decode it to \(\widehat{ld}_{n}\) and conduct Eq.(4) to get \(\widehat{lba}_{n+1}\). 19:Read the corresponding block and prefetch it into the cache or conduct no prefetching. 20:\(\widehat{lba}_{n+1}\), blocks \(\in\mathbb{R}^{N}\) in cache. ``` **Algorithm 1** The Workflow of **SGDP** Framework **HW**: It consists of three datasets collected from a real-world commercial hybrid storage system, which describes storage traffic characteristics on enterprise virtual desktop infrastructure and production servers. It intercepts the stream from an intra-enterprise storage system under different application scenarios and reads the storage system record logs directly. We named these three datasets as {**hw_1, hw_2, hw_3**}. **Table I provides the detail of the eight datasets from two data sources. Memory means the total amount of storage space that has been accessed in the trace. Sequential shows the percentage of sequential accesses in the trace.** ### _Compared Methods_ We compare SGDP with the following methods from three categories: traditional prefetchers, regression-based prefetchers, and learning-based prefetchers. **No_pre** means without any prefetching facilities and is used as a baseline to show the gain by other schemes. **Naive Prefetcher** treats the LBA stream as a whole sequence, i.e., \(\widehat{ld}_{n}=ld_{n-1}\), and directly uses Eq. (4) to predict LBA. **Stride Prefetcher**[6] simultaneously records 128 LBA access streams, and each of them tracks the last 3 LBA accesses. Each access is mapped to a stream based on hashing the most significant LBA. If the difference between the 3 LBA accesses matches, it will detect a stride and conduct a prediction. **ARIMA**[9] treats the problem as a time-series prediction problem and applies the ARIMA model built from \(t-\delta\) to \(t\) to forecast the next LBA. **Informer\({}^{\dagger}\)**[11] is the SOTA for time-series forecasting. Same as ARIMA, it takes the previous LBA delta sequence as input and predicts the following LBA. **DeepPrefetcher**[20] captures the LBA delta patterns by employing the word2vec model and LSTM architecture for prefetching. **Delta-LSTM\({}^{\ddagger}\)**[5] is another learning-based prefetcher, which uses an LSTM-based model to predict the LBA delta for prefetching. Besides, we set the sequences of LBA delta as the input for a fair comparison. There is a class explosion problem in DeepPrefetcher, which makes it unrealistic to train. To solve the problem, we restrict the top-\(K\) class with \(K=10000\). This \(K=10000\) value is to balance the efficiency and accuracy based on our preliminary study. For Delta-LSTM and SGDP, we set top-\(1000\) frequently occurring LBA deltas as input. ### _Evaluation Criteria_ **HR@N** (Hit Ratio) is the number of cache hits divided by the total number of memory requests over a given time interval. It is an important storage indicator given a fixed cache size \(N\). That is, \[\mathrm{HR}=\frac{\mathrm{Cache\ Hits}}{\mathrm{Cache\ Hits}+\mathrm{Cache\ Misses}}\times 100\%. \tag{19}\] **EPR@N** (Effective Prefetching Ratio) is the ratio of the number of correctly prefetched data to all executed prefetches given a fixed cache size \(N\), which is strongly related to the prefetcher's efficiency. That is, \[\mathrm{EPR}=\frac{\mathrm{Correct\ Prefetchings}}{\mathrm{All\ Prefetchings}} \times 100\%. \tag{20}\] Note that HR and EPR describe the prefetching results more precisely and feasible refer to Accuracy and Recall in DeepPrefetcher [20] and Delta-LSTM [5], respectively. We use HR and EPR in our work because they describe the prefetching results more precisely. Besides, there is a trade-off between HR and EPR in the subsection VI-B1 and some results are shown in **Figure**4. Besides, we feed the next step predicted LBA into the cache simulator based on the Least Recently Used (LRU) strategy for prefetching. LRU is a classical cache elimination algorithm. It selects the most recently unused LBA to retire. ### _Implementation Details_ We implemented SGDP for offline training and online testing by PyTorch [57]. All experiments are trained and tested on a computing server equipped with an Intel Xeon Platinum 8180M [email protected] and an NVIDIA Tesla V100 GPU. For a more fair and effective comparison, we normalize all LBA in increments of 8KB blocks and according to the I/O size of the 8KB block alignment and increment operations. We apply the 10-fold cross-validation method for training and testing, the same as SOTA methods. As for neural networks, all parameters are initialized with a Gaussian distribution with a means of 0 and a standard deviation of 0.1 with the latent vectors \(d\) equaling 200 for all 8 datasets. Moreover, we set the initial learning rate to 1.5\(\times 10^{-3}\) with decay by 95% after every 3 epochs, the batch size to 128 with 10 epochs, and the \(\mathit{l}\mathit{\varnothing}\)-norm penalty factor to 10\({}^{-5}\). Adam optimizer [12] with default parameter is applied for optimization. We set the stream split time interval \(T\) as 0.1ms for HW and 0.01ms for MSRC, and set the top number of most frequent LBA delta \(K\) as 1000 for SGDP. Note that since the preprocessed LBA stream is shorter, the training epoch can be smaller to prevent over-fitting, which is also useful to shorten the training time. ## VI Experimental Results ### _Results of Single-Step Prefetching_ We analyze the results of data prefetching conducted by SGDP and the compared methods on different datasets in the case of single-step Prefetching, as reported in **Table** II. The detailed analysis is presented in the following. **ARIMA and Informer** Time-series forecasting models (ARIMA and Informer) perform the worst, excepting the case of hw_2 trace where ARIMA achieves around 80% HR as this dataset has a very high degree of sequential access (95.1%). ARIMA and Informer take LBA delta inputs as scalar variables and can produce a correct prediction if the input sequences are steady. As there are frequent large fluctuations in complex non-sequential access patterns, ARIMA and Informer prompt incorrect LBA access. The worst results shown in almost all cases confirm our claims that regression-based approaches are not feasible for accurate and complex data prefetching. **Naive and Stride Prefetcher** Traditional prefetchers (Naive and Stride) have relatively stable performances in sequential access. However, for the random accesses, those traditional prefetchers encounter a big gap compared to SGDP. Moreover, Stride always achieves higher EPR while lower HR as it is more laziness and only prefetches when detecting an inside-page stride. As a result, it prefetches less and has higher accuracy for sequential access. In other words, although Stride has a high EPR, it prefetches less and gets quite low HR, which makes it impractical. Overall, the robustness performance of the Naive and Stride Prefetcher is poor, especially for completely random access. **Delta-LSTM, DeepPrefetcher and SGDP** Learning-based prefetchers (Delta-LSTM, DeepPrefetcher and SGDP) cover all highest HR and almost the highest EPR. SGDP has higher HR than DeepPrefetcher/Delta-LSTM in 19/24 out of all 24 cases, and 24/19 about EPR. Specifically, Delta-LSTM and DeepPrefetcher share a similar structure and show a similar effect. DeepPrefetcher has a larger LBA delta candidates pool which leads to more prefetching and lowers accuracy, reflected in lower average EPR (71.6% compared to 80.3%). On the contrary, Delta-LSTM prefetches more accurately but with fewer blocks, which leads to lower HR (70.8% compared to 73.5%). To be fair, as SGDP takes the top-1000 LBA delta as input (same as Delta-LSTM), the comparison to Delta-LSTM can prove that SGDP has better feature extraction ability. ### _Ablation study and SGDP Variants by Stream Construction_ #### Iv-B1 Retaining top-\(K\) delta value (Sgdp\({}_{l}\)) SGDP considers the top-1000 most frequently occurring LBA delta in the whole search space. Considering more LBA delta values further increases the model coverage, but also increases the search space and degrades the accuracy of the model. So to explore it quantitatively and prove the HR-EPR trade-off, we apply the top-10000 LBA delta for model building and name it SGDP\({}_{large}\), or SGDP\({}_{l}\) for brevity. The experiment of SGDP\({}_{l}\) confirms the trade-off of HR-EPR. As Table II shows, SGDP\({}_{l}\) achieves 1.5% slightly higher than SGDP in terms of HR while showing a large gap with 9.6% loss than SGDP in terms of EPR. Compared to DeepPrefetcher, which also uses top-10000 LBA delta as input, SGDP\({}_{l}\) maintains higher HR in 23 cases and higher EPR in 20 cases. Notice that for dataset hm_1, SGDP\({}_{l}\) gets a low EPR@1000 (24.4%). The reason is that with an extremely high HR@1000 (99.4%, almost all hit), SGDP\({}_{l}\) prefetches extra useless blocks without harm to HR, leading to an obvious decline of EPR. To further verify the effectiveness of SGDP and the HR-EPR trade-off, we conduct extra tests on dataset prxy_0 by testing Delta-LSTM, DeepPrefetcher, SGDP and SGDP\({}_{l}\) on 20 different cache sizes ({5, 10, 20, \(\cdots\),90 and 100, 200, \(\cdots\), 900, 1000}). As shown in **Figure**4, the top-10000 methods (SGDP\({}_{l}\) and DeepPrefetcher) show higher HR but lower EPR than their top-1000 counterparts (SGDP and Delta-LSTM). The two pairs of top-\(K\) comparisons confirm that SGDPs achieve better performance consistently than other methods. #### Vi-B2 Stream partition with page (Sgdp\({}_{p}\)) Considering the spatially localized relevance of LBA access patterns, we divide the entire search space by 64MB size page, record the LBA access streams on each page simultaneously, and perform parallel prediction in each page stream for prefetching the next block inside the page stream. We call it SGDP\({}_{p}\). SGDP\({}_{p}\) models LBA deltas, as 64MB page contains 8192 unique blocks, the total LBA delta candidate class of SGDP\({}_{p}\) is 16383 (\(\pm 8191\)) instead of top-\(K\) classes. SGDP\({}_{p}\) keeps the best HR results on half of all cases. Its average HR is slightly lower than SGDP and SGDP\({}_{l}\), but still higher than other methods. HR of SGDP\({}_{p}\) on hw\({}_{3}\) encounters a severe drop. The reason is that hw\({}_{3}\) is the shortest and has the second-largest storage capacity, which means the LBAs are much more sparse. SGDP\({}_{p}\) needs at least an LBA stream with length 2 to generate an LBA delta stream. But as hw\({}_{3}\) cross over \(1.4\times 10^{4}\) pages, the average length of inside-page-stream is 12.4, which means SGDP could not perform prefetching on 1/12 of data points. Nevertheless, SGDP\({}_{p}\) obtains the highest HR (79.9%) on all datasets except hw\({}_{3}\) on average. Therefore, it could be concluded that SGDP\({}_{p}\) performs well in real-world scenarios with sufficient data. ### _Multi-step Prefetching_ We further evaluate the performance of SGDP methods in multi-step prefetching based on rolling prediction. We feed the prediction of LBA back to the aforementioned learning-based prefetchers and get the rolling prediction for the next LBAs. The experiments are performed on cache size 100 with a rolling step from 2 to 10. The average results of HR@100 and EPR@100 are reported in **Table** III. Overall, SGDP\({}_{l}\) has the best HR@100 on all steps on average, and SGDP achieves the best EPR@100. SGDP\({}_{p}\) shows worse results than SGDP and SGDP\({}_{l}\). SGDP\({}_{p}\) gets the highest HR@100 (from 79.6% to 83.8%) on average in all steps on all the datasets except hw\({}_{3}\) as it is too sparse. The second best method is SGDP\({}_{l}\), of which HR@100s range from 78.9% to 83.0%. These results demonstrate that SGDP methods are able to keep their superiority and robustness in multi-step prefetching. ### _Offline Training and Online Testing Efficiency_ The offline training time in dataset hw\({}_{l}\) for SGDPs is 0.37 hours, and the training time for other learning-based methods is about 1.1 hours. The GPU utilization is 24%, the parameter number is 192,500, and the flop number is 48,570,779. For the online inference test, the GPU utilization is 10%, the model size is 1.47 MB, and the flop number is 1,884,055. Furthermore, to verify the practicality of SGDP compared to the other methods, we collect statistics of inference time as shown in **Table** VI. SGDPs process 469 to 670 LBA deltas per second, while Delta-LSTM and DeepPrefetcher can only process 91.2 and 197.7 on average. SGDP\({}_{l}\) speeds up inference time up to 3.13\(\times\) than DeepPrefetcher. Overall, SGDPs show much higher efficiency and practicality for real deployment applications. ## VII Conclusions To improve the performance of the data prefetcher in practice, this paper proposed SGDP, a novel stream-graph-based data prefetcher. SGDP takes each LBA delta stream as a weighted directed graph fusing both sequential and global features. By gated GNN and attention mechanism, SGDP extracts and aggregates the sequential and global information for better data prefetching. The experiment results from eight different real-world datasets demonstrate that SGDP outperforms SOTA methods and high speeds up inference time. The generalized SGDP variants can further adapt to extensive application scenarios. This novel data prefetcher has been verified in commercial hybrid storage systems in the experimental phase and will be deployed in the future product series.
2304.08925
Understand Data Preprocessing for Effective End-to-End Training of Deep Neural Networks
In this paper, we primarily focus on understanding the data preprocessing pipeline for DNN Training in the public cloud. First, we run experiments to test the performance implications of the two major data preprocessing methods using either raw data or record files. The preliminary results show that data preprocessing is a clear bottleneck, even with the most efficient software and hardware configuration enabled by NVIDIA DALI, a high-optimized data preprocessing library. Second, we identify the potential causes, exercise a variety of optimization methods, and present their pros and cons. We hope this work will shed light on the new co-design of ``data storage, loading pipeline'' and ``training framework'' and flexible resource configurations between them so that the resources can be fully exploited and performance can be maximized.
Ping Gong, Yuxin Ma, Cheng Li, Xiaosong Ma, Sam H. Noh
2023-04-18T11:57:38Z
http://arxiv.org/abs/2304.08925v1
# Understand Data Preprocessing for Effective End-to-End Training of Deep Neural Networks ###### Abstract. In this paper, we primarily focus on understanding the data preprocessing pipeline for DNN Training in the public cloud. First, we run experiments to test the performance implications of the two major data preprocessing methods using either raw data or record files. The preliminary results show that data preprocessing is a clear bottleneck, even with the most efficient software and hardware configuration enabled by NVIDIA DALI, a high-optimized data preprocessing library. Second, we identify the potential causes, exercise a variety of optimization methods, and present their pros and cons. We hope this work will shed light on the new co-design of "data storage, loading pipeline" and "training framework" and flexible resource configurations between them so that the resources can be fully exploited and performance can be maximized. + Footnote †: journal: Computer Vision and Pattern Recognition + Footnote †: journal: Computer Vision and Pattern Recognition + Footnote †: journal: Computer Vision and Pattern Recognition + Footnote †: journal: Computer Vision and Pattern Recognition + Footnote †: journal: Computer Vision and Pattern Recognition + Footnote †: journal: Computer Vision and Pattern Recognition + Footnote †: journal: Computer Vision and Pattern Recognition + Footnote †: journal: Computer Vision and Pattern Recognition + Footnote †: journal: Computer Vision and Pattern Recognition + Footnote †: journal: Computer Vision and Pattern Recognition + Footnote †: journal: Computer Vision and Pattern Recognition ## 1. Introduction One major contributor to the huge success of deep learning (DL) is the existence of diverse and large datasets, while another is the abundance of massive computing power, mostly from accelerators like GPUs. Popular DL frameworks, such as MXNet (Maswani et al., 2017), TensorFlow (Krizhevsky et al., 2014), and PyTorch (Krizhevsky et al., 2014), connect these two driving forces to train deep neural network (DNN) models, iteratively feeding GPUs with batches of data samples from a collection of raw data such as images, videos, and text. Before being efficiently consumed by armies of GPU cores, raw data must first be loaded into memory and processed through a sequence of transformation operators such as decode, crop, resize, and normalize. To effectively utilize the massive GPU parallelism available today, such data preprocessing must also be effective enough to continually pump data to satisfy the GPUs' appetite. Unfortunately, most existing studies have focused on just the training part, often neglecting the data preprocessing pipeline (Deng et al., 2015; Goyal et al., 2016; Goyal et al., 2016). Fortunately, though a few recent studies have started to consider this issue. _E.g._, Uber and Apple introduced their data platforms, with data models and methods to store and manage data for machine learning tasks (Goyal et al., 2016; Goyal et al., 2016). Yang and Gong proposed a distributed cache to speed up the I/O steps in data preparation for distributed DNN training (Xiao et al., 2017), while OneAccess applies a similar idea to avoid redundant data loading for concurrent hyper-parameter tuning experiments sharing datasets (Goyal et al., 2016). Still, none of the existing studies provide a comprehensive overview of DL data preprocessing pipeline, its performance, or major systems design issues involved. This work examines the data preprocessing pipeline in three major frameworks, specifically, TensorFlow, MXNet, and PyTorch, and its performance implications on overall training efficiency. Our major findings are as follows: * The widely used DL frameworks have long and highly similar data preprocessing pipelines, with the common data format and data structure choices. * Different DNN models, meanwhile, show different relative speeds in data preprocessing and actual training. With most studies focused on training performance, the majority of model training workflows have bottlenecks at data loading and preprocessing. * While the aforementioned three major frameworks all perform data preprocessing on CPUs and training on GPUs, the new NVIDIA framework DALI (Goyal et al., 2016) does deliver better overall performance by enabling CPU-GPU co-processing for preparing training data samples. However, it possesses caveats such as potential OutOf-Memory (OOM) problems, currently requiring a manual search for a proper batch size to avoid OOM while preserving high throughput. * Nevertheless, a single time-consuming step (such as image decoding, currently placed at the CPU side by DALI) may dominate the pipeline execution time, making GPUs wait for data. To eliminate this bottleneck, one would need to add more CPU resources. * Our preliminary results indicate that more flexible node configurations would allow more cost-effective executions of diverse DL pipelines: 7.86% and 3.03% speedup of training speed for AlexNet and ResNet50 with more CPU resources allocated, respectively, and 75% reduction in CPU resource allocation for ResNet50 with relatively comparable performance. Loading data samples from SSD-based storage options almost delivers the best training speed for ResNet18, while using DRAM introduces a 1.84\(\times\) speedup for AlexNet. Our study chimes in the argument for _resource disaggregation_(Cordes and McAllester, 2011; Chen et al., 2013; Chen et al., 2014; Chen et al., 2015), a new trend in cloud infrastructure design featuring composable and disaggregated resource deployment, delivering comparable performance, while retaining strong flexibility at the same time (Zhou et al., 2015; Zhang et al., 2016). Currently, some cloud providers such as Google Cloud and EC2 are enabling this feature to some extent, by allowing the number of vC-PUs for GPU machines to be adjusted, though under particular constraints (Chen et al., 2013). We believe that the data preprocessing-training resource balancing problem described in this paper lends a common and resource-intensive use case to upcoming cloud resource disaggregation offerings. In particular, to avoid time-consuming manual configuration, there should be tools making such configuration and scaling decisions automatic, for higher overall user DL model training throughput (per hour or dollar) and simultaneously, for better overall system utilization from the cloud provider's point of view. ## 2. Understanding the Training Pipeline It is necessary to train DNN models with vast amounts of data to achieve accurate results. However, the real-world data sets are often not in a suitable form such that they can be directly fed into the neural network. The data set often goes through a data preprocessing pipeline, spanning across loading, decoding, decompression, data augmentation, format conversion, and resizing. Given that the performance of accelerators, including GPUs, is rapidly improving, this data loading pipeline phase of end-to-end training will inevitably become more and more significant. ### Iterative DNN training Training DNN models are computationally intensive and time-consuming. To shorten the training process and make DNN models quickly deployable, current common practice explores the massive parallelism offered by multiple GPUs for collective training following a mini-batch stochastic gradient descent (SGD) algorithm (Srivastava et al., 2014). This phase of training, which is depicted (and denoted "DNN model") on the rightmost side of Figure 1, has been the focus of the majority of studies on improving DNN training. This training process works iteratively: at each round, a small batch of data samples will be fetched and loaded into the GPU memory as input for the neural network model training. However, for such training, typically, the application-specific raw data stored in persistent storage need to be transformed into _tensors_, a unified data format consumed by various training frameworks. We refer to this phase of training as a data preprocessing pipeline, which is depicted in the left part of Figure 1. ### Overview of data preprocessing pipeline We analyze four different implementations of the data preprocessing pipeline, where the first three are built-in solutions for three widely adopted training frameworks, namely, TensorFlow, MXNet, and PyTorch, and the last one is a unified interface for all three aforementioned frameworks developed by NVIDIA called DALI (Nvidia et al., 2015). Despite being implemented by different communities, the composition of their pipelines looks almost the same. As follows, we report two major data preprocessing methods, namely, loading from raw data and loading from record files. For simplicity, in this paper, we describe the image processing scenario as an example. However, we observe that the general scenario holds across tasks ranging from Natural Language Processing (NLP) to Video Processing. #### 2.2.1. Raw data preprocessing The numbers in the black circle in Figure 1 depict the preprocessing pipeline for raw data. Figure 1. The end-to-end training pipeline where the first stage is the data preprocessing for Computer Vision tasks. First, Data Preprocessor (or short, DPP) reads a sequential metadata file, and stores it in memory as a dictionary for retrieving the actual data later on. The metadata file is usually generated offline, and each of its tuples contains the index (sequentially assigned), label, and path of each image. Then, \(\mathtt{\raisebox{-1.0pt}{\includegraphics[width=1.0pt]{fig-1.0pt}{fig-1.0pt}} }\) DPP partitions the whole file identifier list into a set of smaller sequences and shuffles them. \(\mathtt{\raisebox{-1.0pt}{\includegraphics[width=1.0pt]{fig-1.0pt}{fig-1.0pt}} }\) DPP continues to get the file ids from each sequence, uses ids to look up the corresponding labels and paths in the memory dictionary, loads the raw image files pointed by the paths, and decodes them into tensors. When tensors of the raw image files are ready, \(\mathtt{\raisebox{-1.0pt}{\includegraphics[width=1.0pt]{fig-1.0pt}{fig-1.0pt}} }\) DPP moves to the "augmentation" step, where tensors are transformed into new ones via a sequence of steps such as random crop, flip, rotation, etc. Finally, \(\mathtt{\raisebox{-1.0pt}{\includegraphics[width=1.0pt]{fig-1.0pt}{fig-1.0pt}} }\) Data Loader combines multiple tensors to form batches and \(\mathtt{\raisebox{-1.0pt}{\includegraphics[width=1.0pt]{fig-1.0pt}{fig-1.0pt}} }\) load these batches to the GPUs. #### 2.2.2. Record file preprocessing As indicated in Figure 1 by the white circled numbers, in addition to raw data preprocessing, there is another method, which makes use of record files. These record files are generated, through offline processing, \(\mathtt{\raisebox{-1.0pt}{\includegraphics[width=1.0pt]{fig-1.0pt}{fig-1.0pt}} }\) - \(\mathtt{\raisebox{-1.0pt}{\includegraphics[width=1.0pt]{fig-1.0pt}{fig-1.0pt}} }\) by reading a large number of raw image files stored on disks and then, appending them into a few large sequential record files. These files include images as well as their label and id. Then, during runtime, these record files are \(\mathtt{\raisebox{-1.0pt}{\includegraphics[width=1.0pt]{fig-1.0pt}{fig-1.0pt}} }\) read into memory and partitioned into smaller chunks. These chunks are \(\mathtt{\raisebox{-1.0pt}{\includegraphics[width=1.0pt]{fig-1.0pt}{fig-1.0pt}} }\) decoded, and thereafter, the remaining steps \(\mathtt{\raisebox{-1.0pt}{\includegraphics[width=1.0pt]{fig-1.0pt}{fig-1.0pt}} }\) - \(\mathtt{\raisebox{-1.0pt}{\includegraphics[width=1.0pt]{fig-1.0pt}{fig-1.0pt}} }\) are the same as the raw data preprocessing method. There are two major reasons for designing this record file loading method. First, compared to raw data, record files transform random accesses into sequential accesses, which can lead to performance gains if data are stored in slow storage or scattered across multiple machines. Second, it is possible to offload some operators, such as crop and resize, in the data preprocessing pipeline to the record file generation phase for improved data loading efficiency. In essence, the record file loading method is trading extra processing time and storage space for training speed improvement. Finally, one would think it feasible to take all tasks along the data preprocessing pipeline offline so that the runtime can be optimized. While this is feasible in terms of performance, this may not be the best approach for DNNs. This is because the training process requires some form of randomness from data sample inputs to improve the robustness and universality of DNN models, which is achieved by executing some non-deterministic operators in the pipeline such as random rotates and flips. Such randomness is required for the best results in DNN. Therefore, the preferable choice is to just append images to sequential record files with no further preprocessing. #### 2.2.3. CPU-GPU co-processing All the four data loading pipeline implementations that we consider allow both raw data and record file loading methods. The main difference between the three built-in data loading libraries in the TensorFlow, MXNet, and PyTorch frameworks and DALI is that while the former three-run the data loading pipeline on CPUs only, DALI makes use of the GPUs to speed up the task by offloading parts of the pipeline to GPUs. We refer readers to DALI code examples (B **Models and data sets:** We train five DNN models, namely, AlexNet (Krizhevsky et al., 2015), ShuffleNet (Zie et al., 2015), ResNet18(He et al., 2017), ResNet50 (He et al., 2017), and ResNet152 (He et al., 2017), on the widely used ImageNet data set (Krizhevsky et al., 2015). We enable mixed-precision training (FP16 option on) to fully exploit GPU resources. For AlexNet, ShuffleNet, and ResNet18, we adopt a batch size of 512 as larger batches produce little performance improvement. The other two models are much larger due to having more layers, so ResNet50 uses a batch size of 192 and ResNet152 uses 128, due to memory constraints. **Metrics:** We measure data preprocessing and model training throughput, in samples per second. For reference, we also plot the "ideal" training performance, where training reuses a single batch preloaded into GPU memory. In addition, we measure both the CPU and GPU utilization levels. ### Overall performance Figure 2 gives overall training performance across preprocessing methods. First, most models see improvement when using record files and especially when adopting hybrid data preprocessing. The former benefits from a higher ratio of sequential I/O, which is advantageous even on NVMe SSDs. The latter allows powerful GPUs to ease the data preprocessing bottleneck on CPUs and achieve more balanced system utilization. However, we observe that for three of the five models, their best end-to-end training throughput is significantly lower than the ideal one. This demonstrates the performance impact of the data preprocessing pipeline and GPU underutilization. That is, the data preprocessing pipeline is not able to fill the GPUs fast enough such that the GPUs are being underutilized, which is validated in the following section. In particular, for AlexNet, its peak performance under record-hybrid is only 23% of the ideal case. Considering these three fast data consumers where hybrid data preprocessing helps the most (exemplified by the large jump from green bar to red bar), as the GPUs otherwise starved for data is used to offload data preparation from CPUs, we observe 98% to 114% throughput improvement for them compared to record-CPU. Interestingly, even for these three models, hybrid processing does not help when raw files are used, as random I/O dominates loading and CPUs alone can match the I/O speed. ResNet50 and Resnet152, in contrast, are much more computation-intensive in training (with much lower ideal training throughput than the other models), rendering data loading less influential. To further investigate why offloading portions of preprocessing to the GPUs significantly improves training performance, here, we report the latency breakdown of different steps along the data loading pipeline. In so doing, we do not enable training, instead, only focus on running the data preprocessing pipeline and exercising the performance of its individual operators. We plot the times spent in different data augmentation operators in Figure 3. Note that we are reporting breakdowns when only the CPU is being used for data preprocessing. The results highlight that all data preprocessing operators consume nearly 95% of the whole pipeline cost. Among these operators, image decoding is most time-consuming, which accounts for 47.7% of the total time. When record-hybrid is used in our experiments, data preprocessing splits the operators such that most of the decoding and beyond are performed by the GPU, reducing the overall preprocessing time. Note that the performance benefits of record-hybrid come at a cost. First, it requires extra work offline to produce record files. Second, effective pipeline design requires concurrent data preprocessing and model training on the GPUs. This comes with two consequences. One is that there is a potential cause for OOM errors, which will require manual intervention to avoid. The other is that, as we show later in Figure 5, training throughput may be negatively affected due to the sharing of the GPUs. ### Resource Utilization Figure 4 plots the utilization level of different resources during the training process under record-hybrid for AlexNet and ResNet50, each, respectively, representing a fast and slow data consumer. It is worth noting that the roughly first one-third of each curve corresponds to the initialization of training. For ResNet50, GPUs are nearly saturated for the last two-thirds of the entire process while CPU utilization is Figure 3. 100% stacked bar graph showing breakdown latency of major steps for preprocessing a single image on CPU, which takes 14.26 ms in total (Numbers are percentages.) Figure 2. End-to-end training performance at a much lower 38% and the I/O bandwidth-consuming only 147MB/s, also much lower than its maximum capacity. We observe that ResNet50 is GPU-bound where training data consumption is slow enough to hide I/O and data preprocessing. Thus, we find that CPU and storage devices are being underutilized. We also see that even though GPU resources are precious, DAI is making use of these resources for data loading, which is an unwise choice of use. AlexNet, on the other hand, is a fast data consumer making quick use of the loaded data and then waiting for more data to arrive. This is reflected in the fluctuation of GPU utilization. Overall, the GPU is utilized under 50%. In contrast, we see that the CPU utilization much higher than that of ResNet50 (Figure 3(b)) and that the I/O bandwidth is also considerably higher (Figure 3(c)). We see that record-hybrid is helpful in this case as it helps improve the utilization of the GPUs. However, we see that the CPUs are not enough to satiate the data needs of the GPU and that the more CPUs need to be allocated to the data preprocessing pipeline. ## 4. Effect of Resource Balancing Public cloud providers are beginning to offer more flexible instance configurations. Table 1 lists available GPU VM instances on Amazon EC2 and Google Cloud. With a given instance type associated with fixed GPU resources, both platforms allow users to specify the desired number of vCPUs within a preset range. EC2 further enables I/O throughput (proportional to persistent storage capacity requested), while Google Cloud provide a limited number of storage choices. Along with such flexible configurations come fined-grained charging policies. _E.g._, on the listed Google Cloud instances, GPU and vCPU cost 2.48 and 0.033$/hour, respectively, while memory costs 0.00445/GB-hour. While such flexible configurations provide consumers with better choices, selecting the best configuration for a DNN model is not an easy task. Our eventual goal is to develop a tool that will propose model-specific, fine-grained resource configurations for a model training workflow while maintaining high throughput performance. Our findings described in the previous section show that such a tool will be valuable. In this section, we present some results that may be possible once this tool is developed. In particular, we investigate the performance implications of adjusting the number of vCPUs. Again, in the interest of space, we focus on the two representative DNN models evaluated earlier, AlexNet and ResNet50. First, consider the preprocessing-bound AlexNet, where we fix the number of GPUs to 4 and adjust the number of \begin{table} \begin{tabular}{c||c|c|c|c} Type & \#GPU & \#vCPU & I/O & \$/h \\ \hline \hline p3.2xlarge & 1 & \(\leq 8\) & Configurable & \(<3.06\) \\ p3.16xlarge & 8 & \(\leq 64\) & Configurable & \(<24.48\) \\ p3dn.24xlarge & 8 & \(\leq 96\) & Configurable & \(<31.21\) \\ \hline V100-1 & 1 & \(\leq 12\) & Options & \(<3.22\) \\ V100-4 & 4 & \(\leq 48\) & Options & \(<12.90\) \\ V100-8 & 8 & \(\leq 96\) & Options & \(<25.80\) \\ \hline \end{tabular} \end{table} Table 1. VM instances commonly used for DNN model training on AWS EC2 (Gupta et al., 2017) (top), and Google Cloud (Gupta et al., 2017) (bottom). All GPUs are V100. Figure 4. Resource stats of AlexNet and ResNet50 corresponding to the best performed record-hybrid experiments in Figure 2. Figure 5. End-to-end training performance of AlexNet and ResNet50 with CPU resources adjusted for GPUs vCPUs. With all 64 vCPUs available for the 4 GPUs, we investigate one additional loading method (aside from the hybrid mode evaluated earlier), which performs decoding on CPU and the rest of preprocessing on GPU, denoted as hybrid-0. This mode uses more CPU resources while relieving the more expensive GPU resources to training. Recall that in a hybrid image decoding is jointly performed by CPU and GPU. Figure (a)a shows that, while hybrid saturates training at 24 vCPUs (6 per GPU), hybrid-0 delays its saturation point to 44 vCPUs (11 per GPU). This results in a 7.86% increase in training speed as depicted by a higher line beyond 11 vCPUs in the figure. Now consider the training-bound ResNet50, where the GPU is the clear bottleneck. Thus, we make use of all 8 GPUs for these experiments. Here we can explore reducing vCPU allocation without performance degradation or improving performance by re-configuring the CPU-GPU co-processing tasks. Figure (b)b confirms that the number of required vCPUs here is much lower than available in such instances. For instance, under the hybrid mode, 16 vCPUs (2 per GPU) can adequately feed the GPUs. To further reserve GPUs for the time-consuming training, we push DALI optimization back to using solely CPU for data preparation, _i.e._, the cpu mode, denoted CPU in the figure. Now we need 48 vCPUs (6 per GPU) to saturate the training pipeline, paying more CPU costs, for a training speed improvement of 3.03%. We further observe (but not shown here) that moving from ResNet50 to ResNet152, with deeper layers, the training pipeline becomes even more GPU-bound, reducing the vCPU requirement to 8 vCPUs (1 per GPU). Note that in both the AlexNet and ResNet50 examples, we observe that employing GPUs for the data preprocessing pipeline, though helpful for the pipeline, results in reduced throughput. Finally, we shift our attention to exploring the performance implications of using different storage media for hosting training data. For this purpose, we deploy AlexNet and ResNet18 on an EC2 p3dn.24xlarge instance, and train them with 4 V100 GPUs, each assisted by 12 vCPU cores. We vary the storage devices, testing EBS (up to 7500 IOPS), two NVMe SSDs (default setting by EC2), and DRAM. Figure 6 reports the end-to-end training performance. We observe that loading data samples directly from EBS and NVMe SSDs (corresponding to 1 in Figure 1) achieves almost the same training performance for the two models. This is because EBS is a highly optimized storage option exploring SSDs and it offers similar I/O bandwidths as the attached NVMe SSDs. Interestingly, when loading data samples from DRAM, the training performance of ResNet18 has been just improved by 8.8%. This is a direct consequence of the fact that ResNet18, like ResNet50, is computation-intensive and the bandwidths of EBS and NVMe SSDs are sufficient to meet the needs of the training phase in GPU. In contrast, using DRAM leads to a 1.84\(\times\) speedup of the AlexNet training performance against the other two storage options. This is because the computation of AlexNet is much faster than ResNet18, and it demands larger I/O bandwidth beyond the capacity of both EBS and NVMe SSDs. Therefore, the performance impact of storage configuration is model dependent. For certain models, investing in high-bandwidth storage may significantly improve the overall cost-effectiveness of DNN training. ## 5. Conclusion and Future Directions It is commonly accepted that DNN training requires considerable resources in terms of GPU/accelerator and network infrastructure. While studies to expedite training through better management of these resources have been the focus of many studies, we contend that there is another aspect that is as important, which, to date, has been largely neglected. Specifically, data has to be fed to the accelerators such that the accelerators can be fully utilized. In this work, we examine the data preparation process of widely used deep learning model training frameworks. We have found that different frameworks have highly similar data loading and preprocessing pipelines, while the relative overhead of data preparation to that of in-memory model training varies significantly across popular DNN models. Based on our performance results, our contention is that this pipeline is currently inefficient, often leading to considerable resource waste, especially the under-utilization of expensive GPU resources. We further verify the effectiveness in hybrid CPU-GPU data preparation and propose model-specific, fine-grained cloud instance configuration for efficient and cost-effective model training. In future work, we will extend our performance analysis to both NLP and video processing models. Following that, Figure 6. End-to-end training performance of ResNet18 and AlexNet, loading data samples from different storage options we plan to build a tool that enables automatic resource configuration to adapt to the demand for diverse deep learning training workloads.
2303.16564
Implicit Visual Bias Mitigation by Posterior Estimate Sharpening of a Bayesian Neural Network
The fairness of a deep neural network is strongly affected by dataset bias and spurious correlations, both of which are usually present in modern feature-rich and complex visual datasets. Due to the difficulty and variability of the task, no single de-biasing method has been universally successful. In particular, implicit methods not requiring explicit knowledge of bias variables are especially relevant for real-world applications. We propose a novel implicit mitigation method using a Bayesian neural network, allowing us to leverage the relationship between epistemic uncertainties and the presence of bias or spurious correlations in a sample. Our proposed posterior estimate sharpening procedure encourages the network to focus on core features that do not contribute to high uncertainties. Experimental results on three benchmark datasets demonstrate that Bayesian networks with sharpened posterior estimates perform comparably to prior existing methods and show potential worthy of further exploration.
Rebecca S Stone, Nishant Ravikumar, Andrew J Bulpitt, David C Hogg
2023-03-29T09:47:35Z
http://arxiv.org/abs/2303.16564v3
# Implicit Visual Bias Mitigation by Posterior Estimate Sharpening of a Bayesian Neural Network ###### Abstract The fairness of a deep neural network is strongly affected by dataset bias and spurious correlations, both of which are usually present in modern feature-rich and complex visual datasets. Due to the difficulty and variability of the task, no single de-biasing method has been universally successful. In particular, implicit methods not requiring explicit knowledge of bias variables are especially relevant for real-world applications. We propose a novel implicit mitigation method using a Bayesian neural network, allowing us to leverage the relationship between epistemic uncertainties and the presence of bias or spurious correlations in a sample. Our proposed posterior estimate sharpening procedure encourages the network to focus on core features that do not contribute to high uncertainties. Experimental results on three benchmark datasets demonstrate that Bayesian networks with sharpened posterior estimates perform comparably to prior existing methods and show potential worthy of further exploration. ## 1 Introduction In a perfectly unbiased world, every possible combination of features would be equally present in every sample set. Unfortunately, it has become increasingly apparent that societal and historical biases are prevalent in every domain. Furthermore, even if it were always feasible to obtain a balanced dataset, this in itself does not ensure a fair model, as relative quantities are not the sole contributor towards bias [41, 26]. Not only are biased datasets pervasive, but algorithms themselves can even amplify bias [50, 18]. Particularly in the visual domain, it is not realistic to assume a comprehensive knowledge of all bias variables in a dataset, let alone know where they occur across the training data. In high-impact domains highly susceptible to dataset bias, including medicine, finance, welfare, and crime, confidentiality and privacy requirements prohibit general use of metadata which might specify presence of bias variables in training sets. Furthermore, in most cases population bias makes balanced sampling impossible. The implications and consequences [11, 9, 28, 8]1 of unfair models built using such biased datasets are disheartening and intolerable. Footnote 1: [https://www.propublica.org/article/machine-bias-risk-assessments-in-criminal-sentencing](https://www.propublica.org/article/machine-bias-risk-assessments-in-criminal-sentencing) Recently, various studies propose implicit mitigation methods for neural networks [42, 27, 46, 4]. Yet many challenges still remain. Sample imbalances between minority and majority groups can be too steep to overcome without overfitting [43, 4, 36], learning spurious correlations is often much easier than learning the desired core features [18], and some bias-conflicting samples are simply more difficult to learn than others [41]. Additionally, studies comparing results for multiple methods on more than one visual bias benchmark dataset indicate that _no single mitigation method is universally effective_[34, 42, 18]. We contribute towards a better understanding and exploration of visual bias mitigation by proposing a novel implicit mitigation method which leverages the correlation between uncertainties and bias-conflicting samples. Episemic uncertainties in the Bayesian paradigm arise from lack of knowledge - missing information or data - and decrease given a more comprehensive distribution of data. This contrasts with aleatoric uncertainty, or data "noise" uncertainty which is irreducible since probabilistic variations are present irrespective of the dataset size. Thus, a more balanced distribution of data (in both quantity and ease of learning) will reduce epistemic uncertainties. We can directly leverage this for implicit bias mitigation. A few recent works have also used this correlation. Branchaud-Charron et al. [7] show Bayesian Active Learning by Disagreement (BALD) [15] can help mitigate bias against relying on spurious correlations through rebalancing the dataset via an acquisition scheme which greedily reduces epistemic uncertainty. Khan et al. [22] use Bayesian uncertainty estimates to deal with class imbalance by weighting the loss function to move learned class boundaries away from more uncertain classes. This focuses primarily on class-level bias in the class imbalance score nario, with some consideration for sample-level bias; our proposed method focuses solely on sample-level bias as we do not expect bias to be constrained to classes. Epistemic uncertainties are also used in a previous study [36] (EpiWt) to dynamically weight samples during training, but this approach suffers from the same overfitting problem as both explicit and implicit up-weighting methods. Contributing to this body of literature, we propose a novel posterior estimate sharpening approach, which focuses on uncertainty-guided implicit feature re-weighting in the classification layers of a Bayesian neural network. In addition to showing potential compared against other methods, our sharpening approach also provides post-inference uncertainty estimates which can be useful for a variety of purposes. ## 2 Related Work Prior mitigation methods can be categorized as _explicit_ or _implicit_. Explicit approaches require knowing the bias variables and which training samples are bias-aligned. Various works have experimented with re-weighting or re-sampling, the intuitive approach by which the minority samples are made to appear more often, thus encouraging the model not to leverage undesired correlations. This can be done via sampling probability [10, 21], loss weighting [12], or synthetically generating or augmenting data to balance out or encourage learning of certain features [19, 16]. Other methods focus on discouraging the representation portion of the network from encoding the biases. This can be accomplished through adversarial learning [48, 40], or by manipulating the feature representations in latent space to disentangle the spurious and core features [38, 37]. Another category of works explicitly learn the bias variable, in order to then unlearn it or adjust the model decisions based on this knowledge [14, 42]. Alvi et al. [3] propose a variant of this through "fairness through blindness", simultaneously learning the target task while learning to ignore the bias variables. However, these methods are vulnerable to redundant encoding [26], or learning combinations of other perhaps unlabeled bias variables as a proxy for the chosen bias variables. The knowledge of bias variables can also be used to group the training data into subgroups for training fairer models. Group distributionally robust optimization (gDRO) suggests sub-grouping data according to their bias and class variables, and optimizes such that the model generalizes best over all groups [30]. Predictive group invariance (PGI) [1] also groups data according to bias variables and encourages matched predictive distributions across the groups, penalizing learning spurious features that do not appear across all groups. Both [30, 1] assume bias variables are specified in the training set, but also propose ways to infer groupings implicitly from the data. Similarly, but with a reinforcement learning setup, [41] propose an adaptive margin loss function which computes ideal margins between groups. In contrast, implicit methods do not assume any prior knowledge of bias variables in the data. One such category of implicit methods leverages the observation that networks themselves can sometimes identify when they have learned spurious features as they are more easily learned, but, relying on them still results in misclassifications for a minority. Learning from Failure (LfF) [27], Learning with Biased Committee (LWBC) [23], and approaches by Bahng et al. [5] and Sanh et al. [31] exploit the failures of one or more normal or bias-amplifying networks to inform a de-biased network. These methods attempt to minimise the effect of bias-aligned training samples, some by actually removing samples from the training set shown to the target network. Other methods explore implicit versions of up-weighting or re-sampling, by discovering sparse areas of the feature space [4] or dynamically identifying samples more likely to be bias-conflicting [36]. Du et al. [13] de-bias the classification head of the network by training on neutralized representations of training data. This requires knowing when bias variables appear in the training samples (or at least being able to predict using some other model) in order to adjust the representations. Another category of implicit methods change the loss function to reward learning a fairer model; Xu et al. [46] implement this via a false positive rate penalty loss, and Pezeshki et al. [29] through Spectral Decoupling (SD), an adjusted L2 loss encouraging feature decoupling and discouraging learning features at the expense of learning another. SD allows the learning of simple correlations but not unilaterally, resulting in the preservation of minority core features. Recently, Shrestha et al. [35] open a promising new direction of work, leveraging architectural inductive biases with an adaptable architecture (OccamNets) which allows the network to favor simpler solutions when needed. The resulting model prefers focusing on smaller visual regions for predictions yet does not constrain all samples to rely on the same complexity of hypotheses, as optimal "exit" locations in the architecture are learned per sample. Our proposed implicit method shares intuition and motivation with many of these approaches, as we discuss further in Section 3.4. ## 3 Methodology ### Premise For a Bayesian neural network with parameters \(\boldsymbol{\theta}\), posterior \(p(\boldsymbol{\theta}\ \mid D,\boldsymbol{x})\), class-labelled training data \(D=(X,Y)\), and test sample \(\boldsymbol{x}_{i}\), the predictive posterior distribution for a given target class \(\boldsymbol{y}_{i}\) is as follows: \[p(\mathbf{y}_{i}\mid D,\mathbf{x}_{i})=\int p(\mathbf{y}_{i}\mid\mathbf{\theta},\mathbf{x}_{i})p(\mathbf{ \theta}\mid D)d\mathbf{\theta} \tag{1}\] While this itself is intractable, stochastic gradient MCMC (SG-MCMC [44]) is a tractable variation of the gold standard Markov chain Monte Carlo (MCMC) algorithm, and uses the stochastic gradient over mini-batches with an additional Gaussian noise bound instead of the gradient over the whole training distribution. Furthermore, for faster convergence and a more thorough exploration of the multimodal distributions prevalent in deep neural networks, we adopt the cyclical learning rate schedule introduced in [49] known as cyclical SG-MCMC, or cSG-MCMC. Larger learning step phases provide a warm restart to the subsequent smaller steps constituting the sampling phase. The final estimated posterior of the Bayesian network consists of \(\mathbf{\Theta}=\{\mathbf{\theta_{1}},...\mathbf{\theta_{M}}\}\), \(M\) moments sampled from the posterior over all trainable parameters, taken during the sampling phases of each learning cycle. With functional model \(\mathbf{\Phi}\) representing the neural network, the approximate predictive mean \(\mathbf{\mu}_{i}\) and output class prediction \(\mathbf{\hat{y}}_{i}\) for sample \(\mathbf{x}_{i}\) are: \[\mathbf{\mu}_{i}\approx\frac{1}{M}\sum_{m=1}^{M}\mathbf{\Phi}_{\theta_{m}}(\mathbf{x}_{i}) \tag{2}\] \[\mathbf{\hat{y}}_{i}=\text{argmax}\left(\mathbf{\mu}_{i}\right) \tag{3}\] The epistemic uncertainty corresponding to this prediction is: \[\mathbf{\sigma}_{i}\approx\frac{1}{M}\sqrt{\sum_{m=1}^{M}\left(\mathbf{\Phi}_{\mathbf{ \theta}_{m}}(\mathbf{x}_{i})-\mathbf{\mu}_{i}\right)^{2}} \tag{4}\] which for any given sample is an indicator of model confidence in its prediction based on the information given. We refer readers to [20] for a more in-depth presentation of Bayesian neural networks and their implementation. ### Bias and Uncertainties Bias-conflicting samples tend to have higher epistemic uncertainties than their bias-aligned counterparts [17, 2, 36]. These epistemic uncertainties arise from the classification, not representation, portions of the network despite the learned representations being arguably "biased representations" [13]. We can briefly explore these two claims on a toy synthetic dataset which we call Biased Synbols. We choose Synbols [25] as the tool to build Biased Synbols as we can easily control the resolution and features in each generated image. The foreground of each \(224\) x \(224\) image is a character displayed in a font chosen randomly from a large selection of fonts, and the texture of the character is a random natural scene, cropped to fit the character mask. The background behind the character is a 2-color gradient. We introduce four types of bias as shown in Figure 1. We generate a two letter ("s" and "t") binary classification task with train/val/test splits of 20k/5k/5k and train Bayesian AlexNet on four versions of Biased Synbols, each with a different bias variable and \(p_{bias}=0.95\) for the "s" class and \(p_{bias}=0.05\) for the "t". In each case, the bias-conflicting samples have higher mean group uncertainties than the bias-aligned (a mean increase by 0.15, 0.16, 0.09, and 0.20 for the four variables shown in Figure 1 respectively, for normalized uncertainties between 0.0-1.0). Next, we identify where the discrepancies in uncertainties arise from in the network. We find indiscernible difference in uncertainties by averaging the uncertainties across the features extracted directly after the final convolutional layer. To further confirm, we perform network dissection [6]. on Biased Synbols with the spurious square in a random corner. Network dissection measures the alignment between convolutional kernel activations and any concept, which can be defined by segmentation masks on the dataset. As the square bias variable is generally spatially distinct from the core feature, i.e. the character shape, we can dissect the network to locate which convolutional kernels are most strongly activated by the former (Figure 2). For every convolutional layer in AlexNet, we compute the intersection-over-union (IoU) of the square with the thresh Figure 1: One sample from class “s” of our toy dataset Biased-Synbols with controllable bias variables _(left to right)_: texture of letter, spurious square placed in random corner, resolution of whole image, and gray-scale. Figure 2: The six training images for which kernel 0, convolutional layer 4 _(top)_ and kernel 10, convolution layer 2 _(bottom)_ from AlexNet most strongly activate. The first kernel has identified a core feature for class “s”, whereas the second corresponds to the spurious or bias feature rather than the character. olded kernel activation heatmaps, and measure correlation between these IoUs and the kernel uncertainties. The Pearson correlations per layer are -0.01, -0.03, 0.13, -0.07, and 0.17, strongly indicating no clear correlation; thus, simply learning features associated with bias variables _does not create discrepancies in uncertainties_. These observations motivate our focus on the classification head and the uncertainties induced by learning a biased feature weighting in the classification layers of the network. ### Posterior Estimate Sharpening We propose a _sharpening_ procedure (Algorithm 1) which further fine-tunes the classification layers of each Monte-Carlo sample from the Bayesian posterior using a multi-component loss function. We freeze the representation portion of the network during this procedure because (1) we aim to learn re-weighting of learned features in the classification head only, (2) updating the representation network can change the feature representations, thus complicating the re-weighting goal, and (3) experimental evidence backs these intuitions, showing a drastic drop in both performance and model fairness when the whole network is fine-tuned. Thus, when we refer to posterior estimates for sharpening, we are referring to \(\mathbf{\theta}_{c}\), where each posterior sample \(\mathbf{\theta}_{m}=\{\mathbf{\theta}_{r,m},\mathbf{\theta}_{c,m}\}\) includes the parameters from the representation and classification portions of the network respectively. The validity of operating on \(\mathbf{\theta}_{c}\) alone can be supported by literature on "Bayesian last layer" networks [24]. Our novel loss, a _sharpening loss_, penalizes the posterior of a Bayesian neural network for having a large variance. This can also be compared to artificially sharpening or tempering the posterior (see discussion in Section 3.4). Consider a regular negative log likelihood loss measuring, for a sample \(\mathbf{x}_{i}\), the divergence between the true class and the predicted likelihood of each class. For one-hot encoded true target \(\mathbf{y}_{i}\) and model prediction \(\mathbf{\Phi}(\mathbf{x}_{i})\), negative log likelihood loss computes the sum over all possible classes: \[L_{nll}=L(\mathbf{y}_{i},\mathbf{\Phi}(\mathbf{x}_{i}))=-\sum\mathbf{y}_{i}\cdot\text{log}(\bm {\Phi}(\mathbf{x}_{i})) \tag{5}\] With our Bayesian posterior estimate, our proposed loss \(L_{s}\) must be computed separately for each posterior sample \(\mathbf{\theta}_{m}\). We replace the true target \(\mathbf{y}_{i}\) with one-hot encoded \(\mathbf{\hat{y}}_{i}\) (Equation 3) derived from the predictive mean, capturing the divergence between the prediction of _a single posterior estimate_ and the mean prediction of the whole posterior: \[L_{s}=L(\mathbf{\hat{y}}_{i},\mathbf{\Phi}_{\theta_{m}}(\mathbf{x}_{i}))=-\sum\mathbf{\hat{y}} _{i}\cdot\text{log}(\mathbf{\Phi}_{\theta_{m}}(\mathbf{x}_{i})) \tag{6}\] This minimizes \(\mathbf{\sigma}\) in Equation 4. Equivalently, \(L_{s}\) encourages the classification layers of the network to learn a feature weighting which minimizes uncertainties for high uncertainty samples, by diminishing the importance of features contributing to high uncertainties. A bias-conflicting sample class pair \((\mathbf{x}_{i},\mathbf{y}_{i})\) may have high uncertainty because it does not contain bias feature \(b\) present in the majority of class \(\mathbf{y}_{i}\). One or more features \(F\) capture the relationship between \(b\) and \(\mathbf{y}_{i}\) and the variance of the distributions over the weights of \(F\) are responsible for the high class uncertainty for \(\mathbf{x}_{i}\). The sharpening loss rewards down-weighting \(F\), hence discouraging the \((b,\mathbf{y}_{i})\) correlation. Not all samples are equally important. The bias-conflicting sample with high uncertainty, for example, should have larger gradients which shift the distribution. In contrast, there is no need to adjust the weights for a bias-aligned sample with low uncertainty; to do so would strengthen the existing undesired correlation. To reflect this, we weight each sample by \(\mathbf{w}_{i}\) as a function of its epistemic uncertainty as proposed in [36] and shown in Equation 7 for a batch of size \(N\). The distribution is shifted by 1.0 and scaling constant \(\kappa\) controls the steepness of the function such that low uncertainty samples are never completely discounted, but only minimally shift the distribution. \[\mathbf{w}_{i}=(1.0+\mathbf{\sigma}_{i,y_{i}})^{\kappa} \tag{7}\] Backpropagating with this loss sharpens the estimated posterior, and has the potential to also shift the predictive mean away from the true target. Thus, we find it is not beneficial to completely discard the original loss that directs the network towards true targets. ``` 0: Training data \(X,Y\), neural network \(\mathbf{\Phi}\), update step size \(\epsilon\), posterior \(\mathbf{\Theta}\) 1:for each iteration of sharpening do 2: Given \(\mathbf{\Theta}\), compute \(\mathbf{\mu}\) and \(\mathbf{\sigma}\), for all \(X\) 3:for each \(\mathbf{\theta}_{m}=\{\mathbf{\theta}_{r,m},\mathbf{\theta}_{c,m}\}\in\mathbf{\Theta}\)do 4:for each batch \(\mathbf{x}_{b}\), \(\mathbf{y}_{b}\) of size \(\left|b\right|\)do 5:\(\mathbf{w}_{b}=(1.0+\mathbf{\sigma}_{b,y_{b}})^{\kappa}\) 6:\(\mathbf{\hat{y}}_{b}=\text{argmax}\left(\mathbf{u}_{b}\right)\) 7:\(L_{nll}=L(\mathbf{y}_{b},\mathbf{\Phi}_{\theta_{m}}(\mathbf{x}_{b}),\mathbf{w}_{b})/\left|b\right|\) 8:\(L_{s}=L(\mathbf{\hat{y}}_{b},\mathbf{\Phi}_{\theta_{m}}(\mathbf{x}_{b}),\mathbf{w}_{b})/\left|b\right|\) 9: Update \(\left[\mathbf{\theta}_{c,m}+\mathbf{\epsilon}\text{PCGrad}(L_{s},L_{nll})\right]\) 10:endfor 11:endfor 12:endfor ``` **Algorithm 1** Sharpening procedure on Monte-Carlo estimate of posterior \(\mathbf{\Theta}=\{\mathbf{\theta}_{m},...\mathbf{\theta}_{M}\}\) As the two loss gradients may conflict, we use a form of gradient surgery used in multi-task learning called _projecting conflicting gradients_ (PCGrad) [47], whereby the gradient of one loss is projected onto the normal plane of the other when the gradients have negative cosine similarly. For each sample in each mini-batch, gradients for losses \((L_{s},L)\) are computed. If there is destructive interference, one gradient is selected at random and projected onto the normal plane of the other. In the case of constructive interference, both gradients are combined as usual. The cumulative update to the weights is then averaged over the batch. An ablation study showing experimental support for the use of gradient surgery is shown in Table 5. ### Related Observations Sharpening posterior estimates allows the network to first learn all features unhindered, then implicitly adjusts the weighting of those features with respect to the final task. The motivation for this novel approach stems from two main observations. **Addressing simplicity bias.** Firstly, deep neural networks trained with empirical risk minimization (ERM) prefer simple solutions, tending to rely on spurious correlations especially when they are easier to learn than the core features. This has been referred to as _simplicity bias_[33]. Every bias mitigation method attempts to inform the model when it should rely on more complex predictive features versus when a simpler explanation is preferable. In literature, this has been addressed by either (1) selectively modifying the learned representations post-training [32, 13], or (2) guiding the network to selectively learn un-biased representations to begin with [27, 23, 29, 35, 36]. Posterior estimate sharpening falls in the first category, an implicitly-guided re-weighting of the classification head. It constrains the complexity of the model, not unlike OccamNets [35] which does so architecturally. Furthermore, sharpening is less prone to overfitting to minority samples as unlike [36, 10, 21, 12], it is not directly equivalent to up-weighting samples, focusing rather on feature weighting. The sharpening procedure addresses simplicity bias by relying on uncertainty estimates to inform when simpler solutions are not preferable, because they result in high uncertainties for bias-conflicting samples. **Adjusting Bayesian posteriors.** Secondly, artificially tampering with posteriors of Bayesian deep neural networks is not a foreign concept. As presented by Wenzel et al. [45], the true Bayesian posteriors of deep neural networks are rarely used in practice. Rather, _tempered_ or _cold posteriors_ are widely found to perform better. Tempered posteriors are equivalent to over-counting the data by a factor of \(1/T\) for temperature scalar \(T\) and re-scaling the prior to \(p(\mathbf{\theta})^{1/T}\). In contrast, the true Bayes posterior corresponding to \(T=1\) usually gives sub-optimal performance. We note, however, that our proposed sharpening procedure is applied only to the _estimated_ posterior derived from MC sampling, not to the true Bayes posterior. The MC samples provide a finite, numerical handle on model inference. Furthermore, running the sharpening procedure with a sampling size \(M\) of up to 20 indicates that increasing the MC sample size for a more accurate posterior estimate has negligible impact on the de-biasing. ## 4 Experiments ### Datasets Following the benchmarks established by Shreshtha et al. in [35], we experiment on three datasets for visual bias mitigation shown in Figure 3. **Biased MNIST**[34] introduces color, texture, scale, and contextual biases into a 5 x 5 grid of cells, one or more of which contain one of the target MNIST 10 digits. With \(p_{bias}=0.95\), each digit co-occurs 95% with each bias source. The test set is unbiased with a 50K/10K/10K train/val/test split. **COCO-on-Places**[1] spuriously correlates Places backgrounds with COCO object foregrounds. Most zebras, for example, appear in front of a desert, and most horses in front of a snowy landscape. Three test sets are provided: 1) biased backgrounds, matching the correlations present in the training set, 2) unseen backgrounds, including seen objects placed on new backgrounds unseen during training, and 3) seen but unbiased backgrounds. COCO-on-Places has a 7200/900/900 train/val/test split and 9 classes. Finally, **Biased Action Recognition (BAR)**[27] includes manually selected real-world images of action-background pairs, where the backgrounds are correlated to the action; e.g., most characters in the "climbing" class are climbing snowy mountains, and more rarely climb other objects such as buildings, structures, etc. BAR is the smallest dataset with a 1641/300/654 Figure 3: Datasets used for evaluation: Biased MNIST _(left)_, COCO-on-Places _(center)_, Biased Action Recognition (BAR) _(right)_. train/val/test split 2 and 6 target classes. Footnote 2: We randomly split the published training set into training and validation sets as no split is consistently used in literature. ### Group Epistemic Uncertainties Unlike Biased-Synbols where the bias variable and its effect on model uncertainty can be observed and controlled in isolation, our benchmark datasets are significantly more complex. Bias-inducing features co-occur, but not always on the same samples (Biased MNIST). Classes can be severely imbalanced (BAR contains only 163 fishing images compared to its largest class of 520 images). Furthermore, both COCO and BAR exhibit intra-class diversity; the "racing" category includes bikes, motorcycles, runners, and a wide variety of vehicles, and COCO objects occur with different angles and coloring. This diversity also introduces bias into the dataset, albeit unintentional and unaccounted for. The mean group sample uncertainties extracted from Bayesian ResNet18 models trained on each dataset reflect this as well, as shown in Figure 4. While this entangled experimental setup makes evaluation of the impact of de-biasing methods more difficult, the scenario is certainly realistic given the state of real-world visual datasets. Instead of explicitly disentangling the bias sources, sharpening trusts that the posterior adequately expresses its own shortages in information. Thus, sharpening considers class imbalance, intra-class diversity, unintentional biases, and known biases simultaneously. ### Training and Inference Optimal parameters for cSG-MCMC are determined via grid search for initial step sizes {0.01 0.05, 0.1, 0.5}, cycle lengths {150, 200, 300, 400, 500, 600, 700}, and Gaussian noise control parameter \(\alpha\in\{\)0.1, 0.3, 0.5, 0.7}. We fixed each schedule to 2 cycles and 3 moments sampled per sampling phase. Batch sizes for the baseline Bayesian models were fixed at 128 for training, and 64 for the sharpening procedure due to memory constraints (32 for BAR due to larger image size). Validation accuracy was used to determine stopping points and optimal hyper-parameters for both baseline Bayesian models and the sharpening procedure. Training took place on several IBM Power 9 dual-CPU nodes with 4 NVIDIA V100 GPUs. We refer readers to the Appendix for the optimal parameters for all experiments. Following methodology reported in [35], we reduce the kernel size of the first convolutional layer of ResNet18 from 7 to 3 for COCO due to the small image size (64 x 64). We also initialize the priors for the BAR Bayesian ResNet18 models using the weights from a deterministic ResNet18 trained on an ImageNet subset of 100 classes. The sharpening procedure requires keeping a handle on each Monte Carlo sample from \(p(\mathbf{\theta}\mid D,\mathbf{x})\), and back-propagating on each of these samples for every iteration. Thus, the procedure has time complexity of \(O(M\cdot N\cdot K)\) for \(M\) posterior samples, \(K\) multiplication operations as required for the network architecture, and \(N\) iterations, versus \(O(N\cdot K)\) for a deterministic network. ## 5 Results and Discussion For a fair comparison against prior reported results on these datasets, we use a ResNet18 throughout the experiments. We compare against several explicit and implicit mitigation methods, separated in each table: UpWt, gDRO, and PGI for explicit approaches, and the baseline ERM, SD and OccamNet for implicits. We also include EpiWt, another implicit method, due to its similarity to our approach in leveraging the epistemic uncertainties of a Bayesian neu \begin{table} \begin{tabular}{l c c c} \hline \hline Architecture+Method & Biased MNIST & COCO & BAR \\ \hline \multicolumn{4}{c}{_Explicit method_} \\ ResNet+UpWt & \(37.7\pm 1.6\) & \(35.2\pm 0.4\) & \(51.1\pm 1.9\) \\ ResNet+gDRO [30] & \(19.2\pm 0.9\) & \(35.3\pm 0.1\) & \(38.7\pm 2.2\) \\ ResNet+PGI [1] & \(\mathbf{48.6\pm 0.7}\) & \(\mathbf{42.7\pm 0.6}\) & \(\mathbf{53.6\pm 0.9}\) \\ \hline \multicolumn{4}{c}{_Implicit method results_} \\ ResNet+ERM & \(36.8\pm 0.7\) & \(35.6\pm 1.0\) & \(51.3\pm 1.9\) \\ ResNet+SD [29] & \(37.1\pm 1.0\) & \(35.4\pm 0.5\) & \(51.3\pm 2.3\) \\ OccamResNet [35] & \(\mathbf{65.0\pm 1.0}\) & \(\mathbf{43.4\pm 1.0}\) & \(52.6\pm 1.9\) \\ \multicolumn{4}{c}{BayResNet+EpiWt [36]} & \(34.4\pm 1.1\) & \(34.4\pm 0.8\) & \(52.1\pm 1.5\) \\ \multicolumn{4}{c}{- BayResNet+Sharpen} & \(38.6\pm 0.6\) & \(34.9\pm 0.6\) & \(\mathbf{53.9\pm 0.7}\) \\ \hline \hline \end{tabular} \end{table} Table 1: Unbiased test set accuracies comparing Bay-ResNet against current debiasing methods. **First, second** and third best results are formatted. Figure 4: Mean uncertainties for subgroups of each test dataset, showing bias-induced discrepancies, but also increased uncertainties arising from a variety of other sources, some of which may be unintentional bias present in the data. ral network. We consider two baselines: (1) empirical risk minimization (ERM) of a deterministic ResNet18, and (2) a Bayesian ResNet18, both trained with normal cross entropy loss and no bias mitigation. The sharpening procedure gives competitive results on BAR, and comparable performance on Biased MNIST (Table 1). We observe poorer performance on the COCO dataset. Posterior estimate sharpening always increases model fairness when compared to its baseline Bayesian starting point. As demonstrated in Table 3, the Bayesian ResNet struggles with both the out-of-distribution and unbiased background test sets, with differences of -3.5% and -2.6% respectively compared to the deterministic ERM baseline. Building on the BayResNet, the sharpening thus starts with a _more unfair model_ than methods based on a deterministic ERM model, giving it a distinct disadvantage. Assuming the discrepancy in performance is somewhat due to the stochastic nature of the network, BayResNet+EpiWt would also have a disadvantage but does better on the biased test set than BayResNet+Sharpen; nonetheless, as is consistent across datasets, BayResNet+Sharpen still does better than BayResNet+EpiWt on the two unbiased test sets. Regardless, this highlights a weakness of the sharpening approach. We consider the vast topic of comparing the predictive performances of deterministic and Bayesian neural networks out of the scope of this paper, but acknowledge that Bayesian neural networks can struggle to match deterministic benchmarks, which directly affects the sharpening method. We weigh these sacrifices in performance against the added benefit of quantified prediction uncertainty estimates, which deterministic models fail to communicate altogether. BAR is a counterexample, where the Bayesian baseline outperforms or does at least as well as the deterministic one across class groups. The most realistic and complex dataset of the three, BAR is neither texturally simple like Biased MNIST nor synthetically created and low-resolution like COCO-on-Places. The posterior estimate sharpening method performs well on BAR (Table 2), especially considering the large discrepancy in performances across classes and methods. Notably, while various methods do well in two or three classes, BayResNet+Sharpen has good performance across the majority of classes (5/7 classes). For this dataset, perhaps because of its ability to regularize despite the small dataset size and substantial intra-class diversity, the baseline BayResNet provides a strong starting point for the sharpening method. Table 4 shows the majority/minority group accuracies and bias-induced accuracy gap for the six bias variables in Biased MNIST. Compared to the baseline ERM, the sharpened model decreases the accuracy gaps between majority and minority groups across the dataset for 4 out of 6 of the biases (texture, texture color, letter, and letter color). While BayResNet+Sharpen results on Biased MNIST are not as competitive, results demonstrate that the sharpening objective aims at increasing model fairness rather than simply \begin{table} \begin{tabular}{l c c c c c c c} \hline \hline Methods & Overall & Climbing & Diving & Fishing & Pole & \multirow{2}{*}{Racing} & \multirow{2}{*}{Throwing} \\ & \multicolumn{6}{c}{_Explicit method results_} \\ ResNet+UpWt & 51.1 \(\pm\)1.9 & 61.7 \(\pm\)13.2 & **43.9**\(\pm\)5.8 & 42.3 \(\pm\)8.3 & 52.3 \(\pm\)7.4 & 67.9 \(\pm\)6.7 & 28.2 \(\pm\)12.8 \\ ResNet+gDRO [30] & 38.7 \(\pm\)2.2 & 49.5 \(\pm\)8.5 & 40.3 \(\pm\)8.4 & 44.0 \(\pm\)10.4 & 39.9 \(\pm\)7.1 & 41.7 \(\pm\)4.0 & 13.5 \(\pm\)5.9 \\ ResNet+PGI [1] & 53.6 \(\pm\)0.9 & 61.2 \(\pm\)10.4 & 38.4 \(\pm\)4.1 & 42.9 \(\pm\)8.4 & **73.3**\(\pm\)3.7 & 68.9 \(\pm\)5.9 & 23.5 \(\pm\)1.9 \\ OccamResNet+UpWt & 52.2 \(\pm\)1.4 & 57.9 \(\pm\)1.8 & 35.7 \(\pm\)7.5 & 51.8 \(\pm\)11.2 & 64.3 \(\pm\)8.8 & 71.8 \(\pm\)3.8 & 27.4 \(\pm\)3.5 \\ OccamResNet+gDRO [30] & 52.9 \(\pm\)0.8 & 51.2 \(\pm\)9.6 & 42.8 \(\pm\)8.2 & 52.3 \(\pm\)5.1 & 63.5 \(\pm\)7.3 & 74.2 \(\pm\)5.2 & 25.3 \(\pm\)4.5 \\ OccamResNet+PGI [1] & **55.9**\(\pm\)0.7 & 64.2 \(\pm\)5.1 & **52.3**\(\pm\)6.4 & 51.4 \(\pm\)8.3 & 64.4 \(\pm\)4.1 & 70.9 \(\pm\)8.1 & 18.6 \(\pm\)6.8 \\ \hline \multicolumn{8}{c}{_Implicit method results_} \\ ResNet+ERM & 51.3 \(\pm\)1.9 & 69.5 \(\pm\)7.5 & 29.2 \(\pm\)1.8 & 39.9 \(\pm\)16.2 & 55.5 \(\pm\)6.4 & 75.6 \(\pm\)5.6 & **31.8**\(\pm\)4.3 \\ ResNet+SD [29] & 51.3 \(\pm\)2.3 & 62.1 \(\pm\)7.5 & 35.8 \(\pm\)2.0 & 51.2 \(\pm\)6.4 & 62.4 \(\pm\)9.2 & 71.6 \(\pm\)10.0 & 18.5 \(\pm\)6.7 \\ OccamResNet [30] & 52.6 \(\pm\)1.9 & 59.3 \(\pm\)3.8 & 42.3 \(\pm\)7.5 & 44.6 \(\pm\)14.9 & 60.5 \(\pm\)8.6 & 74.1 \(\pm\)7.2 & 22.1 \(\pm\)3.9 \\ OccamResNet+SD [29] & 52.3 \(\pm\)2.4 & 56.4 \(\pm\)6.8 & 34.3 \(\pm\)5.8 & **55.4**\(\pm\)7.4 & **69.1**\(\pm\)4.9 & 72.9 \(\pm\)4.2 & 21.8 \(\pm\)2.1 \\ BayResNet & 52.7 \(\pm\)2.6 & **71.1**\(\pm\)2.7 & 28.3 \(\pm\)10.3 & 54.8 \(\pm\)8.2 & 54.2 \(\pm\)3.3 & **78.0**\(\pm\)3.9 & **31.8**\(\pm\)2.6 \\ BayResNet+EpiWt [36] & 52.1 \(\pm\)1.6 & 67.9 \(\pm\)2.2 & 27.9 \(\pm\)5.1 & 51.6 \(\pm\)5.4 & 59.8 \(\pm\)3.5 & 76.2 \(\pm\)0.4 & 30.0 \(\pm\)2.9 \\ BayResNet+Sharpen & **53.9**\(\pm\)0.7 & **72.1**\(\pm\)2.0 & 32.1 \(\pm\)3.2 & **59.5**\(\pm\)2.3 & 52.7 \(\pm\)2.7 & **79.6**\(\pm\)0.7 & **32.6**\(\pm\)2.9 \\ \hline \hline \end{tabular} \end{table} Table 2: Overall and per-class accuracies on BAR, showing large discrepancies in performance across methods and classes. \begin{table} \begin{tabular}{l c c c} \hline \hline Architecture+Method & Biased & Unseen & Seen, but \\ & Bgs & Bgs & Unbiased \\ \hline \multicolumn{4}{c}{_Explicit method results_} \\ ResNet+PGI [1] & 77.5 \(\pm\)0.6 & 52.8 \(\pm\)0.7 & 42.7 \(\pm\)0.6 \\ OccamResNet+PGI [1] & 82.8 \(\pm\)0.6 & **55.3**\(\pm\)1.3 & **43.6**\(\pm\)0.6 \\ \hline \multicolumn{4}{c}{_Implicit method results_} \\ ResNet+ERM & 84.9 \(\pm\) 0.5 & 53.2 \(\pm\)0.7 & 35.6 \(\pm\)1.0 \\ OccamResNet [35] & 84.0 \(\pm\)1.0 & **55.8**\(\pm\)1.2 & **43.4**\(\pm\)1.0 \\ \multicolumn{4}{c}{BayResNet} \\ BayResNet+EpiWt [36] & **85.8**\(\pm\)0.1 & 50.3 \(\pm\)1.1 & 34.4 \(\pm\)0.8 \\ \hline BayResNet+Sharpen & **85.6**\(\pm\)0.6 & 51.2 \(\pm\)0.2 & 34.9 \(\pm\)0.6 \\ \hline \hline \end{tabular} \end{table} Table 3: Accuracies on all three test splits of COCO-on-Places: biased backgrounds (Bgs), unseen backgrounds, and seen but unbiased backgrounds. rewarding accuracy gains on the majority groups. We consider the impact of PCGrad on the multi-task loss in the ablation study shown in Table 5. For weighted loss \(L+k\cdot L_{s}\), scalar weight \(k\) is chosen using a grid search in range \(k=2\) to \(k=10\) with optimal \(k\) being in range 3 to 5 for all datasets with negligible impact for \(k<3\) and declining accuracy (biased and unbiased sets) for values \(k>5\); this loss simply adds the two losses together regardless of conflict, with a fixed weighting term across all samples. Finally, uncertainty distributions across training sets do not collapse under PCGrad sharpening, so sample uncertainty estimates extracted at inference time may still be useful for triage or other purposes in high-risk scenarios. ## 6 Conclusion The visual datasets heavily relied on by today's deep neural networks are complex, feature-dense, and full of unidentified biases and spurious correlations. While no single bias mitigation method has thus far been unilaterally successful, a wide variety of ideas in recent literature make promising advances in both explicit and implicit mitigation. Our posterior estimate sharpening method adds to this body of work by implicitly exploiting the relationship between minority samples and epistemic uncertainties. We have demonstrated competitive performance on one benchmark, and comparable results on another. Further exploration is required to better understand when and why Bayesian neural networks struggle with respect to deterministic networks within the context of bias mitigation, and why the performances of mitigation methods vary across datasets. This perhaps calls for a better disentangling of features and correlations within training and test datasets used for evaluation, which we leave for future consideration. ## 7 Acknowledgements The first author is a recipient of an Ezra Rabin Scholarship. Training was carried out on Bede, a facility of the N8 Centre of Excellence in Computationally Intensive Research (N8 CIR) 3. We would like to acknowledge the respective authors for their publicly available code for cSG-MCMC 4, network dissection 5, PCGrad [39], and OccamNets 6 from which we have modified code for our work. We thank Robik Shrestha for kindly providing the checkpoint for the ResNet18 trained on the ImageNet-100 subset, which was used as the prior for the BAR models. Finally, special thanks to Jose Sosa and Mohammed Alghamdi from the School of Computing's Computer Vision Group for critical feedback and many great discussions. Footnote 3: [https://n8cir.org.uk/bede/](https://n8cir.org.uk/bede/) Footnote 4: [https://github.com/ruqizhang/csgmcmc](https://github.com/ruqizhang/csgmcmc) Footnote 5: [https://github.com/davidbau/dissect](https://github.com/davidbau/dissect) Footnote 6: [https://github.com/erobic/occam-nets-v1](https://github.com/erobic/occam-nets-v1)
2303.03169
A Unified Algebraic Perspective on Lipschitz Neural Networks
Important research efforts have focused on the design and training of neural networks with a controlled Lipschitz constant. The goal is to increase and sometimes guarantee the robustness against adversarial attacks. Recent promising techniques draw inspirations from different backgrounds to design 1-Lipschitz neural networks, just to name a few: convex potential layers derive from the discretization of continuous dynamical systems, Almost-Orthogonal-Layer proposes a tailored method for matrix rescaling. However, it is today important to consider the recent and promising contributions in the field under a common theoretical lens to better design new and improved layers. This paper introduces a novel algebraic perspective unifying various types of 1-Lipschitz neural networks, including the ones previously mentioned, along with methods based on orthogonality and spectral methods. Interestingly, we show that many existing techniques can be derived and generalized via finding analytical solutions of a common semidefinite programming (SDP) condition. We also prove that AOL biases the scaled weight to the ones which are close to the set of orthogonal matrices in a certain mathematical manner. Moreover, our algebraic condition, combined with the Gershgorin circle theorem, readily leads to new and diverse parameterizations for 1-Lipschitz network layers. Our approach, called SDP-based Lipschitz Layers (SLL), allows us to design non-trivial yet efficient generalization of convex potential layers. Finally, the comprehensive set of experiments on image classification shows that SLLs outperform previous approaches on certified robust accuracy. Code is available at https://github.com/araujoalexandre/Lipschitz-SLL-Networks.
Alexandre Araujo, Aaron Havens, Blaise Delattre, Alexandre Allauzen, Bin Hu
2023-03-06T14:31:09Z
http://arxiv.org/abs/2303.03169v2
# A Unified Algebraic Perspective on Lipschitz Neural Networks ###### Abstract Important research efforts have focused on the design and training of neural networks with a controlled Lipschitz constant. The goal is to increase and sometimes guarantee the robustness against adversarial attacks. Recent promising techniques draw inspirations from different backgrounds to design 1-Lipschitz neural networks, just to name a few: convex potential layers derive from the discretization of continuous dynamical systems, Almost-Orthogonal-Layer proposes a tailored method for matrix rescaling. However, it is today important to consider the recent and promising contributions in the field under a common theoretical lens to better design new and improved layers. This paper introduces a novel algebraic perspective unifying various types of 1-Lipschitz neural networks, including the ones previously mentioned, along with methods based on orthogonality and spectral methods. Interestingly, we show that many existing techniques can be derived and generalized via finding analytical solutions of a common semidefinite programming (SDP) condition. We also prove that AOL biases the scaled weight to the ones which are close to the set of orthogonal matrices in a certain mathematical manner. Moreover, our algebraic condition, combined with the Gershgorin circle theorem, readily leads to new and diverse parameterizations for 1-Lipschitz network layers. Our approach, called SDP-based Lipschitz Layers (SLL), allows us to design non-trivial yet efficient generalization of convex potential layers. Finally, the comprehensive set of experiments on image classification shows that SLLs outperform previous approaches on certified robust accuracy. Code is available at github.com/araujoalexandre/Lipschitz-SLL-Networks. + Footnote †: Equal contribution. ## 1 Introduction The robustness of deep neural networks is nowadays a great challenge to establish confidence in their decisions for real-life applications. Addressing this challenge requires guarantees on the stability of the prediction, with respect to adversarial attacks. In this context, the Lipschitz constant of neural networks is a key property at the core of many recent advances. Along with the margin of the classifier, this property allows us to certify the robustness against worst-case adversarial perturbations. This certification is based on a sphere of stability within which the decision remains the same for any perturbation inside the sphere (Tsuzuku et al., 2018). The design of 1-Lipschitz layers provides a successful approach to enforce this property for the whole neural network. For this purpose, many different techniques have been devised such as spectral normalization (Miyato et al., 2018; Farnia et al., 2019), orthogonal parameterization (Trockman et al., 2021; Li et al., 2019; Singla et al., 2021; Yu et al., 2022; Xu et al., 2022), Convex Potential Layers (CPL) (Meunier et al., 2022), and Almost-Orthogonal-Layers (AOL) (Prach et al., 2022). While all these techniques share the same goal, their motivations, and derivations can greatly differ, delivering different solutions. Nevertheless, their raw experimental comparison fails to really gain insight into their peculiar performance, soundness, and in the end their possible complementarity. Therefore a question acts as a barrier for an in-depth analysis and future development: _Are there common principles underlying the developments of 1-Lipschitz Layers?_ In this paper, we propose a novel perspective to answer this question based on a unified Semidefinite Programming (SDP) approach. We introduce a common algebraic condition underlying various types of methods like spectral normalization, orthogonality-based methods, AOL, and CPL. Our key insight is that this condition can be formulated as a unifying and simple SDP problem, and that the development of 1-Lipschitz architectures systematically arise by finding "analytical solutions" of this SDP. Our main contributions are summarized as follows. * We provide a unifying algebraic perspective for 1-Lipschitz network layers by showing that existing techniques such as spectral normalization, orthogonal parameterization, AOL, and CPL can all be recast as a solution of the same simple SDP condition (Theorem 1 and related discussions). Consequently, any new analytical solutions of our proposed SDP condition will immediately lead to new 1-Lipschitz network structures. * Built upon the above algebraic viewpoint, we give a rigorous mathematical interpretation for AOL explaining how this method promotes "almost orthogonality" in training (Theorem 2). * Based on our SDPs, a new family of 1-Lipschitz network structures termed as SDP-based Lipschitz layers (SLL) has been developed. Specifically, we apply the Gershgorin circle theorem to obtain some new SDP solutions, leading to non-trivial extensions of CPL (Theorem 3). We derive new SDP conditions to characterize SLL in a very general form (Theorem 4). * Finally, we show, by a comprehensive set of experiments, that our new SDP-based Lipschitz layers outperform previous approaches on certified robust accuracy. Our work is inspired by Fazlyab et al. (2019) that develops SDP conditions for numerical estimation of Lipschitz constants of given neural networks. A main difference is that we focus on "analytical SDP solutions" which can be used to characterize 1-Lipschitz network structures. ## 2 Related Work In recent years, certified methods have been central to the development of trustworthy machine learning and especially for deep learning. _Randomized Smoothing_(Cohen et al., 2019; Salman et al., 2019) is one of the first defenses to offer provable robustness guarantees. The method simply extends a given classifier by the smart introduction of random noise to enhance the robustness of the classifier. Although this method offers an interesting level of certified robustness, it suffers from important downsides such as the high computational cost of inference and some impossibility results from information-theory perspective (Yang et al., 2020; Kumar et al., 2020). Another approach to certify the robustness of a classifier is to control its Lipschitz constant (Hein et al., 2017; Tsuzuku et al., 2018). The main idea is to derive a certified radius in the feature space by upper bounding the margin of the classifier. See Proposition 1 of Tsuzuku et al. (2018) for more details. This radius, along with the Lipschitz constant of the network can certify the robustness. In order to reduce the Lipschitz constant and have a non-trivial certified accuracy, Tsuzuku et al. (2018) and Leino et al. (2021) both upper bound the margin via computing a bound on the global Lipschitz constant, however, these bounds have proved to be loose. Instead of upper bounding the global Lipschitz constant, Huang et al. (2021) leverages _local_ information to get tighter bound on the Lipschitz constant. On the other hand, other works, instead of upper bounding the local or global Lipschitz, devised neural networks architecture that are provably 1-Lipschitz. One of the first approaches in this direction consists of normalizing each layer with its spectral norm (Miyato et al., 2018; Farnia et al., 2019). Each layer is, by construction, 1-Lipschitz. Later, a body of research replaces the normalized weight matrix by an orthogonal matrix. It improves upon the spectral normalization method by adding the gradient preservation (Li et al., 2019; Trockman et al., 2021; Singla et al., 2021; Yu et al., 2022; Xu et al., 2022). These methods constrain the parameters by orthogonality during training. Specifically, the Cayley transform can be used to constrain the weights (Trockman et al., 2021) and, in a similar fashion, SOC (Singla et al., 2021) parameterizes their layers with the exponential of a skew symmetric matrix making it orthogonal. To reduce cost, Trockman et al. (2021), Yu et al. (2022), and Xu et al. (2022) orthogonalize their convolutional kernel in the Fourier domain. More recently, a work by Meunier et al. (2022) has studied Lipschitz networks from a dynamical system perspective. Starting from the continuous view of a residual network, they showed that the parameterization with the Cayley transform (Trockman et al., 2021) and SOC (Singla et al., 2021) correspond respectively to two specific discretization schemes of the continuous flow. Furthermore, a new layer is derived from convex potential flows to ensure the 1-Lipschitz property1: Footnote 1: We reverse the transposition from the original layer to have a consistent notation in the rest of the article. \[z=x-\frac{2}{\|W\|_{2}^{2}}W\sigma(W^{\top}x+b), \tag{1}\] where \(\|W\|_{2}\) is the spectral norm of the weight matrix \(W\) and \(\sigma\) is the ReLU activation function. In general, the training of orthogonal layers can be expensive. The Cayley approach involves a matrix inversion, and the implementation of SOC requires either an SVD or an iterative Taylor expansion. The CPL approach can be more efficient, although the computation of \(\|W\|_{2}\) is still needed. A recent work, _Almost-Orthogonal-layer_ (AOL) (Prach et al., 2022) came up with a middle ground: a new normalization which makes the layer 1-Lipschitz by favoring orthogonality. The fully-connected AOL layer is defined as \(z=WDx+b\) where \(D\) is a diagonal matrix given by2: Footnote 2: For simplicity, we assume all the columns of \(W\) have at least one non-zero entry. Then (2) is well defined. \[D=\mathrm{diag}\left(\sum_{j}|W^{\top}W|_{ij}\right)^{-\frac{1}{2}} \tag{2}\] They demonstrated that this layer is 1-Lipschitz and they empirically show that, after training, the Jacobian of the layer (with respect to \(x\)) is almost orthogonal, hence facilitating the training. Another source of inspiration is the application of convex programs for robustness certification of neural networks (Wong et al., 2018; Raghunathan et al., 2018; Fazlyab et al., 2019; Revay et al., 2020; Fazlyab et al., 2020; Wang et al., 2022). The most relevant work is Fazlyab et al. (2019), which leverages the quadratic constraint approach from control theory (Megretski et al., 1997) to formulate SDPs for estimating the global Lipschitz constant of neural networks numerically. It is possible to solve such SDPs numerically for training relatively small Lipschitz networks (Pauli et al., 2021). However, due to the restrictions of existing SDP solvers, scalability has been one issue when deploying such approaches to deep learning problems with large data sets. Our focus is on the design of Lipschitz network structures, and we avoid the scalability issue via solving SDPs analytically. ## 3 Background Notation.The \(n\times n\) identity matrix and the \(n\times n\) zero matrix are denoted as \(I_{n}\) and \(0_{n}\), respectively. The subscripts will be omitted when the dimension is clear from the context. When a matrix \(P\) is negative semidefinite (definite), we will use the notation \(P\preceq(\prec)0\). When a matrix \(P\) is positive semidefinite (definite), we will use the notation \(P\succeq(\succ)0\). Let \(e_{i}\) denote the vector whose \(i\)-entry is \(1\) and all other entries are \(0\). Given a collection of scalars \(\{a_{i}\}_{i=1}^{n}\), we use the notation \(\mathrm{diag}(a_{i})\) to denote the \(n\times n\) diagonal matrix whose \((i,i)\)-th entry is \(a_{i}\). For a matrix \(A\), the following notations \(A^{\mathsf{T}}\), \(\|A\|_{2}\), \(\mathrm{tr}(A)\), \(\sigma_{\min}(A)\), \(\|A\|_{F}\), and \(\rho(A)\) stand for its transpose, largest singular value, trace, smallest singular value, Frobenius norm, and spectral radius, respectively. Lipschitz functions.A function \(f:\mathbb{R}^{n}\to\mathbb{R}^{m}\) is \(L\)-Lipschitz with respect to the \(\ell_{2}\) norm iff it satisfies \(\|f(x)-f(y)\|\leq L\|x-y\|\) for all \(x,y\in\mathbb{R}^{n}\), where \(\|\cdot\|\) stands for the \(\ell_{2}\) norm. An important fact is that the robustness of a neural network can be certified based on its Lipschitz constant (Tsuzuku et al., 2018). In this paper, we are interested in the case where \(L=1\). Specifically, we consider the training of 1-Lipschitz neural networks. If each layer of a neural network is 1-Lipschitz, then the entire neural network is also 1-Lipschitz. The Lipschitz constant also satisfies the triangle inequality, and hence convex combination will preserve the 1-Lipschitz property. Matrix cones: Positive semidefiniteness and diagonal dominance.Let \(\mathbf{S}^{n}\) denote the set of all \(n\times n\) real symmetric matrices. Let \(\mathbf{S}^{n}_{+}\subset\mathbf{S}^{n}\) be the set of all \(n\times n\) symmetric positive semidefinite matrices. It is well known that \(\mathbf{S}^{n}_{+}\) is a closed-pointed convex cone in \(\mathbf{S}^{n}\). With the trace inner product, \(\mathbf{S}^{n}_{+}\) is also self-dual. Consider two symmetric matrices \(A\) and \(B\) such that \(A\succeq B\in\mathbf{S}^{n}\), then we have \(A-B\in\mathbf{S}^{n}_{+}\), and \(\operatorname{tr}(A-B)\) provides a distance measure between \(A\) and \(B\). In addition, we have \(\|A-B\|_{F}\leq\operatorname{tr}(A-B)\). Finally, the set of all \(n\times n\) real symmetric diagonally dominant matrices with non-negative diagonal entries is represented by \(\mathbf{D}^{n}\). It is known that \(\mathbf{D}^{n}\) forms a closed, pointed, full cone (Barker et al., 1975). Based on the Gershgorin circle theorem (Horn et al., 2012), we know \(\mathbf{D}^{n}\subset\mathbf{S}^{n}_{+}\). It is also known that \(\mathbf{D}^{n}\) is smaller than \(\mathbf{S}^{n}_{+}\)(Barker et al., 1975). For any \(A\in\mathbf{D}^{n}\), we have \(A_{ii}\geq\sum_{j:j\neq i}|A_{ij}|\). It is important to require \(A_{ii}\geq 0\), and the set of real symmetric diagonally dominant matrices is not a cone by itself. ## 4 An Algebraic Unification of 1-Lipschitz Layers In this section, we present a unified algebraic perspective for various 1-Lipschitz layers (Spectral Normalization, Orthogonalization, AOL, and CPL) via developing a common SDP condition characterizing the Lipschitz property. Built upon our algebraic viewpoint, we also present a new mathematical interpretation explaining how AOL promotes orthogonality in training. ### The unifying Algebraic Condition First, we present an algebraic condition which can be used to unify the developments of existing techniques such as SN, AOL, and CPL. Our main theorem is formalized below. **Theorem 1**.: _For any weight matrix \(W\in\mathbb{R}^{m\times n}\), if there exists a nonsingular diagonal matrix \(T\) such that \(W^{\mathsf{T}}W-T\preceq 0\), then the two following statements hold true._ 1. _The mapping_ \(g(x)=WT^{-\frac{1}{2}}x+b\) _is_ \(1\)_-Lipschitz,_ 2. _The mapping_ \(h(x)=x-2WT^{-1}\sigma(W^{\mathsf{T}}x+b)\) _is_ \(1\)_-Lipschitz if_ \(\sigma\) _is ReLU,_ \(\tanh\) _or sigmoid._ The proof of the above theorem and some related control-theoretic interpretations are provided in the appendix. This theorem allows us to design different 1-Lipschitz layers just with various choices of \(T\), in two important cases: for a linear transformation with Statement 1, as well as for a residual and non-linear block with Statement 2. Moreover, for any given weight matrix \(W\), the condition \(W^{\mathsf{T}}W\preceq T\) is linear in \(T\), and hence can be viewed as an SDP condition with decision variable \(T\). To emphasize the significance of this theorem, we propose to derive existing methods used for designing 1-Lipschitz layers by choosing specific \(T\) for the SDP condition \(W^{\mathsf{T}}W\preceq T\). The 1-Lipschitz property is then automatically obtained. * Spectral Normalization (SN) corresponds to an almost trivial choice if we notice that \(W^{\mathsf{T}}W\preceq\|W^{\mathsf{T}}W\|_{2}I\preceq\|W\|_{2}^{2}I\). Hence with \(T=\|W\|_{2}^{2}I\), we build the SN layer \(g(x)=WT^{-\frac{1}{2}}x+b=\frac{1}{\|W\|_{2}}Wx+b\). * The Orthogonality-based parameterization is obtained by setting \(T=I\) and enforcing the equality \(W^{\mathsf{T}}W=T=I\). Then obviously \(g(x)=Wx+b\) is 1-Lipschitz. * AOL formula can be derived by letting \(T=\operatorname{diag}(\sum_{j=1}^{n}|W^{\mathsf{T}}W|_{ij})\). With this choice, we have \(T-W^{\mathsf{T}}W\in\mathbf{D}^{n}\subset\mathbf{S}^{n}_{+}\), hence \(W^{\mathsf{T}}W\preceq T\). Then Statement 1 in Theorem 1 implies that the AOL layer, written as \(g(x)=WT^{-\frac{1}{2}}x+b\), is 1-Lipschitz.3 Footnote 3: For ease of exposition, our main paper always assumes that all the columns of \(W\) have at least one non-zero entry such that (2) is well defined. To drop this assumption, we can use a variant of Theorem 1 which replaces the SDP condition with a bilinear matrix inequality condition. We will discuss this point in the appendix. * CPL follows the same SN choice \(T=\|W\|_{2}^{2}I\), but with Statement 2 of Theorem 1. Hence we derive a different function \(h(x)=x-\frac{1}{\|W\|_{2}^{2}}W\sigma(W^{\mathsf{T}}x+b)\) which is also 1-Lipschitz. The above discussion illustrates the benefit of expressing all these methods within the same theoretical framework, offering us a new tool to characterize the similarity between different meth ods. For instance, SN and CPL share the same choice of \(T=\|W\|_{2}^{2}I\). The difference between them is which statement is used. Hence CPL can be viewed as the "residual version" of SN. Clearly, the residual network structure allows CPL to address the gradient vanishing issue more efficiently than SN. With the same approach, we can readily infer from our unified algebraic condition what are the "residual" counterparts for orthogonality-based parameterization and AOL. For orthogonality-based parameterization, if we enforce \(W^{\mathsf{T}}W=T=I\) via methods such as SOC and ECO, then the function \(h(x)=x-2W\sigma(W^{\mathsf{T}}x+b)\) is 1-Lipschitz (by Statement 2 in Theorem 1). Finally, if we choose \(T=\operatorname{diag}\left(\sum_{j=1}^{n}|W^{\mathsf{T}}W|_{ij}\right)\), then the function \(h(x)=x-2W\operatorname{diag}\left(\sum_{j=1}^{n}|W^{\mathsf{T}}W|_{ij}\right)^ {-1}\sigma(W^{\mathsf{T}}x+b)\) is also 1-Lipschitz. Therefore it is straightforward to create new classes of 1-Lipschitz network structures from existing ones. Another important consequence of Theorem 1 is about new layer development. Any new nonsingular diagonal solution \(T\) for the SDP condition \(W^{\mathsf{T}}W-T\preceq 0\) immediately leads to new 1-Lipschitz network structures in the form of \(g(x)=WT^{-\frac{1}{2}}x+b\) or \(h(x)=x-2WT^{-1}\sigma(W^{\mathsf{T}}x+b)\). Therefore, the developments of 1-Lipschitz network structures can be reformulated as finding analytical solutions of the matrix inequality \(W^{\mathsf{T}}W\preceq T\) with nonsingular diagonal \(T\). As a matter of fact, the Gershgorin circle theorem can help to improve the existing choices of \(T\) in a systematic way. In Section 5, we will discuss such new choices of \(T\) and related applications to improve CPL. At this point, it is worth noticing that to develop deep Lipschitz networks, it is important to have analytical formulas of \(T\). The analytical formula of \(T\) will enable a fast computation of \(WT^{-\frac{1}{2}}\) or \(WT^{-1}\). Theorem 1 is powerful in building a connection between 1-Lipschitz network layers and the algebraic condition \(W^{\mathsf{T}}W\preceq T\). Next, we will look closer at this algebraic condition and provide a new mathematical interpretation explaining how AOL generates "almost orthogonal" weights. **Remark 1**.: _The proof of Statement 2 in Theorem 1 relies on (Fazlyab et al., 2019, Lemma 1), which requires the activation function \(\sigma\) to be slope-restricted on \([0,1]\). Therefore, Statement 2 cannot be applied to the case with \(\sigma\) being the GroupSort activation function (Anil et al., 2019). In contrast, Statement 1 can be used to build neural networks with any activation functions which are 1-Lipschitz._ ### A New Mathematical Interpretation for AOL In Prach et al. (2022), it is observed that AOL can learn "almost orthogonal" weights and hence overcome the gradient vanishing issue. As a matter of fact, the choice of \(T\) used in AOL is optimal in a specific mathematical sense as formalized with the next theorem. **Theorem 2**.: _Given any \(W\in\mathbb{R}^{m\times n}\) which does not have zero columns, define the set \(\mathbf{T}=\left\{T:T\text{ is nonsingular diagonal, and }T-W^{\mathsf{T}}W\in\mathbf{D}^{n}\right\}\). Then the choice of \(T\) for the AOL method actually satisfies_ \[T=\operatorname{diag}(\sum_{j=1}^{n}|W^{\mathsf{T}}W|_{ij})=\operatorname*{ arg\,min}_{T\in\mathbf{T}}\operatorname{tr}(I-T^{-\frac{1}{2}}W^{\mathsf{T}}WT^{- \frac{1}{2}})=\operatorname*{arg\,min}_{T\in\mathbf{T}}\lVert T^{-\frac{1}{2} }W^{\mathsf{T}}WT^{-\frac{1}{2}}-I\rVert_{F}.\] We defer the proof for the above result to the appendix. Here we provide some interpretations for the above result. Obviously, the quantity \(\lVert T^{-\frac{1}{2}}W^{\mathsf{T}}WT^{-\frac{1}{2}}-I\rVert_{F}\) provides a measure for the distance between the scaled weight matrix \(WT^{-\frac{1}{2}}\) and the set of \(n\times n\) orthogonal matrices. If \(\lVert T^{-\frac{1}{2}}W^{\mathsf{T}}WT^{-\frac{1}{2}}-I\rVert_{F}=0\), then the scaled weight \(WT^{-\frac{1}{2}}\) is orthogonal. If \(\lVert T^{-\frac{1}{2}}W^{\mathsf{T}}WT^{-\frac{1}{2}}-I\rVert_{F}\) is small, it means that \(WT^{-\frac{1}{2}}\) is "almost orthogonal" and close to the set of orthogonal matrices. Since we require \(W^{\mathsf{T}}W-T\preceq 0\), we know that \(I-T^{-\frac{1}{2}}W^{\mathsf{T}}WT^{-\frac{1}{2}}\) is a positive semidefinite matrix, and its trace provides an alternative metric quantifying the distance between \(WT^{-\frac{1}{2}}\) and the set of orthogonal matrices. Importantly, we have the following inequality: \[\lVert T^{-\frac{1}{2}}W^{\mathsf{T}}WT^{-\frac{1}{2}}-I\rVert_{F}\leq \operatorname{tr}(I-T^{-\frac{1}{2}}W^{\mathsf{T}}WT^{-\frac{1}{2}}).\] If \(\operatorname{tr}(I-T^{-\frac{1}{2}}W^{\mathsf{T}}WT^{-\frac{1}{2}})\) is small, then \(\lVert T^{-\frac{1}{2}}W^{\mathsf{T}}WT^{-\frac{1}{2}}-I\rVert_{F}\) is also small, and \(WT^{-\frac{1}{2}}\) is close to the set of orthogonal matrices. Therefore, one interpretation for Theorem 2 is that among all the nonsingular diagonal scaling matrices \(T\) satisfying \(T-W^{\mathsf{T}}W\in\mathbf{D}^{n}\), the choice of \(T\) used in AOL makes the scaled weight matrix \(WT^{-\frac{1}{2}}\) the closest to the set of orthogonal matrices. This provides a new mathematical explanation of how AOL can generate "almost orthogonal" weights. One potential issue for AOL is that \(\mathbf{D}^{n}\) is typically much smaller than \(\mathbf{S}^{n}_{+}\), and the condition \(T-W^{\mathsf{T}}W\in\mathbf{D}^{n}\) may be too conservative compared to the original condition \(T-W^{\mathsf{T}}W\in\mathbf{S}^{n}_{+}\) in Theorem 1. If we denote the set \(\hat{\mathbf{T}}=\left\{T:T\text{ is nonsingular diagonal, and }T-W^{\mathsf{T}}W\in\mathbf{S}^{n}_{+}\right\}\), then we have \(\arg\min_{T\in\hat{\mathbf{T}}}\operatorname{tr}(I-T^{-\frac{1}{2}}W^{\mathsf{ T}}WT^{-\frac{1}{2}})\leq\arg\min_{T\in\mathbf{T}}\operatorname{tr}(I-T^{- \frac{1}{2}}W^{\mathsf{T}}WT^{-\frac{1}{2}})\), and \(\arg\min_{T\in\hat{\mathbf{T}}}\lVert T^{-\frac{1}{2}}W^{\mathsf{T}}WT^{- \frac{1}{2}}-I\rVert_{F}\leq\arg\min_{T\in\hat{\mathbf{T}}}\lVert T^{-\frac{1 }{2}}W^{\mathsf{T}}WT^{-\frac{1}{2}}-I\rVert_{F}\). This leads to interesting alternative choices of \(T\) which can further promote orthogonality: \[T=\operatorname*{arg\,min}_{T\in\hat{\mathbf{T}}}\lVert T^{-\frac{1}{2}}W^{ \mathsf{T}}WT^{-\frac{1}{2}}-I\rVert_{F}\quad\text{or}\quad T=\operatorname*{ arg\,min}_{T\in\hat{\mathbf{T}}}\operatorname{tr}(I-T^{-\frac{1}{2}}W^{ \mathsf{T}}WT^{-\frac{1}{2}}) \tag{3}\] Although (3) may be solved as convex programs on small toy examples, it is not practical to use such choice of \(T\) for large-scale problems. It is our hope that our theoretical discussion above will inspire more future research on developing new practical choices of \(T\) for promoting orthogonality. ## 5 Extensions of CPL: The Power of Gershgorin circle theorem In this section, we extend the original CPL layer (5) to a new family of 1-Lipschitz network structures via providing new analytical solutions to our condition \(W^{\mathsf{T}}W\preceq T\). We term this general family of layers as SDP-based Lipschitz layers (SLL), since the condition \(W^{\mathsf{T}}W\preceq T\) can be viewed as an SDP for the decision variable \(T\). First of all, we extend the existing CPL (Eq. (1)) via applying more general choices of \(T\) with Theorem 1. From the discussion after Theorem 1, we already know that we can use the choice of \(T=\operatorname{diag}(\sum_{j=1}^{n}|W^{\mathsf{T}}W|_{ij})\) to replace the original choice \(T=\lVert W\rVert_{2}^{2}I\). In this section, we will strengthen CPL via an even more general choice of \(T\), which is based on a special version of Gershgorin circle theorem. Specifically, we will apply (Horn et al., 2012, Corollary 6.1.6) to show the following result. **Theorem 3**.: _Let \(W\) be the weight matrix. Suppose \(T\) is a nonsingular diagonal matrix. If there exists some diagonal matrix \(Q\) with all positive diagonal entries such that \((T-QW^{\mathsf{T}}WQ^{-1})\) is a real diagonally dominant matrix with diagonal entries being all positive, then \(T\succeq W^{\mathsf{T}}W\), and the function \(h(x)=x-2WT^{-1}\sigma(W^{\mathsf{T}}x+b)\) is 1-Lipschitz for \(\sigma\) being ReLU, \(\tanh\) or sigmoid._ We defer the proof of this result to the appendix. If we choose \(Q=I\), the above theorem just recovers the choice of \(T\) used in AOL, i.e. \(T=\operatorname{diag}(\sum_{j=1}^{n}|W^{\mathsf{T}}W|_{ij})\). However, it is expected that the use of more general \(Q\) will allow us to train a less conservative 1-Lipschitz neural network due to the increasing expressivity brought by these extra variables. We will present numerical results to demonstrate this. We also emphasize that \((T-QW^{\mathsf{T}}WQ^{-1})\) is typically not a symmetric matrix and hence is not in \(\mathbf{D}^{n}\) even when it only has non-negative eigenvalues. However, this does not affect our proof on the positive-semidefiniteness of \((T-W^{\mathsf{T}}W)\). Application of Theorem 3.We can parameterize \(Q^{-1}=\operatorname{diag}(q_{i})\) with \(q_{i}>0\). Then the \((i,j)\)-th entry of \(QW^{\mathsf{T}}WQ^{-1}\) is equal to \((W^{\mathsf{T}}W)_{ij}q_{j}/q_{i}\). Hence we can just set the diagonal entry of \(T\) as \[T_{ii}=\sum_{j=1}^{n}|(W^{\mathsf{T}}W)_{ij}q_{j}/q_{i}|=\sum_{j=1}^{n}|W^{ \mathsf{T}}W|_{ij}\frac{q_{j}}{q_{i}}. \tag{4}\] This leads to our new choice of \(T=\operatorname{diag}(\sum_{j=1}^{n}|W^{\mathsf{T}}W|_{ij}q_{j}/q_{i})\). Notice that the layer function \(h(x)=x-2WT^{-1}\sigma(W^{\mathsf{T}}x+b)\) has a residual network structure. Hence it is expected that vanishing gradient will not be an issue. Therefore, we can simultaneously optimize the training loss over \(W\) and \(\{q_{i}\}\). We will present a numerical study to demonstrate that such a training approach will allow us to generate competitive results on training certifiably robust classifiers. SDP conditions for more general network structures.It is also worth mentioning that the SDP condition in Theorem 1 can be generalized to address the following more general structure: \[h(x)=Hx+G\sigma(W^{\mathsf{T}}x+b), \tag{5}\] where \(H\) and \(G\) will be determined by the weight \(W\) in some manner, and the matrix dimensions are assumed to be compatible. If we choose \(H=I\) and \(G=-2WT^{-1}\), then (5) reduces to the residual network structure considered in Theorem 1. There are many other choices of \((H,G)\) which can also ensure (5) to be 1-Lipschitz. Our last theoretical result is a new SDP condition which generalizes Theorem 1 and provides a more comprehensive characterization of such choices of \((H,\bar{G})\). **Theorem 4**.: _Let \(n\) be the neuron number. For any non-negative scalars \(\{\lambda_{i}\}_{i=1}^{n}\), define_ \[\Lambda=\operatorname{diag}(\lambda_{1},\lambda_{2},\ldots,\lambda_{n}). \tag{6}\] _Suppose the activation function \(\sigma\) is ReLU or \(\tanh\) or sigmoid. If there exist non-negative scalars \(\{\lambda_{i}\}_{i=1}^{n}\) such that the following matrix inequality holds_ \[\begin{bmatrix}I-H^{\mathsf{T}}H&-H^{\mathsf{T}}G-W\Lambda\\ -G^{\mathsf{T}}H-\Lambda W^{\mathsf{T}}&2\Lambda-G^{\mathsf{T}}G\end{bmatrix}\succeq 0 \tag{7}\] _then the network layer (5) is \(1\)-Lipschitz, i.e., \(\|h(x)-h(y)\|\leq\|x-y\|\) for all \((x,y)\)._ The above theorem can be proved via modifying the argument used in Fazlyab et al. (2019, Theorem 1)4 and we defer the detailed proof to the appendix. On one hand, if we choose \(H=0\), then our condition (7) reduces to a variant of Theorem 1 in Fazlyab et al. (2019).5 On the other hand, for residual network structure with \(H=I\), we can choose \(T=2\Lambda^{-1}\) and \(G=-W\Lambda=-2WT^{-1}\) to reduce (7) to our original algebraic condition \(T\succeq W^{\mathsf{T}}W\). Therefore, Theorem 4 provides a connection between the SDP condition in Fazlyab et al. (2019) and our proposed simple algebraic condition in Theorem 1. It is possible to obtain new 1-Lipschitz network layers via providing new analytical solutions to (7). It is our hope that our proposed SDP condition (7) can lead to many more 1-Lipschitz network structures in the future. Footnote 4: As commented in Pauli et al. (2021), such a modification works as long as \(\Lambda\) is diagonal. ## 6 Experiments In this section, we present a comprehensive set of experiments with 1-Lipschitz neural networks based on our proposed _SDP-based Lipschitz Layer_. More specifically, we build 1-Lipschitz neural networks based on the following layer: \[h(x)=x-2W\operatorname{diag}\left(\sum_{j=1}^{n}|W^{\mathsf{T}}W|_{ij}q_{j}/q_ {i}\right)^{-1}\sigma(W^{\mathsf{T}}x+b), \tag{8}\] where \(W\) is a parameter matrix being either dense or a convolution, \(\{q_{i}\}\) forms a diagonal scaling matrix as described by Theorem 3, and \(\sigma(\cdot)\) is the ReLU nonlinearity function. We use the same architectures proposed by Meunier et al. (2022) with _small_, _medium_, _large_ and _xlarge_ sizes. The architecture consists of several Conv-SLL and Linear-SLL. For CIFAR-100, we use the Last Layer Normalization proposed by Singla et al. (2022b) which improves the certified accuracy when the number of classes becomes large. Note that the layer presented in Equation (8) can be easily implemented with convolutions following the same scaling as in Prach et al. (2022). Our experiments focus on the impact of the Lipschitz layer structures on certified robustness. This complements a recent study on other aspects (e.g. projection pooling) of robust networks (Singla et al., 2022a). \begin{table} \begin{tabular}{l r r r r r r r} \hline \hline \multirow{2}{*}{**Models**} & \multirow{2}{*}{**Natural**} & \multicolumn{3}{c}{**Provable Accuracy (\(\varepsilon\))**} & \multicolumn{2}{c}{**Number of**} & \multicolumn{1}{c}{**Time by**} \\ \cline{3-8} & & \multicolumn{1}{c}{**Accuracy**} & \multicolumn{1}{c}{\(\frac{36}{255}\)} & \multicolumn{1}{c}{\(\frac{72}{255}\)} & \multicolumn{1}{c}{\(\frac{108}{255}\)} & \multicolumn{1}{c}{\(1\)} & **Parameters** & **Epoch (s)** \\ \hline **GloRo**(Leino et al., 2021) & 77.0 & 58.4 & - & - & - & 8M & 6 \\ **Local-Lip-B**(Huang et al., 2021b) & 77.4 & 60.7 & 39.0 & 20.4 & - & 2.3M & 8 \\ **Cayley Large**(Trockman et al., 2021) & 74.6 & 61.4 & 46.4 & 32.1 & - & 21M & 30 \\ **SOC 20**(Singla et al., 2021) & 78.0 & 62.7 & 46.0 & 30.3 & - & 27M & 52 \\ **SOC + 20**(Singla et al., 2022b) & 76.3 & 62.6 & 48.7 & 36.0 & - & 27M & 52 \\ **CPL XL**(Meunier et al., 2022) & 78.5 & 64.4 & 48.0 & 33.0 & - & 236M & 163 \\ **AOL Large**(Pach et al., 2022) & 71.6 & 64.0 & 56.4 & 49.0 & 23.7 & 136M & 64 \\ \hline **SLL Small** & 71.2 & 62.6 & 53.8 & 45.3 & 20.4 & 41M & 20 \\ **SLL Medium** & 72.2 & 64.3 & 56.0 & 48.3 & 23.9 & 78M & 35 \\ **SLL Large** & 72.7 & 65.0 & 57.3 & 49.7 & 25.4 & 118M & 55 \\ **SLL X-Large** & 73.3 & 65.8 & 58.4 & 51.3 & 27.3 & 236M & 105 \\ \hline \hline \end{tabular} \end{table} Table 1: This table presents the natural, provable accuracy as well as the number of parameters and training time of several concurrent work and our SLL networks on CIFAR10 dataset. All results for SLL networks are the result of the average of 3 trainings. **Details on the architectures & Hyper-parameters.** Table 3 describes the detail of our Small, Medium, Large and X-Large architectures. We trained our networks with a batch size of 256 over 1000 epochs with the data augmentation used by. We use an Adam optimizer (Kingma et al., 2014) with \(0.01\) learning rate and parameters \(\beta_{1}\) and \(\beta_{2}\) equal to \(0.5\) and \(0.9\) respectively and no weight decay. We use a piecewise triangular learning rate scheduler to decay the learning rate during training. We use the CrossEntropy loss as in Prach et al. (2022) with a temperature of \(0.25\) and an offset value \(\frac{3}{2}\sqrt{2}\). **Results in terms of Natural and Certified Accuracy on CIFAR10/100.** First, we evaluate our networks (SLL) on CIFAR10 and CIAFR100 and compute the results against recent 1-Lipschitz neural network structures: Cayley, SOC, SOC+, CPL and AOL. We also compare SLL with two other Lipschitz training approaches (Leino et al., 2021; Huang et al., 2021b), which do not guarantee prescribed global Lipschitz bounds during the training stage. Table 1 presents the natural and certified accuracy with different radius of certification on CIFAR10. For a fair comparison, parameter number and training time per epoch for each method are also added to Table 1. Results on CIFAR100 are included in Table 2. We can see that our approach outperforms existing 1-Lipschitz architectures including AOL and CPL on certified accuracy for all values of \(\varepsilon\). We also observe that SLL-based 1-Lipschitz neural networks offer a good trade-off among previous approaches with respect to natural and certified accuracy. A detailed comparison is given below. **Advantages of SLL over Cayley/SOC.** In general, it is difficult to compare the expressive power of non-residual and residual networks. Hence we do not claim that with the same model size, SLL is more representative than Cayley or SOC which are not residual networks in the first place. However, we believe that the current choice of \(T\) in SLL is very easy to calculate and hence leads to a scalable approach that allows us to train very large models with a reasonable amount of time. For illustrative purposes, consider the comparison between SLL and Cayley in Table 1. We can see that SLL Small has more parameters than Cayley Large (41M vs. 21M) while being faster to train. Indeed, the Cayley approach involves computing an expensive orthogonal projection (with a matrix inverse), while SOC requires to the computation of several convolutions at training and inference (from 6 to 12) to compute the exponential of a convolution up to a desired precision. Hence the training time per epoch for Cayley Large and SOC is actually longer than SLL Small. While being faster to train SLL Small still outperforms Cayley Large and SOC for all three values of \(\varepsilon\). In general, we think it is fair to claim that our approach is more scalable than previous approaches based on orthogonal layers, and allows the use of larger networks which leads to improvements in certified robustness. \begin{table} \begin{tabular}{l l c c c c c} \hline \hline \multirow{2}{*}{**Datasets**} & \multirow{2}{*}{**Models**} & \multirow{2}{*}{**Natural**} & \multicolumn{4}{c}{**Provable Accuracy (\(\varepsilon\))**} \\ \cline{3-6} & & & \(\frac{36}{25}\) & \(\frac{72}{25}\) & \(\frac{108}{25}\) & \(1\) \\ \hline \multirow{8}{*}{CIFAR100} & **Cayley Large** (Trockman et al., 2021) & 43.3 & 29.2 & 18.8 & 11.0 & - \\ & **SOC 20** (Singla et al., 2021) & 48.3 & 34.4 & 22.7 & 14.2 & - \\ & **SOC+ 20** (Singla et al., 2022b) & 47.8 & 34.8 & 23.7 & 15.8 & - \\ & **CPL XL** (Meunier et al., 2022) & 47.8 & 33.4 & 20.9 & 12.6 & - \\ & **AOL Large** (Prach et al., 2022) & 43.7 & 33.7 & 26.3 & 20.7 & 7.8 \\ Advantages of SLL over AOL/CPL.With careful tuning of the offset value, SLL outperforms AOL for all values of \(\varepsilon\). We experiment with several offset values: \(\sqrt{2}\), \(\frac{3}{2}\sqrt{2}\) and \(2\sqrt{2}\). The detailed results for all these different offset values are deferred to Table 6 in the appendix. In general, the offset value offers a trade-off between natural accuracy and robustness, thus, by choosing the offset value properly, SLL Large already achieves better results than AOL Large (notice that the training time per epoch for these two is roughly the same). SLL X-Large has even more improvements. We can also see that SLL Large outperforms CPL XL for all values of \(\varepsilon\) while being faster to train. For larger value of \(\varepsilon\), the gain of SLL over CPL is remarkable (over 10%). Results on TinyImageNet.We have also implemented SLL on TinyImageNet (see Table 2). Previously, other 1-Lipschitz network structures including SOC, Cayley, AOL, and CPL have not been tested on TinyImageNet, and the state-of-the-art approach on TinyImageNet is the local Lipschitz bound approach (Huang et al., 2021). We can see that SLL significantly outperforms this local Lipschitz approach for larger values of \(\varepsilon\) (while generating similar results for the small \(\varepsilon\) case). Notice that the local Lipschitz approach (Huang et al., 2021) is quite different from other 1-Lipschitz network methods in the sense that it has no guarantees on the Lipschitz constant of the resultant network and hence does not generate 1-Lipschitz networks in the first place. Furthermore, given that this approach does not guarantee a Lipschitz bound during training, a lot more computation needs to be performed during inference, making the certification process very time consuming. Table 4 describes the inference time on TinyImageNet for this local Lipschitz approach and SLL X-large. Results on Empirical Robustness.We also provide results of our approach on empirical robustness against an ensemble of diverse parameter-free attacks (_i.e._, _AutoAttacks_) developed by Croce et al. (2020). Table 5 reports the empirical robustness accuracy for different levels of perturbations. Although _AutoAttacks_ is a strong empirical attack consisting of an ensemble of several known attacks: APGDCE, APGDLR, FAB (Croce et al., 2020) and Square (Andriushchenko et al., 2020). We can observe that the measure robustness is high and well above the certified radius. Indeed, on CIFAR10, we observe a robustness "gain" of up to 4.5%, 9.6%, 14.1% and 21.7% for respectively, 36, 72, 108 and 255 \(\varepsilon\)-perturbations. ## 7 Conclusion In this paper, we present a unifying framework for designing Lipschitz layers. Based on a novel algebraic perspective, we identify a common SDP condition underlying the developments of spectral normalization, orthogonality-based methods, AOL, and CPL. Furthermore, we have shown that AOL and CPL can be re-derived and generalized using our theoretical framework. From this analysis, we introduce a family of SDP-based Lipschitz layers (SLL) that outperforms previous work. In the future, it will be interesting to investigate more expressive structures of \(T\) and extending our contributions to address multi-layer neural networks. \begin{table} \begin{tabular}{l c} \hline \hline **Models** & **Inference Time** \\ \hline **Local-Lip-B** & 41 min \\ **SLL X-Large** & 8 sec \\ \hline \hline \end{tabular} \end{table} Table 4: Inference time for Local-Lip-B and SLL X-Large on the full TinyImageNet validation with 4 GPUs. \begin{table} \begin{tabular}{l c c c c c c c c} \hline \hline \multirow{2}{*}{**Models**} & \multicolumn{3}{c}{**CIFAR10 \(-\)_AutoAttack_ (\(\varepsilon\))} & \multicolumn{3}{c}{**CIFAR100 \(-\)_AutoAttack_ (\(\varepsilon\))} \\ \cline{2-9} & \(\frac{36}{255}\) & \(\frac{72}{255}\) & \(\frac{108}{255}\) & \(1\) & \(\frac{36}{255}\) & \(\frac{72}{255}\) & \(\frac{108}{255}\) & \(1\) \\ \hline **SLL Small** & 68.1 & 62.5 & 56.8 & 35.0 & 40.7 & 35.2 & 30.4 & 17.0 \\ **SLL Medium** & 69.1 & 63.8 & 58.4 & 37.0 & 41.5 & 36.4 & 31.5 & 17.9 \\ **SLL Large** & 69.8 & 64.5 & 59.1 & 37.9 & 42.1 & 37.1 & 32.6 & 18.7 \\ **SLL X-Large** & 70.3 & 65.4 & 60.2 & 39.4 & 42.7 & 37.8 & 33.2 & 19.5 \\ \hline \hline \end{tabular} \end{table} Table 5: The table describes the empirical robustness of our SLL-based classifiers on CIFAR10 ans CIFAR100 datasets. The empirical robustness is measured with _AutoAttacks_. All results are the average of 3 models. #### Acknowledgments This work was performed using HPC resources from GENCI-IDRIS (Grant 2021-AD011013259) and funded by the French National Research Agency (ANR SPEED-20-CE23-0025). A. Havens and B. Hu are generously supported by the NSF award CAREER-2048168.